text:
Wire.requestFrom() not a blocking function, even though it should be(?)
I'm working on creating a simple ACK/NACK handshake between 2 Arduino's that will essentially go like this:

Arduino 1 signals Arduino 0 it is available
Arduino 0 sends a connect byte to Arduino 1 (say, 'c')
Arduino 1 sends a confirmation byte to Arduino 0 (say, 's')

This seems simple enough, so what I'm doing to avoid any kind of multithreading or callback functions is to use Wire.requestFrom(). From the wiki, this function "requests" the device at the specified address to send data. From what I understand, this "request" simply entails the master device simply blocking until it receives the necessary data. It doesn't seem to send any signal to the slave device that it should send anything, just does a simple wait. As such, I created a simple demo of this handshake between the two devices as follows:
// slave
#include <Wire.h>

void setup() {
  Serial.begin(9600);
  Wire.begin(1);
  Wire.requestFrom(0, 1, false);
  Serial.println("finished");
}

// master
#include <Wire.h>

bool last = false;

void setup() {
  Serial.begin(9600);
  Wire.begin(0);
  pinMode(2, INPUT);
}

void loop() {
  if (digitalRead(2) && !last) {
    Wire.beginTransmission(1);
    Wire.write('c');
    Wire.endTransmission(1);
  } else if (!digitalRead(2)) {
    last = false;
  }
  delay(1000);
}

Here, the master code waits on a signal (pin 2) (which is given by Arduino 1) that it is available, and then on connect, will send one connect byte to Arduino 1. In Arduino 1 (slave)'s code, I've placed the requestFrom call that should block until Arduino 0 sends that connect byte.
The problem here is that it's not actually blocking. Even before I've gotten a chance to run the master's code, the slave's "finished" output has instantly triggered. Am I understanding this function incorrectly or is there something wrong in my implementation?

You completely misunderstand how I2C communication (that's what the Wire library does) works. I won't explain the full I2C interface here, since that is a bit too much for this answer.
Wire.requestFrom() doesn't block until it receives data. It will configure the I2C interface as master (when previously in slave mode this will be temporary). Then it enforces a start condition on the bus, sends the address of the slave and then sends a clock pulse for the acknowledgement bit. During this clock pulse the slave can pull the SDA line low and signal that way, that it is reachable. After that the master continues to generate the clock for all the bytes it wants, expecting the slave to control the SDA line. If the slave doesn't do that (for example because you didn't connect the onRequest() callback), then the received data will just be 1s (so each byte 0xFF).
So Wire.requestFrom() does only block for the time, that the transmission needs. If the slave doesn't acknowledge its address, the function will exit after that. The transaction will only need a few milliseconds either way.

avoid any kind of multithreading or callback functions

On AVR based Arduinos (like the Uno or Nano) multithreading isn't really a thing (besides using a time sharing library, but still on only one core), though callbacks from interrupts are. And as long as you use the Wire library (and with it the I2C hardware interface of the microcontroller) you have to use interrupts and thus callback functions. And honestly there is normally no reason not to do that.

Another problem with what you are currently doing it, that both Arduinos act as masters on the bus. No two masters can send on the bus at the same time. While the I2C protocol has a way to determine, which master can send first, this is often implemented rather buggy. I don't know how good the Wire library is with this currently, but you should avoid a multi-master setup if possible.

A minor problem: The I2C address space has some reserved sections for special use. You can start your slave addresses at 8 (refer to the I2C specification on the web). Address 0 is meant as a general call address, so for master-write transactions, which target every slave on the bus. You shouldn't have a slave with that address.

What to do now? Just implement the code with the Wire library as it is meant, including the onRequest() callback function. Refer to the master-read example of the Wire library. Set the second Arduino as master and the first as slave. On the second Arduino you can call Wire.requestFrom() with the slaves address. This will trigger the onReqest() callback function on the first Arduino, where you can use Wire.write() to let the library send the desired data back to the master. On the master (Arduino 2) you an then read that data via Wire.read(). And thats it.

Masters request data from the slave, not the other way around.
See http://gammon.com.au/i2c
Slaves set up a "receive" handler to be told that there is incoming data.
Wire.onReceive (receiveEvent);

From what I understand, this "request" simply entails the master device simply blocking until it receives the necessary data.

Yes, but you don't have this request on the master, you have it on the slave. There is your problem.


text:
Struggling to understand how Bluetooth serial is related to USB on Arduino
I've recently acquired a Bluetooth module to attach to my Arduino Uno, but I'm trying to draw parallels to the standard method of communication that I'm familiar with, which seems to be just directly reading or writing to sensors through methods like digitalRead and digitalWrite, respectively. Additionally however, it seems like it's also possible to connect to a serial console, through the Serial class. These make sense, and I've used both individually (serial console viewed by the built-in Serial window in Arduino IDE, and serial write done through Serial.print/println()).
However, in the Bluetooth module I purchased (HW-10), there are pinouts that connect to the TX/RX ports, which I've currently left unconnected since I'm not using the Bluetooth module or any other serial module. My question is, once I connect these, does this completely replace the connection through USB that is currently used to interface with the Uno?
If so, I had a set of specific functionalities in mind for whether these would be "replaced" by connecting the module through the 4 pinouts (TX, RX, VCC, GND):
1. Serial: Can I write and access the serial monitor through the IDE by connecting to 9600 baud, both in code and in the Serial Monitor
2. Pins: Do these connections also allow me to write and read signals from all of the pins, including analog and digital
3. Sending code: Can I still send code through Bluetooth without needing a USB connection?
Apologies if this question seems really obvious or specific, I'm confused as I've read a bunch of wording saying that the Bluetooth module uses a "serial connection", when I only understood serial functionality as being a method of outputting text, not controlling the Arduino. Thanks in advance for help!

Typically you would want to use the BT module by connecting it to a separate UART.  But since the UNO has only 1 UART you can't do this.  You CAN use SoftwareSerial however, which lets you use make a software based UART on normal digital IO pins.  Apparently it is possible to program over bluetooth though. https://create.arduino.cc/projecthub/mansurkamsur/upload-sketch-arduino-over-bluetooth-using-android-f1ce55

hmm, I don't actually know what a UART is; does this mean that I am unable to alter the state of pins? what about serial and sending code

I don't actually know what a UART is

UART (Universal Asynchronous Receiver Transmitter) is the technical term for the communication interface, which is called Serial in Arduino speak. It's often called UART, because that is more precise, since there are many different communication protocols, which also work serially (meaning transferring data bits one after another in contrast to parallel, where multiple bits are transferred simultaneously), like I2C, SPI or USB. All serial protocols, but totally different from the Arduino Serial interface. Yes, this is a bit confusing. I guess the Arduino term Serial was coined to make the learning curve less steep for beginners (hiding complexity can also make things confusing unfortunately).
So UART is the same as the Arduino Serial interface.

once I connect these, does this completely replace the connection through USB that is currently used to interface with the Uno?

Here it is good to know, how the USB communication works on the Uno. The microcontroller on the Uno (Atmega328p) does not have a native USB interface. So it cannot speak to USB itself. For that there is an extra microcontroller on the board (I think an Atmega32u4). This controller has a native USB interface and it acts as a USB to Serial bridge (it creates a virtual serial interface on the PC and translate between that and its physical Serial/UART interface). The Atmega328p (which you program with your code) has it's RX and TX pins connected to the RX and TX pins on the Atmega32u4, which can then translate between the Serial/UART protocol and the USB protocol. Thus the Atmega328p doesn't know anything about USB. I just talks via Serial/UART to the Atmega32u4. In fact it also doesn't know anything about bluetooth. Most bluetooth modules for Arduino are also just bluetooth-Serial bridges
Now you need to know, that Serial/UART is made for one-to-one connections. With multiple devices you can get problems, when multiple devices try to send data at the same time. I this case (BT module RX to Arduino TX and vice versa) you would get garbled data, if you try to simultaneously send data from bluetooth and USB to the Arduino. The signals would overlap on the Arduinos RX pin, corrupting the data.
That means, that you don't want to send from both interfaces. In fact it is the easiest way to just use one Serial/UART  interface for only one device. If you leave the Serial Monitor (or any other Serial communication program) closed on the PC, the PC will not interfere with the communication. Though you need to disconnect the bluetooth module, when you write your program to the Arduino, since this is done via Serial and you don't want it to meddle with the data.
So in result the bluetooth module will not "replace" the connection through USB. It will be added and it is your duty to prevent data corruption.

Serial: Can I write and access the serial monitor through the IDE by connecting to 9600 baud, both in code and in the Serial Monitor

Yes. You don't need to use 9600 baud necessarily. The only requirement is, that you use the same baud number in both sketch and Serial Monitor. That number just represents the speed, that the data is send in. Both sender and receiver need to agree on the same communication speed, or the receiver will not be able to read the data. Imagine someone talking to you, but talking twice the speed with that you are able to understand the words. You will not be able to understand much, because the speaker is just too fast. Either you would need to change your hearing/understanding speed or the sender needs to change it's speaking speed, to make the two match.
9600 baud is just one of the standard baudrates, though one of the lower ones. If you need it to be faster (maybe because you are sending much data in fast succession), you might want to use a higher baudrate.

Pins: Do these connections also allow me to write and read signals from all of the pins, including analog and digital

That is up to you. Serial/UART is just a communication interface. How it is used is up to you. You already have seen, that it is often used to output text for a user to read over the Serial interface, often used as a way to debug the code by sending specific text at specific places in the code. Since that connection works in both ways, you can also program the Arduino to receive commands over Serial/UART and then act upon them.
Here the overlaying communication protocol comes in. Serial/UART just transmits a series of bytes over its two lines. It doesn't care, what these bytes mean. It can be text (for example encoded via the ASCII standard, as the Serial Monitor does), or it can be just some binary data. Also there is no concept of "messages". There are only individual bytes and you don't have control over when exactly they are sent. So to make meaningful use of Serial/UART you need to use an extra communication protocol on top of Serial/UART, that the receiver understands.
When you send text to the Serial Monitor you are the receiver. Thus you would send text (because you can understand text) and a natural way for humans to distinguish individual messages is to use a delimiter character. In normal text that can be a period, though in this field going to a new line has somewhat evolved to the standard (so the delimiter character is the newline character '\n'). If you read the delimiter character (either yourself on the Serial Monitor, or the Arduino in your program), that marks the end of the message. You can also use that text based approach in your Arduino program (and I would say that is the easiest way). Though you don't need to. You could also use any binary protocol on it (or even invent your own protocol).
I would suggest you look at the examples in the Arduino IDE, that involve Serial and maybe try some tutorials on the web. There are many of them available.

Sending code: Can I still send code through Bluetooth without needing a USB connection?

You don't need an USB connection for Serial/UART to work. In fact the Atmega328p, which you program on the Uno, doesn't care about the USB connection at all. It only knows Serial/UART.

I hope that gave you a good overview over that topic. When you understand these core concepts you will be able to understand the tutorials and examples on the internet.

so sorry for the late response, this helps tremendously and I totally have a better understanding of this. I was actually getting hung up on that serial problem you mentioned, and the explanation that the bluetooth module is a bluetooth-serial bridge, instead of the USB-serial bridge that the Atmega32u4 does; this really helped. from what I understand, it seems like you're saying it would be a good idea to do everything through one method (sending code, altering binary data, etc) to prevent corrupting data by sending through both USB and bluetooth, right?

source: Stack Exchange

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

sort: votes


text:
Fastest external High Speed ADC?
I am in a situation close to:
Hi-speed external ADC
But with 100,000 ~ 500,000 samples per second, I don't need more.
I only want to detect changes in 2 sensors, so each loop is only an "analogread" and a couple of conditionals, so I have the 16MHz almost intact to store data from an external ADC.
What is the fastest thing you can aspire to with an arduino and an external ADC?

The link you gave explains the problem with an external ADC:  No matter how fast the ADC is, the Arduino has to get the data somehow, and put it someplace.  You can go faster than analogRead, but 100 kHz is about the limit for a single channel (8 bits, 2MHz clock) in bursts of 1024 samples, or just under 50 kHz with 2 channels. What exactly are you doing?  Can you use digital instead of analog?  Direct read of 8 digital pins can run at over 400 kHz in 1024-byte bursts.

Thanks @Boggyman, I have 2 analog photodiodes, and I want to detect any change in the fastest possible way. With 8 bits, or either 6, it's enough. But I can not find an external ADC with this characteristics. (that can be bought at a reasonable price)

Just browsing through the Mouser catalog brings up the following: MAX153, 1MSps, 8 bit parallel output with prices from about $8 or the TI ADC0820, 667KSps, 8 bit parallel with prices starting at about $5.

The Arduino as only one ADC. So it can't read 2 "A input" at exact same time. So internaly it's done by multiplexing. I suggest to start having at MOZZI Lib. It's a lib for creating musical instrument on Arduino and the LIB has it's own analogRead() function, faster than the original one.

Thanks @StarCat, I'm going to buy MAX153 and test it.

You mention detecting changes.  Depending on exactly what you are doing, there are ways of doing that externally without an ADC.  For example, if you want to know when the difference between the sensors exceeds a certain threshold, you can use a differential amplifier followed by a threshold comparator.  That gives you a pure digital signal that you can detect very quickly, or better yet use to generate an interrupt.

Thanks @Boggyman, I have connected the sensor output to a comparator and this to a digital pin. Now I am investigating if I can get more precision than the micros function offers.

If you explain exactly what you are doing in more detail, we can better help you find a solution.  If you are still at the stage of investigating what's going on, you may want to try my DaquinOscope https://www.daqarta.com/dw_rroo.htm.  It runs under Daqarta, but it's all FREE for Arduino users. It can sample at the speeds I mentioned in my first comment, and show traces of 1024 samples each on your computer screen.

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


text:
How to switch 12V with esp32?
Hello i want to switch electric door lock (12V, 170mA) with esp32(3.3V). If is it possible I want use tranzistor. I tried to use IRF520, but it only worked with 5V. My sugestion is use 2 tranzistors one would switch 5V to IRF520 which would switch 12V. Can someone pro provide me some schematic, how to solve it? Thanks.

there are many tutorials and schematics on the internet ... there is no reason why you should be asking for someone to find them for you

If it works with 5V I guess, that the mentioned MOSFET goes into saturation for 5V, but not for 3.3V. You should buy a MOSFET, which has its saturation voltage at like 1V or so.

BC549 provides strong pull-down for IRFR5305, which is provides up to +12V at 16A with less than 0.09 Ohm channel resistance.
This circuit works well with ESP8266, I use it in some of my devices.
Don't forget about placing the flyback diode (EEV Blog, Wiki) in reverse polarity, parallel to the magnet. Place it as close as possible to the magnet!

How is the MOSFET gate going to be charged with Vcc? The transistor switches the path for ground. Isn't at least a pullup resistor at the MOSFET gate needed?

Oh, i really forget about that - I've added it on PCB but not in shema. I'll fix it now

Thank you very mutch.Of course I forgot the flyback diode  so I'll add it.

Nice answer! One tip: You could make the schematic a bit more “readable” by applying a few standard layout rules: 1) Put the (positive) supply voltage at the top 2) Put Ground (or negative supplies) at the bottom 3) Any input signals to the left and 4) Output signals to the right. You could look at the elaborate answer to this question.

@StarCat - Done :)

This works, but if you're swapping OP's FET, why not just spec a logic-level N-channel FET and decimate the BOM (no flyback, no BJT, no resistors) for the build?

Do you know a good N-channel MOSFET which can be fully opened from 3.3 volts?
In any case, OP needs the flyback diode if the magnet doesn't have one.

@gbg - When I connect the emitter to the ground rail, the ESP 01S locks up (I'm using GPIO2). Any ideas? I'm using the same components listed here, a 330 ohm resistor and a 2N4401. Thanks.

@user87507 Umm, this is strange. Please, show me some pictures of your device

A single, reasonably tough general purpose BJT is all you need here if you really want a simple solution.  The 2N4401 supports up to 600mA of current and has a 40V Vce max.  As long as the solenoid on the door lock has a snubber it doesn't need to be any more complicated than this unless you need isolation or have other constraints.
Note that below I've drawn a relay because it was easy, but you can just as well put your door lock's solenoid coil where the relay is drawn below (they're effectively the same type of device).

I have exactly this setup on an ESP8266 controlling a 24V relay and it works great.  I'm using an old 2N2222, which are long since obsolete, but the 2N4401 would do just the same.

Using a relay to control a door lock magnet is very bad idea because of this: https://youtu.be/XXW27KKHtc8?t=79 - Eve can take a strong magnet, apply it to a control device and boom! - door is just opened.

@gbg The "relay" here is standing in for the coil of the door lock, which OP says draws 170mA@12V.  The point is that you can switch any solenoid with just a BJT as long as it's not too big.

@gbg  As an aside, relays are used for door locks, especially big ones, but usually in installations where the relay is far from the door itself - in a control room cabinet deep in the building, etc.  If you can get access with a magnet to those relays, you're already well past the door that's locking you out.

If relay is in a secured compartment - no problem. But in same smart (not really) locks, the relay is located just outside, in a keypad or a fingerprint sensor box

@gbg True, but consumer grade IoT is not anything I'd put in charge of security in the first place, to be honest.

S in IoT is for Security :)


text:
How or why is the Arduino keeping a LED on when the input putton is no longer pressed?
I'm trying to follow lesson 6 of the Adafruit Arduino lessons on digital inputs found here.
I have the same code and the board setup the exact same and the code it is working exactly as it should. I just can't figure out WHY.
Board:

Code:
    /*
Adafruit Arduino - Lesson 6. Inputs
*/

int ledPin = 5;
int buttonApin = 9;
int buttonBpin = 8;

byte leds = 0;

void setup()
{
  pinMode(ledPin, OUTPUT);
  pinMode(buttonApin, INPUT_PULLUP);
  pinMode(buttonBpin, INPUT_PULLUP);
}

void loop()
{
  if (digitalRead(buttonApin) == LOW)
  {
    digitalWrite(ledPin, HIGH);
  }
  if (digitalRead(buttonBpin) == LOW)
  {
    digitalWrite(ledPin, LOW);
  }
}

Why does the light turn on when one of he buttons is pressed once and turn off when the other button is pressed once. I don't understand the mechanism of how the press is being remembered.
There doesn't seem to be anything in the code that can explain why the button stays on even when no longer pressed, so it should be some component? But what?
Can anyone help explain why this is working?

you are falling into the trap of thinking this ... if the button is pressed and the light turns on, then the light must turn off if the button is released ... which part of the code tells the light to turn off when buttonApin is released?

Look at the code carefully - If button A is low turn the led on and only if button B is low then will it turn off, so if you press button B it will turn off

The port manipulated by digitalWrite maintains a state, kind of like a variable.

I would like to add two more cents. It is a wonderful explanation already from @chrisl
Here is the simulation screenshot for your example:

if you consider mechanical switches, they really cut the connection so that the light will be OFF. When you want the light to be on, you will move the switch to the ON position(in this example, hold the button)

In the case of Microcontrollers, and in the given example, it is more like two people communicating.

The 1st person is looking at the switches. The 2nd person is
controlling the LED
1st person is instructed to notify the second person about anybody pressing the switches
whenever the ON switch is pressed, the 1st person will immediately tell the second person to turn on the LED
Whenever the OFF switch is pressed, the 1st person will tell the 2nd person to turn off the LED

The behaviour of the program much depends on the requirement.

if you would love to see the LED turn OFF when you want to, you can try this example

Code:
/*
  Adafruit Arduino - Lesson 6. Inputs
*/

int ledPin = 5;
int buttonApin = 9;
//int buttonBpin = 8;

byte leds = 0;

void setup()
{
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
  pinMode(buttonApin, INPUT_PULLUP);
  pinMode(buttonBpin, INPUT_PULLUP);
}

void loop()
{
  digitalWrite(ledPin, !digitalRead(buttonApin));
}

If you read the lesson below the first picture and above parts it states: "Pressing the button nearer the top of the breadboard will turn the LED on, pressing the other button will turn the LED off." Try pressing and expect the LED to turn off.

It might be interesting to look at the reasons why the pin remembers its state (as described in other answers).
Every digital pin has dedicated digital output hardware, which can drive the pin to HIGH (Vcc, supply voltage) or LOW (ground). This output hardware is internally tied to a SFR (Special Function Register). A register is a piece of specific memory hardware in the microcontroller of the Arduino. The digital output hardware is electrically hardwired to some of those special function registers. Thus its state depends on what is saved in those registers. Since the registers hold their state during the running time of the Arduino (they are memory after all), the digital output hardware will also not change, until you change the corresponding registers (through executing digitalWrite()).
You can even manipulate the SFRs directly. This can help with programming time sensitive code or setting/reading multiple pins at once. All the digital pins are sorted into so called ports, which can hold up to 8 pins. For each port there are the following SFRs (the x stands for the character of the corresponding port, like PORTA, PORTB, ...), where the bits in these (1 byte big) registers correspond to one pin each:

DDRx: This register is the Data Direction Register. It controls if the corresponding pins are set as digital output or input.
PORTx: This register sets the output state. digitalWrite(pin, HIGH) will write a 1 to the corresponding bit of this register, which then sets the pin to HIGH. If the corresponding pin is set as input, setting a 1 in the corresponding bit of the PORT register will enable the interal pullup resistor of that pin.
PINx: This register holds the current state of the corresponding pins, so you can use it to read a digital pin.

You can also read this reference article. Also the datasheet of the used microcontroller also contains all information about what SFRs exist and how they are used to perform specific actions.

The press is not being remembered. Instead, the output pin "remembers" its state: digitalWrite(HIGH) sets the pin to high and the pin will remain high until you call digitalWrite(LOW).


text:
Variable frequency PWM, without changing timers
I need variable frequency output - 0-5000Hz with some duty cycle. I do not want to change timers, because I am using delays, serial and CAN, so I do not want them to be affected by changed timers. I need this for VDO speedometer, which is driven by variable frequency.
Is it possible to set variable time interrupts and change them accordingly to what frequency I want?

Yes, possible, by changing the settings of a timer. Don't know much about CAN. But a hardware Serial interface doesn't depend on any timer. And delays also use Timer0. Even the Arduino Uno has 3 Timers I think. There should be one available to use for you

timers, as I understand, need to be changed by their prescalers, but what if I want an exact value of frequency? Something like delay()?

Try using tone()...

For changing the timer frequency you can also use the output compare mode, where the timers runs up to a value, that you write into the output compare registers (OCR...). So the frequency can be adjusted with rather high resolution (depending on the used timer). Why don't you want to use timers? Try using tone() would be the easiest. It also uses a Timer.

YES! Thank you, tone() works perfectly


text:
I need help making an arduino control system
My project is to use an Arduino to control two solenoid valves with pwm and receive an input signal from a sensor as feedback.

As can be seen from the picture, the valves direct the flow of water which cause a hydraulic actuator to move which is detected by an LVDT sensor.
What I want my program to do is to allow me to set a desired displacement as a goal which causes the Arduino to dynamically change the duty cycle of the pwm frequency based off of the feedback input the Arduino receives.
I am a total novice programmer and its my first time working with electronics. I'm just hoping someone can point me in the right direction.
Based off of youtube videos this is the code I've written.
int myPin1=3;
int myPin2=5;
int readPin=A3;

//V2 is input from sensor
int V2=0;
int delayTime=50;
float D1=0.5;
float D2=0.5;
int readVal;

int goal=;

void setup() {
  // Set pin states:
  pinMode(myPin1,OUTPUT);
  pinMode(myPin2,OUTPUT);
  pinMode(readPin,INPUT);
  Serial.begin(9600);

  //set frequency of the PWM pins
  SetPinFrequencySafe(myPin1, 1000);
  SetPinFrequencySafe(myPin2, 1000);
}

void loop() {
  // Volatge reading from the VTLD:
  readVal=(5/1023)analogRead(readPin);
  V2 = (5./1023.)*readVal
  Serial.print("Voltage is ");
  Serial.println(V2);

  //PWM for the 2 output pins
  analogWrite(myPin1,D1);

  analogWrite(myPin1,D2);
  delay(delayTime);

  //Varying of dutcy cycle untill getting the desired actuator position
while (V2!=goal) {
  if (V2>goal) {
    D1=D1+0.01;
    D2=D2-0.01;
  }
   if (V2<goal) {
    D1=D1-0.01;
    D2=D2+0.01;
  }
}
  if (V2=goal) {
    D1=0.5
    D2=0.5
  }

}

I have seen people using PID libraries but I'm not sure which one is suitable to use for my project.

I successfully used this PID library before. Just try it

Welcome Marius, it would be much easier to answer your question if we had more information. Can you post your schematic or drawing of the circuit. What are you using to drive the solenoids, what is the sensor? Post links to the hardware devices that give technical information.


text:
Reading and Writing to a JSON File on the Desktop from Arduino?
I'm fairly new to Arduino. I'm working on a project where I'm making HTTP requests using a python code and this lets me read and write to a JSON file on my desktop. I have an Arduino with sensors that records values and I want to take those recorded values and update them to the JSON file on my desktop in real-time. I looked online and many suggested using some Arduino library, but it was only for reading. I'm still confused about reading and writing to the JSON file on my desktop. I appreciate any help to guide me in the right direction. Thank you.

The Arduino cannot just write to your PCs storage. There must be some kind of program on the PC to do the writing. Thus you don't need an Arduino JSON library. You could let your python code, that already writes to the JSON file, also read data from the Arduino (for example over serial) and put that data into the file

@chrisl is there a reliable resource you recommend that demonstrates how the python code can read data from the Arduino. From a quick search, I was able to find some examples of communication over serial.

The way the PC and the Arduino communicate depends on the used interface. If you connect the Arduino via USB, then it will be Serial. If you have a Wifi Arduino or an Ethernet shield, you could also send data via network connection. But it seems, you want serial here. I have no source, but you can google it. Probably you also should read Majenkos take on Serial on the Arduino.

When googling you can separate the Arduino from the PC, meaning, that you can google for something like "python reading serial" and then "Arduino serial" individually, instead of googling it together. Though you might find good resources with that too

Thank you, I'll check it out.

The Arduino cannot access files on a desktop computer.
However you can write software on your computer (you already use Python, so why not use that?) to accept information over Serial, process it, and store it in any way you like (including JSON), or return data from the computer to the Arduino if needed.

These were links I was looking at, thank you. I'm not too familiar with the coding to do this so I'm relying on sample codes that I can modify for my needs.


text:
Is it possible to save and restore the Arduino IDE "Tools" settings somehow?
I'm using quite a few different types of microcontrollers with the Arduino IDE (v 1.8.19). Several AVR-based boards, but also ESP32 and Arduino Due. Particularly the newer boards have a quite long set of options in the tool menu, as seen in this screen shot (for an ESP32-Dev module).

Each time I swap boards, the settings revert back to defaults and I have to remember updating them according to my needs. Is there a way to save the current IDE configuration, so that I can easily load all the settings I need for e.g. "ESP32"? When I haven't used a certain board for some time, I often even fail to remember exactly what settings I needed.

I didn't find a way

@Juraj Thanks for trying. Maybe someone knows a way to backup a settings file or something. Because at least the IDE remembers the last settings.

even the IDE 2 doesn't have it. only the WebEditor and CLI have it https://arduino.github.io/arduino-cli/0.28/sketch-specification/#sketchjson

IDE remembers the settings in global preferences.txt with many other IDE settings

a workaround could be to define own board in boards.local.txt with all the settings predefined

One of the many reasons people switch to VS Code + platformIO plugin for Arduino programming. It configures the setting on each project with platformio.ini file.


text:
ESP32 PWM with extended resolution doesn't work as expected
I have attached an RGB-LED to three output lines of the ESP32 and I'm trying to fade all colors independently. Since it didn't work with my code, I went back to the basic ESP32 ledcWrite_RGB sample program, extracts copied for reference:
uint8_t ledR = 25;
uint8_t ledG = 33;
uint8_t ledB = 32;

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

  ledcAttachPin(ledR, 1); // assign RGB led pins to channels
  ledcAttachPin(ledG, 2);
  ledcAttachPin(ledB, 3);

  // Initialize channels
  // channels 0-15, resolution 1-16 bits, freq limits depend on resolution
  // ledcSetup(uint8_t channel, uint32_t freq, uint8_t resolution_bits);
  ledcSetup(1, 12000, 8); // 12 kHz PWM, 8-bit resolution
  ledcSetup(2, 12000, 8);
  ledcSetup(3, 12000, 8);
}
void loop()
{
  Serial.println("Send all LEDs a 255 and wait 2 seconds.");
  ledcWrite(1, 255);
  ledcWrite(2, 255);
  ledcWrite(3, 255);
  delay(2000);

  // ... run some color fade tests ...
}

With this code, everything works as expected. Now according to the documentation the resolution (third parameter of ledcSetup) can be changed up to 20 bits. If I change the resolution to 12 bits (and increase the max value to 12^2 - 1 = 4095) it still works fine. But if I change it to 13 bits, all of a sudden, nothing happens any more. The LED stays dark all the time.
Now I know that a PWM resolution of 12 or 13 bits isn't particularly useful for driving a LED, but still I would like to know why this isn't working.
Edit I just found that the kernel dumps this message when it's not working:
[     3][D][esp32-hal-cpu.c:244] setCpuFrequencyMhz(): PLL: 480 / 2 = 240 Mhz, APB: 80000000 Hz
E (31) ledc: requested frequency and duty resolution can not be achieved, try reducing freq_hz or duty_resolution. div_param=208
[    33][E][esp32-hal-ledc.c:75] ledcSetup(): ledc setup failed!
E (37) ledc: requested frequency and duty resolution can not be achieved, try reducing freq_hz or duty_resolution. div_param=208
[    50][E][esp32-hal-ledc.c:75] ledcSetup(): ledc setup failed!
E (54) ledc: requested frequency and duty resolution can not be achieved, try reducing freq_hz or duty_resolution. div_param=208
[    67][E][esp32-hal-ledc.c:75] ledcSetup(): ledc setup failed!

Does this mean that there's a limit imposed by the product of frequency and resolution?

it can only turn the pin on and off so many times per second. When you use more bits, it uses more ons/offs, heh; that's what a bit is. Think of a human analogy; you can recite more 5 digit codes in one minute than you can 10 digit codes...  There's a tradeoff between resolution and frequency as you've noticed. There's nothing you can do to "fix" this hardware limit.

and if you don't have audio feedback issues with your hardware (the leds or driver buzzing), there's little human advantages to anything over about 4khz, and as you increase frequency, your switching costs will rise, generating more heat and increasing the effects of any capacitance in the wiring or strips, which (ironically) further reduces the practical resolution (number of dim levels achievable).

@dandavis I'm seeing that it has to do with the internal oscillator required, but the frequency of the (theoretical) PWM signal doesn't change when the resolution is increased (only the duty cycle can be set more accurately). What I'm actually looking for is a documentation about this. How is the limit of frequency x resolution defined?

If you use, say, 16b instead of 8b, or go slower in freq, then the equivalent "010" will become "001100" or "000111000" as needed, so while the apparent output won't change, the internals that encode the duty cycle will. You can look at the freq of a 2 bit or the rez of a max freq to get an idea of the over-all bandwidth available. iirc, it's about 80mbps/2^bits.


text:
Arduino not recognizing external microcontroller
I've been trying to follow the official Arduino instructions on how to program and power an external breadboard, and I've gotten a pack of ATmega328p's that may or may not have been preloaded with the bootloader (found here). From the title, I assumed that they were, in fact, preloaded, but I followed the instructions to "reload it" from a working Arduino (with its original microcontroller), and I did it with the following circuit setup (this is the best image that I have of it, unfortunately, I promise I've checked that the wiring actually is equivalent to the original diagram, just shifted around for convenience on the breadboard):

I'm not sure whether I should've kept the original microcontroller in, as the guide ambiguously shows a void in the area where the controller should be in the provided diagram...

...but my thinking was that the Arduino basically isn't anything without its attached microcontroller, so attempting to "send" bootloader code to a separate microcontroller would require a plugged in microcontroller, and that was the only way I got it to work.
With all this set up, I tried to test using this new microcontroller, and it worked perfectly when mounted in the provided microcontroller area. However, when I tried to follow this up with the steps detailed in the guide, found here, with the following circuit (slightly better angle):

...I was faced with errors of being unable to connect.

From what I understand, it seems like the Arduino should automatically detect that no microcontroller is plugged in, hence allowing the stated "FTDI chip can talk to the microcontroller on the breadboard instead" from the guide. However, the error I'm getting seems to be the same as the error I got when I just plainly tried to send code or program without any microcontroller connected, so I'm assuming this implies that it can't find any microcontroller, either internal or standalone.
From googling this error, it seems that others have had this problem with seemingly no solution, and I have absolutely no idea how I could fix this. If there's something I'm missing, would greatly appreciate the help.
side note, when I was idly testing out the program with a tiny test circuit that lights up an LED, after programming it with a program that turns on a GPIO pin, connecting that pin to the LED, it did in fact light up. I'm concluding this means that the setup of the actual microcontroller is functional, but it's unable to be written to. this has also happened with the original microcontroller that I tried to simply program externally.
any help is appreciated, thanks for reading!

If you have been able to put the new MCU chip into your Uno and it works, say you can upload a sketch, then it has a bootloader. Clearly,  a chip must be present in the Uno when the Uno is used to burn a bootloader onto another chip because the Uno must run the ISP sketch. For the second part, that is loading a sketch onto the chip on the breadboard, check your wiring carefully between TX, RX and Reset on the Uno and the breadboard. It does look wrong but that could be the picture quality. For this part it is correct that the Uno has no MCU chip.

Simply to eliminate variables, I would not put the crystal away from the chip that way. You can angle that crystal at roughly 45 degrees, connecting the crystal directly to the same breadboard tie points that the MCU's crystal related pins go to. Your load caps can then connect those same exact tie point to the nearby ground bus. In the end, you have jumpers involved in the purely crystal-related part of the circuit. Less crap to go wrong. Or worse, go wrong intermittently while you're troubleshooting.

Can you please see my page about detecting chip signatures. Using your Uno and 6 wires (MOSI, MISO, SCK, SS, 5V, Gnd) you can see if it recognises the chip at all, and if so, is there a bootloader on it, and also the fuse settings. Please edit your question with the results of that.

Also see my page about breadboard Arduinos which describes something very similar to what you are attempting.

apologies for the late responses y'all, getting to this! @6v6gt, I didn't include a Reset as I figured that I didn't need to use the reset (would just rerun the code if I needed a reset). will try to add this in in a bit, I'm fairly certain the TX/RX is right but will try that in a bit

@timemage I see, I'll take this into account, but I don't actually plan on mounting it to the breadboard for an extended period of time, just as a testing framework before I actually mount it on a perfboard (perma-proto)

@NickGammon will check this when I get back to this next, much appreciated! I have honestly been having trouble finding good resources on breadboard Arduinos as I feel like this should be a really simple and well-documented problem, but everyone just seems to ignore it so it's really helpful to see a guide!

NickGammon's second link shows the crystal arrangement I was describing. And I am suggesting that it may be worth doing now (regardless how temporary your setup is) because you are having troubles.

great, so I've just rechecked my work with the circuit and as it turns out, the problem seemed to just lie in the fact that I didn't have the Reset connected, as @6v6gt mentioned. I didn't realize that this could've broken everything, so I'll make sure to be very careful when placing this onto an actual perfboard. if you'd like to write the answer for this I'll absolutely accept! much appreciated :D

You kind of don't really. All that matters is for optiboot is that an external reset happens. It's sufficient that you momentary ground reset within about 1.3 seconds prior to avrdude making programing attempt, which it does repeatedly, which has the effect of making the time much looser. The serial-DTR auto-reset mechanism is nice to have but you needn't use it.  It is not uncommon to just use a jumper wire momentary from gnd to reset, nor uncommon to entirely remove it from the board once reset, which makes its absence in the picture not particularly definitive.

In the case of using an Arduino as a USB/UART (FTDI) adapter to upload a sketch onto a barebones Arduino (ATMEGA328P) via its own bootloader,  a reset of that MCU chip must preceed the sketch upload. That is because, immediately following the reset, the bootloader watches the serial traffic to see if this is marked as a sketch upload and, if so, processes it. If this reset operation fails, for example through a bad or missing connection, the sketch upload attempt will also fail.
A good description of the sketch upload process can  be found here: https://www.instructables.com/Overview-the-Arduino-sketch-uploading-process-and-/

this makes a lot of sense! thanks for explaining the reasoning behind it, was very curious why it couldn't just send a reset signal through the TX/RX, lol


text:
Sending multiple data with SPI interface monitored by an Osciloscope
I have multiple 32-bit data stored in an array, and I want to sequentially send them by SPI interface. I want to check that my code is correctly sending data by SPI interface, so I upload the code and connect my Linkit7697 to an oscilloscope.
The expecting waveform is like this:

But it turns out to be like this:

It seems that all data are composited together in every 32 bits.
What's wrong? Any idea?
Here is my code:
#include <SPI.h>

#define SPI_MOSI (11)
#define SPI_MISO (12)
#define SPI_CS (10)
#define SPI_CLK (13)

uint32_t test[]={
  0xF0000000,   //11110000000000000000000000000000
  0x00F00000,   //00000000111100000000000000000000
  0x0000F000,   //00000000000000001111000000000000
  0x0000000F    //00000000000000000000000000001111
  };

int i = 0;

void setup() {
  digitalWrite(SPI_CS,HIGH); //Set slave select to high, linkit7697 is Master
  SPI.begin();
  SPI.beginTransaction(SPISettings(20000000,MSBFIRST,SPI_MODE0 ));

}

void loop() {

  for (i = 0; i < 4; i++){
    digitalWrite(SPI_CS,LOW);
    SPI.transfer(&test[i],4);
    digitalWrite(SPI_CS, HIGH);

  }

}

a quick look at the library shows  transfer16 and transfer32 functions

Without fully understanding your problem description, I guess that SPI.transfer() actually will cut off everything after the lowest byte of your data element (because it expects one byte), thus only sending one byte per number. As jsotola wrote, the transfer32() function is meant for tranferring 32 bit numbers. You should use it

I've used bitwise operator to transform 32 bits data to two 16 bits data, and using SPI.transfer16() to do the transfer. I'm sure that the bitwise operator is working (Because I use serial monitor to print the result). But when I connect the Linkit7697 to the oscilloscope, it shows the waveform as I mentioned above.

SPI.transfer(&test[i],4);

The SPI.transfer() transmit one byte each time and therefore expecting a pointer to a byte (i.e. uint8_t) while you are passing in an address of an uint32_t. What you need to do is to cast the address of uint32_t into a pointer of uint8_t before passing it into the SPI.transfer.
uint8_t *ptr = (uint8_t *) &test;

SPI.beginTransaction(SPISettings(20000000,MSBFIRST,SPI_MODE0 ));
digitalWrite(SPI_CS,LOW);
for (i = 0; i < sizeof(test); i++) {
  SPI.transfer(*ptr++, 4);
}
digitalWrite(SPI_CS, HIGH);
SPI.endTransaction();

Please also note that Arduino is a little endian machine, so if you have a data as 0x41424344, the first byte get transmitted will be 0x44.
One more thing, it is always good to call SPI.endTransaction(), it free up the SPI bus to allow other SPI devices to use the data bus.


text:
Debug Macro Not working
I wrote simple program to test debug macros, but it gives me compilation error
Program:
#include <Arduino.h>

#define DEBUG

#ifdef DEBUG
  #define DPRINT(...)    Serial.print(__VA_ARGS__)
  #define DPRINTLN(...)  Serial.println(__VA_ARGS__)
#else
  // define blank line
  #define DPRINT(...)
  #define DPRINTLN(...)
#endif

void setup() {
  // put your setup code here, to run once:
  String str ="Hello MrNams";
  DPRINT("Here is my string %s",str);
}

void loop() {
  // put your main code here, to run repeatedly:
}

Compilation Error:
src/main.cpp: In function 'void setup()':
src/main.cpp:7:50: error: no matching function for call to 'HardwareSerial::print(const char [21], String&)'
#define DPRINT(...)    Serial.print(VA_ARGS)
^
src/main.cpp:19:3: note: in expansion of macro 'DPRINT'
DPRINT("Here is my string %s",str);
^~~~~~
In file included from C:/Users//.platformio/packages/framework-arduinoespressif32/cores/esp32/Stream.h:26,
from C:/Users//.platformio/packages/framework-arduinoespressif32/cores/esp32/Arduino.h:177,
from src/main.cpp:2:
C:/Users//.platformio/packages/framework-arduinoespressif32/cores/esp32/Print.h:81:12: note: candidate: 'size_t Print::print(const __FlashStringHelper*)'
size_t print(const __FlashStringHelper *);
^~~~~
C:/Users//.platformio/packages/framework-arduinoespressif32/cores/esp32/Print.h:81:12: note:   candidate expects 1 argument, 2 provided
C:/Users//.platformio/packages/framework-arduinoespressif32/cores/esp32/Print.h:82:12: note: candidate: 'size_t Print::print(const String&)'
size_t print(const String &);

Serial.print doesn't support variable arguments

format the error log as code

This: ("Here is my string %s",str); cannot be handed over to Serial.print() which is effectively what you are doing. The argument set appears to be more appropriate for the C++ function printf().


text:
LED sometimes don't turn off when a button is pressed
I'm still very new to this but I've put together some code that when a button is pressed, my servo runs continuously, a second button rotates it the other way and a third cancels everything.
A red or green comes on depending on the rotation and this can be one using an IR receiver also.
Issue I'm having is that randomly, 1/5 of the time, the red or green LED does not turn off. I can manually kill it using the third cancel button or just press it a couple times until it turns off as it should on the next push of the button.
Cant work out where im going wrong.
I also find my IR remote works maybe 60% of the time. Any help would be greatly appreciated.
#include <Servo.h>
Servo servo1;
int servoPin = 9;
#include "IRremote.h"

/*----- Variables, Pins -----*/

int receiver = 12; // Signal Pin of IR receiver to Arduino Digital Pin 6
int RledPin = 5;
int GledPin = 3;
int buttonApin = 7;
int buttonBpin = 8;
int buttonCpin = 4;
unsigned long elapsedTime;
unsigned long onTime;

/*-----( Declare objects )-----*/
// Setup of proper sequencing for Motor Driver Pins
// In1, In2, In3, In4 in the sequence 1-3-2-4

IRrecv irrecv(receiver);    // create instance of 'irrecv'
decode_results results;     // create instance of 'decode_results'

void setup()
{
  irrecv.enableIRIn(); // Start the receiver
  servo1.attach(servoPin);
  servo1.write(90);
  pinMode(RledPin, OUTPUT);
  pinMode(GledPin, OUTPUT);
  pinMode(buttonApin, INPUT_PULLUP);
  pinMode(buttonBpin, INPUT_PULLUP);
  pinMode(buttonCpin, INPUT_PULLUP);

}

void loop(){

if (digitalRead(buttonApin) == LOW)   // Switch is closed to start LED timer
         {
          digitalWrite(RledPin, HIGH);  // Red LED comes On
          digitalWrite(GledPin, LOW);  // Green LED Goes Off
          servo1.attach(servoPin); //Servo is activated
          servo1.write(0);  //Servo turns on clockwise
            onTime = millis();  //time set
          }

      if(onTime > 0 && millis() - onTime > 1500)  //time limit target
            {
            servo1.write(90); //Servo stops
            servo1.detach(); //servo deactivated
            delay(500); //used to sync the servo stop with the LED off
            digitalWrite(RledPin, LOW);  // LED goes off
              onTime = 0;  //time reset
            }

if (digitalRead(buttonCpin) == LOW)   // Switch is closed to start LED timer
         {
          digitalWrite(GledPin, HIGH);  // Green LED comes On
          digitalWrite(RledPin, LOW);  // RED LED Goes Off
          servo1.attach(servoPin); //Servo is activated
          servo1.write(180);  //Servo turns on anti-clockwise
            onTime = millis();  //time set
          }

      if(onTime > 0 && millis() - onTime > 1500)  //time limit target
            {
            servo1.write(90); //Servo stops
            servo1.detach(); //servo deactivated
            delay(500);
            digitalWrite(GledPin, LOW);
              onTime = 0;  //time reset
            }

if (digitalRead(buttonBpin) == LOW) //Deactivation Sequence KILL SWITCH
  {
    digitalWrite(RledPin, LOW);
    digitalWrite(GledPin, LOW);
    servo1.write(90);
    servo1.detach();
      onTime = 0;  //time reset
  }

  if (irrecv.decode(&results)) // have we received an IR signal?

  {
    switch(results.value)

    {

      case 0xFFE01F: // DOWN button pressed
                      {
          digitalWrite(RledPin, HIGH);  // Red LED comes On
          digitalWrite(GledPin, LOW);  // Green LED Goes Off
          servo1.attach(servoPin); //Servo is activated
          servo1.write(0);  //Servo turns on clockwise
          onTime = millis();  //time set
          }

          if(onTime > 0 && millis() - onTime > 2000)  //time limit target
            {
            servo1.write(90); //Servo stops
            servo1.detach(); //servo deactivated
            digitalWrite(RledPin, LOW);  // LED goes off
             onTime = 0;  //time reset
            }
            break;

      case 0xFF906F: // UP button pressed
                      {
          digitalWrite(GledPin, HIGH);  // Green LED comes On
          digitalWrite(RledPin, LOW);  // RED LED Goes Off
          servo1.attach(servoPin); //Servo is activated
          servo1.write(180);  //Servo turns on anticlockwise
          onTime = millis();  //time set
          }

      if(onTime > 0 && millis() - onTime > 2000)  //time limit target
            {
            servo1.write(90); //Servo stops
            servo1.detach(); //servo deactivated
            digitalWrite(GledPin, LOW);  // LED goes off
             onTime = 0;  //time reset
            }
            break;

      case 0xFF02FD: // PAUSE button pressed
                      servo1.write(90);
                      servo1.detach();
                      digitalWrite(GledPin, LOW);
                      digitalWrite(GledPin, LOW);
                      break;

    }

      irrecv.resume(); // receive the next value

  }
}/* --end main loop -- */

insert a layer of separation between the button press and the resulting action ... do same with IR codes .... pressing a button results is a flag variable being set doRed = true; ...... case 0xFFE01F: does the same thing .... neither of these do anything else, just set a flag and continue on ..... further down in loop(), act on the state of the flag if (doRed) {

Please adopt an indenting style and stick to it. Your source is barely readable. Many problems reveal themselves by consistent indentation.

Insert some debugging outputs to see what exactly happens in your program.

Are you debouncing the buttons in hardware? If not, you need to debounce them in software using a debouncer. This will remove the random glitches as the switch contacts bounce when they change over.

@jsotola Thanks for the reply, sorry to sound silly but when you say add a layer of separation, what does that mean?

@tim Thanks for the suggestion, I ave read articles mentioning debouncers but don't know anything about them. I will go away and look into it, thank you.

@NathanCooper ... not separated if button is pressed, then turn on LED.... separated if button is pressed, then set a flag .... if flag is set, then turn on LED .... multiple events can set the flag ... only one function checks the flag and activates the LED

Found the answer!
I added serial print to every line and realised that my kill process after the time elapsed was switching between the red led and green led.
I didn't need the if time elapsed function many times, just once. Deleted that portion and it worked perfectly. Seems to have fixed the IR troubles too.
Working code:

#include <Servo.h>
Servo servo1;
int servoPin = 9;
#include "IRremote.h"

/*----- Variables, Pins -----*/

int receiver = 12; // Signal Pin of IR receiver to Arduino Digital Pin 6
int RledPin = 5;
int GledPin = 3;
int buttonApin = 7;
int buttonBpin = 8;
int buttonCpin = 4;
unsigned long elapsedTime;
unsigned long onTime;

/*-----( Declare objects )-----*/
// Setup of proper sequencing for Motor Driver Pins
// In1, In2, In3, In4 in the sequence 1-3-2-4

IRrecv irrecv(receiver);    // create instance of 'irrecv'
decode_results results;     // create instance of 'decode_results'

void setup()
{
  irrecv.enableIRIn(); // Start the receiver
  servo1.attach(servoPin);
  servo1.write(90);
  pinMode(RledPin, OUTPUT);
  pinMode(GledPin, OUTPUT);
  pinMode(buttonApin, INPUT_PULLUP);
  pinMode(buttonBpin, INPUT_PULLUP);
  pinMode(buttonCpin, INPUT_PULLUP);
  Serial.begin(9600);
  pinMode(LED_BUILTIN, HIGH);

}

void loop(){

if (digitalRead(buttonApin) == LOW)   // Switch is closed to start LED timer
         {
          digitalWrite(RledPin, HIGH);  // Red LED comes On
          Serial.println("RED comes on");
          digitalWrite(GledPin, LOW);  // Green LED Goes Off
          Serial.println("green off");
          servo1.attach(servoPin); //Servo is activated
          Serial.println("red servo attach");
          servo1.write(0);  //Servo turns on clockwise
          Serial.println("red servo spins");
            onTime = millis();  //time set
         }

if(onTime > 0 && millis() - onTime > 1500)  //time limit target
            {
            servo1.write(90); //Servo stops
            Serial.println("servo stops spinning");
            digitalWrite(RledPin, LOW);  // LED goes off
            digitalWrite(GledPin, LOW);  // LED goes off
            Serial.println("red RED goes off");
            delay(500);
            Serial.println("delay");
            servo1.detach(); //servo deactivated
            Serial.println("servo Rled dettach");
              onTime = 0;  //time reset

         }
if (digitalRead(buttonCpin) == LOW)   // Switch is closed to start LED timer
         {
          digitalWrite(GledPin, HIGH);  // Green LED comes On
          Serial.println("green comes on");
          digitalWrite(RledPin, LOW);  // RED LED Goes Off
          Serial.println("RED goes off");
          servo1.attach(servoPin); //Servo is activated
          Serial.println("green servo attached");
          servo1.write(180);  //Servo turns on clockwise
          Serial.println("green servo spins");
            onTime = millis();  //time set
         }

if (digitalRead(buttonBpin) == LOW) //Dectivation Sequence KILL SWITCH
  {
    digitalWrite(RledPin, LOW);
    Serial.println("total red off");
    digitalWrite(GledPin, LOW);
    Serial.println("total green off");
    servo1.write(90);
    Serial.println("total servo off");
    servo1.detach();
    Serial.println("total detach");
      onTime = 0;  //time reset
  }

  if (irrecv.decode(&results)) // have we received an IR signal?

  {
    switch(results.value)

    {

      case 0xFFE01F: // DOWN button pressed
                      {
          digitalWrite(RledPin, HIGH);  // Red LED comes On
          digitalWrite(GledPin, LOW);  // Green LED Goes Off
          servo1.attach(servoPin); //Servo is activated
          servo1.write(0);  //Servo turns on clockwise
          onTime = millis();  //time set
          }
          break;

      case 0xFF906F: // UP button pressed
                      {
          digitalWrite(GledPin, HIGH);  // Green LED comes On
          digitalWrite(RledPin, LOW);  // RED LED Goes Off
          servo1.attach(servoPin); //Servo is activated
          servo1.write(180);  //Servo turns on clockwise
          onTime = millis();  //time set
          }
          break;

      case 0xFF02FD: // PAUSE button pressed
          servo1.write(90);
          digitalWrite(GledPin, LOW);
          digitalWrite(GledPin, LOW);
          delay(500);
          servo1.detach();
          break;
    }

      irrecv.resume(); // receive the next value

  }
}/* --end main loop -- */


text:
Error in I2C Communication Between Arduino and Raspberry Pi
The code below sends data to Raspberry Pi every 20 millisecond. The code works fine but sometimes python throws an error. Why this is happening? Should I give more time between writeData?
Error:
> Traceback (most recent call last):   File "rpi-I2C.py", line 33, in
> <module>
> writeData("360")   File "rpi-I2C.py", line 12, in writeData
> bus.write_i2c_block_data(address,0x00,byteValue) OSError: [Errno 121] Remote I/O error

Python code:
import smbus
import time
# for RPI version 1, use bus = smbus.SMBus(0)
bus = smbus.SMBus(1)

# This is the address we setup in the Arduino Program
address = 0x04

#http://www.raspberry-projects.com/pi/programming-in-python/i2c-programming-in-python/using-the-i2c-interface-2
def writeData(value):
    byteValue = StringToBytes(value)
    bus.write_i2c_block_data(address,0x00,byteValue)
    #first byte is 0=command byte.. just is.
    return -1

def StringToBytes(val):
        retVal = []
        for c in val:
                retVal.append(ord(c))
        return retVal

while True:
    print("sending test")
    writeData("left")
    time.sleep(0.02)

    #print('Sending OPEN-00-00');
    writeData("right")
    time.sleep(0.02)

    #print('Sending WIN-12-200');
    writeData("360")
    time.sleep(0.02)

Arduino code:
#include <Wire.h>
#define SLAVE_ADDRESS 0x04

volatile boolean receiveFlag = false;
char temp[32];
String command;

void setup() {
  Wire.begin(SLAVE_ADDRESS);
  // define callbacks for i2c communication
  Wire.onReceive(receiveEvent);
  Serial.begin(115200);
  Serial.println("Ready!");
}

void loop() {
  if (receiveFlag == true) {
    Serial.println(temp);
    receiveFlag = false;
  }
}

void receiveEvent(int howMany) {
  for (int i = 0; i < howMany; i++) {
    temp[i] = Wire.read();
    temp[i + 1] = '\0';  //add null after ea. char
  }

  //RPi first byte is cmd byte so shift everything to the left 1 pos so temp contains our string
  for (int i = 0; i < howMany; ++i)
    temp[i] = temp[i + 1];
    receiveFlag = true;
  }

Slowing it down a bit would be the first thing I'd try, e.g., crank it up to .5sec. If that fixes it you'll know it's a timing issue. You could also speed up the Arduino side by temporarily removing the Serial.println because it could just be the Arduino can't keep up since it's serial-ing while the host is still blasting I2C data. (Only do one change at a time, obviously).

Changing sleep time to 0.5Sec works but I want to send data every 20ms. Is there any way to do this? What causes the problem exactly? Is Arduino reading data slower than expected?

Serial output is relatively slow.

Got it. Thanks.

Are you using an active level translator for the Arduino and the Pi. This I would expect with a passive (resistor) level translator. A simple trick is to transmit with 2 stop bits and receive with 1. This gives you a free bit time for each character.

A RPI uses 3.3v logic while an arduino uses 5v logic you can use a logic converter but by now it's probly to late and maybe your arduino or RPI is broken (Sorry!)


text:
LCD TFT 2.4"" changes the values of analog read of Arduino Mega
I have a Arduino Mega with LCD TFT 2.4"" with reading 5v signal on A8 pin (Arduino mega pin) from a raspberry pi (just to test). They are grounded together. When the Arduino is without the LCD, the analog reading works fine (4.8V,same from multimeter). But when I assembly the LCD, even if I just assembly VCC and ground, the analog read increasce around of 0.2V measure. I already tried to change the voltage input with a potentiometer and I still receiving a measure error of 0.2V.  External energy supply to the LCD makes the things works, but I wouldn't like to have a external supply just to the screen.
What I'm doing wrong or what I can do ?

Measure the Arduino's 5V pin with the LCD attached. I'll bet it no longer measures 5V...

Yeah, without the LCD attached i got a 4.95V. When I attach the LCD the Arduino's goes to 4.85V

MCUFriend went through a number of revisions of the same 2.4" TFT shield over time. I guess it depended on what TFT screens they could get hold of cheapest at any given moment. I have two versions here, neither of which are the same as yours. Both have their own voltage regulator onboard for the 3.3V power (which yours doesn't). Both of them also have resistors present on the cathode of the back light - which yours doesn't.
I would imagine for this revision they mistakenly though the TFT screen's back light didn't require any current limiting resistors and omitted them, with the end result that connecting the TFT screen to the Arduino drags down the 5V voltage to that of the combined forward voltage of the LEDs in the back light circuit.
In short: your TFT screen is designed badly. Fixing it would require modifying the shield on a trace-level basis. Not easy.

Yeah, It make sense. I was expecting that. Which lcd Tft do you recommend me ?

@GabrielLincoln They're all pretty much of a muchness. Look for one with a few more components on it than just some IO buffers. Personally I design and build my own direcly into products instead of using shields, but I do have a large collection here for when I was developing a big display library system. If you see a "resistor array" on the images of the TFT it's a pretty safe bet it's good.

The short answer is to beef up your power supply:

Don't use small batteries or power supplies.  For instance use D Size Cells instead of 9 Volt Cells.  Or use a 3 Amp power supply instead of a 100mAmp power supply.

The longer answer:

Make sure you have mitigated any power problems.  Like long or thin power lines.  Long or thin wires have more resistance.  And the more current you pull over that resistance the less voltage you will have at the far end.  Remember it follows the rule:
Voltage = Resistance * Current

Probably the best answer:

Check the ADC specification of the processor and make sure your voltage reference is not adversely affected by power fluctuations.  Some processors, like most used on Arduinos, have the ability to switch between internal references and external references.  Most designers who really need a good ADC response will design an external reference and instruct the processor to use the external over the internal reference.  For most Arduinos the function to call to switch references is "analogReference()".  You can read more about this command and external references here.


text:
RTC DS3231 always remember the old time
I try to change time on windows to test my programing condition but RTC usually keep old time when i change time on windows and re-upload the code . I'm also removing the battery  and cut the power it is still not working.
here is my set up and library is https://github.com/adafruit/RTClib
void setup () {

#ifndef ESP8266
  while (!Serial); // for Leonardo/Micro/Zero
#endif

  Serial.begin(9600);
   Serial.println("ESP start...");
  pinMode(Ledpin, OUTPUT);
  pinMode(buzzer, OUTPUT);
  digitalWrite(buzzer, HIGH);

  delay(3000); // wait for console opening

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

  if (rtc.lostPower()) {
    Serial.println("RTC lost power, lets set the time!");
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
    // This line sets the RTC with an explicit date & time, for example to set
    // January 21, 2014 at 3am you would call:
    // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
  }

}

Does it print “RTC lost power, lets set the time!”?

Thanks.  I hadn't seen the rtc.adjust(DateTime(F(__DATE__),F(__TIME__))); construction, which uses the DateTime(char*,char*) routine from  https://github.com/adafruit/RTClib/blob/4ece412b89ed3b72093174d19b50afcf8ed6c6a8/src/RTClib.cpp#L281 and the C environment variables __DATE__, __TIME__  -- Rather than re-upload the code, you might need to re-compile to code to update the time encoded in the binary file.


text:
Is there something that I need to do to make the code from this answer compile?
I tried to compile the following code (using Arduino 1.8.16 with an esp8266-12)
extern volatile unsigned long timer0_millis;
unsigned long new_value = 0;

void setup(){
  //Setup stuff
}

void loop(){
  //Do stuff
  //--------

  //Change Millis
  setMillis(new_value);
}

void setMillis(unsigned long new_millis){
  uint8_t oldSREG = SREG;
  cli();
  timer0_millis = new_millis;
  SREG = oldSREG;
}

from an answer to this question, but I get the following error
 error: 'SREG' was not declared in this scope
   uint8_t oldSREG = SREG;
                 ^
exit status 1
'SREG' was not declared in this scope

I wouldn't necessarily want to use this code for any real purpose, other than as an exercise in learning.  What am I missing?  What is SREG ?

SREG is the processor status register. One of the bits in there is the interrupt flag, which is cleared with the cli() command and reset at the end of the function. Why the original poster used the register instead of just using cli/sei is unclear. (Note: Instead of cli() and sei() the arduino documentation uses the much clearer equivalents noInterrupts() and interrupts().)
This SREG register is, in this form, hardware specific and therefore not available if you're using the esp8266 toolchain. The above code builds fine with an Arduino Uno or similar board. To build for the esp8266, change the code to:
void setMillis(unsigned long new_millis){
  noInterrupts();
  timer0_millis = new_millis;
  interrupts();
}

I don't have such a board, so I can't verify it really works on this board. You might get a linker error about a non-existing timer0_millis variable.

Re “Why the original poster used the register instead of just using cli/sei is unclear”: If setMillis() is ever called from a critical section (a context where interrupts are turned off), you don't want it to enable interrupts before returning.

Ok, that makes sense, but is a bit beyond the point he's trying to make there, I think.


text:
Is there any way to do real time voice communication via bluetooth on arduino?
Is there any way to send and play voice between two arduino projects which has connected via blutooth modules.
1st device ( sender ) : has microphone and bluetooth module to send voice.
2nd device ( reciever ) : has bluetooth module and speaker to play that voice on real time.like an phone call.
Is this possible to do with arduino or any other microcontroller?
Thank you.

Why use a microcontroller when there are bluetooth modules that do that already?

You haven't specified, which bluetooth modules you have, but most likely you have the standard HC-05 or HC-06 modules. Then the answer is somewhat "no". You may get it to work, but it will be very hacky and low quality audio. These are not made for audio. There are bluetooth modules made for audio, which also use an audio protocol in bluetooth (in contrast to the HC-05/6 modules)

with an esp32 you get into plausibility, but not with an UNO.


text:
Where to go after Arduino?
I apologise in advance if this question is not right for this Stack or if it has been answered before but here goes. I have been learning C/C++ using the Arduino Uno and have gotten the hang of it now (I have knowledge of other programming languages so it wasn't too difficult to get in the rhythm). I was wondering how I would go about creating a standalone solution if I wanted to display information on four or five displays similar to These. I would pull data from a network to display on them too so I would also need to accommodate an ethernet or WiFi shield.
I appreciate any help or pointers in the right direction that can get me started on my journey to creating some custom embedded systems (if that is indeed what I am describing).

continue with Arduino for this project

There are a lot of much more powerful boards available (especially if you move from ATmega to ARM).  I'm partial to the Teensy boards myself but Adafruit also makes some nice ARM-based boards.  For example, I'm currently developing a multi-user, Arduino-compatible Unix-ish OS on one of the latter (48MHz ARM, 256kB flash, 32kB SRAM) and it runs great.  Honestly, controlling 5 non-graphical LCDs over I²C is should be easily doable on an Uno but if you need more power there are lots of options available.
(No affiliation to either of those companies)

You can use an ESP8266 or ESP32. This makes it easy to transmit data via WiFi. You can also use the Raspberry Pi, which is much more powerful.

Uno's major limitation is it's 2KB of RAM. If your project can live within that, an Uno can host it.
The display you pointed to is an I2C device and can be bussed, so Uno pin count won't be a limitation. Current might be, and you may need to power the displays independently of the Uno.
The ESP-01 module makes a good Wifi accessory which you can build onto a proto-shield or wire separately. If your Uno is powered at 5v as most are, you'll need to provide 3.3v power to the ESP, and a voltage divider on the ESP's receive pin to reduce the serial input from the Uno to 3.3v.
Update:Upon re-reading, your title suggests you want to move on from an Uno, and you've mentioned a stand-alone solution.
There are many more capable boards available. Arduino Mega is one which would be an easy, almost trivial, transition up from Uno, in flash memory, RAM, and available I/O.
If by "stand-alone" you meant "roll your own", there are any number of how-to projects on the web for rolling your own Atmega 328p-based clone of an Uno.
The direction you take really depends on your project needs and/or your personal preference.


text:
Adafruit fingerprint sensor timer to exit out of enrolling
I have the following fingerprint sensor: Rugged Panel Mount Fingerprint Sensor with Bi-Color LED Ring [R503] : ID 4651 : $39.95 : Adafruit Industries, Unique & fun DIY electronics and kits
Also during the enrollment process, it keeps waiting till the user places the finger and completes the enrollment. Due to this piece of code : while (! getFingerprintEnroll() ) is there a way that I could put a timer for 60 seconds and if there is no enrollment within that time exit that function?
Can someone please help me with that. Thanks!
Below is the code
#include <Adafruit_GFX.h>
#include <Adafruit_ST7735.h>
#include <Adafruit_ST7789.h> // Hardware-specific library for ST7789
#include <SPI.h>
#include <Bounce2.h> // https://github.com/thomasfredericks/Bounce2
#include <EEPROM.h>

//#define WHITE_LED 43

//D v16 debounce algorithm
Bounce2::Button button = Bounce2::Button(); // INSTANTIATE A Button OBJECT
#define BUTTON_PIN 7 // WE WILL attach() THE BUTTON TO THE FOLLOWING PIN IN setup()

//D v15 for audrino to connect to fingerprint sensor
//D v2
#if (defined(__AVR__) || defined(ESP8266)) && !defined(__AVR_ATmega2560__)
// For UNO and others without hardware serial, we must use software serial...
// pin #2 is IN from sensor (GREEN wire)
// pin #3 is OUT from arduino  (WHITE wire)
// Set up the serial port to use softwareserial..
SoftwareSerial mySerial(2, 4);

#else
// On Leonardo/M0/etc, others with hardware serial, use hardware serial!
// #0 is green wire, #1 is white
#define mySerial Serial1

#endif

//D v15 for audrino to connect to display
#if defined(ARDUINO_FEATHER_ESP32) // Feather Huzzah32
#define TFT_CS         14
#define TFT_RST        15
#define TFT_DC         32

#elif defined(ESP8266)
#define TFT_CS         4
#define TFT_RST        16
#define TFT_DC         5

#else
// For the breakout board, you can use any 2 or 3 pins.
// These pins will also work for the 1.8" TFT shield.
#define TFT_CS        10
#define TFT_RST        9 // Or set to -1 and connect to Arduino RESET pin
#define TFT_DC         8
#endif

Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);

// OPTION 1 (recommended) is to use the HARDWARE SPI pins, which are unique
// to each board and not reassignable. For Arduino Uno: MOSI = pin 11 and
// SCLK = pin 13. This is the fastest mode of operation and is required if
// using the breakout board's microSD card.

// For 1.44" and 1.8" TFT with ST7735 use:
Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_RST);

// For 1.14", 1.3", 1.54", and 2.0" TFT with ST7789:
//Adafruit_ST7789 tft = Adafruit_ST7789(TFT_CS, TFT_DC, TFT_RST);

// OPTION 2 lets you interface the display using ANY TWO or THREE PINS,
// tradeoff being that performance is not as fast as hardware SPI above.
//#define TFT_MOSI 11  // Data out
//#define TFT_SCLK 13  // Clock out

// For ST7735-based displays, we will use this call
//Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_MOSI, TFT_SCLK, TFT_RST);

// OR for the ST7789-based displays, we will use this call
//Adafruit_ST7789 tft = Adafruit_ST7789(TFT_CS, TFT_DC, TFT_MOSI, TFT_SCLK, TFT_RST);

// D v15 need to add the following section back to determine the steps and the adc value
//DONT DELETE THE FOLLOWING SECTION
/*
  //D v1
  int readPin=A4;
  int V2=0; //D v5, v2-> analog voltage read by the pin
  int V1=0; //D v5, v1-> v2 converted into feet/hr
  int delayTime=500;

  //D v6
  int batt_ref_pin=A6; // D v6-> pin A6 connected to the vesc temp pin
  int battery_ref=80; // D v6-> comparing it to less than 0.3V
  int low_batt;
*/

//D v16 this to detect it the switch is on or off state.. if high then searching(default) and if low then enrolling
const int DIN_PIN = 7;

//D v8.. initialize sum with 1 and ID with 1
int sum1 = 0; //D v8 initilally put that as 1, so when it went into the sum(), it started as print 2 and not print 1, so modifying that to 0
int sum();
int id = 1;

//D v19 storing data in eeprom, so need extra variables to stores those data
int addr1 = 0; // D v19 storing the value of sum1 in this addr. initally started with 0 value
int var1 = 0; //D v19 storing the value which is retrieved from sum1 and then comparing to see if it is 0 (when the code runs for the first time) and nth number when running it for n-1 time
int var2 = 0; //D v19 storing the value which is retrieved from addr1 and then comparing to see if it is 0 (when the code runs for the first time) and nth number when running it for n-1 time
int addr2 = 205; //D v19 constant address where I can store and read data from.. this is used to write the data to sum and read it back
int addr3 = 206; //D v19 constant address where I can store and read data from.. this is used to write the data to addr1 and read it back

//D v20 stop the fingerprint enrolling after 60 seconds
unsigned long myTime;
unsigned long myTime60 = 60001;

void setup() {

  //D v16 debounce algo
  button.attach( BUTTON_PIN, INPUT ); // USE EXTERNAL PULL-UP
  button.interval(5);// DEBOUNCE INTERVAL IN MILLISECONDS
  button.setPressedState(HIGH); // INDICATE THAT THE LOW STATE CORRESPONDS TO PHYSICALLY PRESSING THE BUTTON // code modifed from Low to high in order to make the fingerprint sensor work

  pinMode( DIN_PIN, INPUT_PULLUP );
  tft.initR(INITR_144GREENTAB); // Init ST7735R chip, green tab

  // OR use this initializer (uncomment) if using a 1.3" or 1.54" 240x240 TFT:
  //tft.init(240, 240);           // Init ST7789 240x240

  // tft print function!
  tftPrintTest();

  //D v2
  Serial.begin(9600);
  /*while (!Serial);  // For Yun/Leo/Micro/Zero/...
    delay(100);*/ // Adding these 2 lines breaks the clue and does not display half of the code below it
  /*Serial.println("\n\nAdafruit finger detect test nAdafruit Fingerprint sensor enrollment");*/

  // set the data rate for the sensor serial port
  finger.begin(57600);
  delay(5);
  if (finger.verifyPassword()) {
    // tft.println("Found fingerprint sensor!");
  } else {
    tft.println("Did not find fingerprint sensor :(");
    while (1) {
      delay(1);
    }
  }

  //arcada.display->println(F("sensor parameters"));
  finger.getParameters();
  finger.getTemplateCount();

  if (finger.templateCount == 0) {
    // arcada.display->print("Sensor doesn't contain any fingerprint data. Please run the 'enroll' example.");
  }
  else {
    //arcada.display->println("Waiting for valid finger...");
  }
}

void loop() {
  button.update();// D v16 debounce algo
  int value;
  value = digitalRead( DIN_PIN );
  tft.setTextColor(ST77XX_GREEN);
  tft.setCursor(0, 10);

  //D v16 make a pin work as a button press

  getFingerprintID();
  delay(50);
  //D v6 button A pressed
  if ( value == HIGH && button.pressed()) {
    /*  tft.setTextWrap(false);
      tft.fillScreen(ST77XX_BLACK);*/

    //D v18 added this scetion to avoid overwrite of data when the fringer print sensor is searching for data and user presses a button
    delay(100);
    tft.setCursor(0, 0);
    tft.fillScreen(ST77XX_BLACK);
    getFingerprintID();
    delay(50);

    //D v16 need to remove the comment from  line below
    //tft.println("Ready to enroll!");

    //D v6 removing this section. So it will always enroll as ID 1
    //Serial.println("Please type in the ID # (from 1 to 127) you want to save this finger as...");

    id = sum(); //D v8 calling this function to mention the ID number
    tft.println("Enrolling ID # ");
    tft.println(id);

    //D v20
    myTime = millis();
    if ((unsigned long)(myTime60 - myTime) >= 1)
    {
      //while (!  getFingerprintEnroll() );
      getFingerprintEnroll();
    }
    else {}
  }
  //D v6 button B pressed
  else {
    /*     tft.setTextWrap(false);
      tft.fillScreen(ST77XX_BLACK);*/
    Serial.begin(9600);
    /* while (!Serial);  // For Yun/Leo/Micro/Zero/...
      delay(100);*/ // Adding these 2 lines breaks the clue and does not display half of the code below it
    /*  delay(500);
      tft.setCursor(0, 0);
      tft.fillScreen(ST77XX_BLACK);*/
    tft.println("fingerprnt detect tst");

    // set the data rate for the sensor serial port
    finger.begin(57600);
    delay(5);
    if (finger.verifyPassword()) {
      /*  delay(500);
        tft.setCursor(0, 0);
        tft.fillScreen(ST77XX_BLACK);*/
      tft.println("Found fingerSensor");
    } else {
      tft.println("Did not find fingerprint sensor :(");
      while (1) {
        delay(1);
      }
    }

    //arcada.display->println(F("sensor parameters"));
    finger.getParameters();
    finger.getTemplateCount();

    if (finger.templateCount == 0) {
      // arcada.display->print("Sensor doesn't contain any fingerprint data. Please run the 'enroll' example.");
    }
    else {
      tft.println("Waiting for valid finger...");
      /*    delay(50);
        tft.setCursor(0, 0);
        tft.fillScreen(ST77XX_BLACK);*/

      // arcada.display->print("Sensor contains "); arcada.display->print(finger.templateCount); arcada.display->println(" templates");
    }
  }
}

// D v6 enroll fingerprint
uint8_t getFingerprintEnroll() {

  int p = -1;
  // arcada.display->println("Waiting for valid finger to enroll as 1"); /*Serial.println(id); */ // D v6 commenting this line
  while (p != FINGERPRINT_OK) {
    p = finger.getImage();
    switch (p) {
      case FINGERPRINT_OK:
        tft.println("Image taken");
        break;
      case FINGERPRINT_NOFINGER:
        //tft.println(".");
        break;
      case FINGERPRINT_PACKETRECIEVEERR:
        tft.println("Communication error");
        break;
      case FINGERPRINT_IMAGEFAIL:
        tft.println("Imaging error");
        break;
      default:
        tft.println("Unknown error");
        break;
    }
  }

  // OK success!

  p = finger.image2Tz(1);
  switch (p) {
    case FINGERPRINT_OK:
      //tft.println("Image converted");
      break;
    case FINGERPRINT_IMAGEMESS:
      tft.println("Image too messy");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
      tft.println("Communication error");
      return p;
    case FINGERPRINT_FEATUREFAIL:
      tft.println("Could not find fingerprint features");
      return p;
    case FINGERPRINT_INVALIDIMAGE:
      tft.println("Could not find fingerprint features");
      return p;
    default:
      tft.println("Unknown error");
      return p;
  }

  tft.println("Remove finger");
  delay(2000);
  p = 0;
  while (p != FINGERPRINT_NOFINGER) {
    p = finger.getImage();
  }
  Serial.print("ID 1"); /*Serial.println(id); */// D v6 commenting this line
  p = -1;
  tft.println("Place finger again");
  while (p != FINGERPRINT_OK) {
    p = finger.getImage();
    switch (p) {
      case FINGERPRINT_OK:
        tft.println("Image taken");
        break;
      case FINGERPRINT_NOFINGER:
        // tft.println(".");
        break;
      case FINGERPRINT_PACKETRECIEVEERR:
        tft.println("Communication error");
        break;
      case FINGERPRINT_IMAGEFAIL:
        tft.println("Imaging error");
        break;
      default:
        tft.println("Unknown error");
        break;
    }
  }

  // OK success!

  p = finger.image2Tz(2);
  switch (p) {
    case FINGERPRINT_OK:
      //  tft.println("Image converted");
      break;
    case FINGERPRINT_IMAGEMESS:
      tft.println("Image too messy");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
      tft.println("Communication error");
      return p;
    case FINGERPRINT_FEATUREFAIL:
      tft.println("Could not find fingerprint features");
      return p;
    case FINGERPRINT_INVALIDIMAGE:
      tft.println("Could not find fingerprint features");
      return p;
    default:
      tft.println("Unknown error");
      return p;
  }

  // OK converted!
  p = finger.createModel();
  if (p == FINGERPRINT_OK) {
    tft.println("Prints matched!");
  } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
    tft.println("Communication error");
    return p;
  } else if (p == FINGERPRINT_ENROLLMISMATCH) {
    tft.println("Fingerprints did not match");
    delay(500);
    // delay(500);
    tft.setCursor(0, 0);
    tft.fillScreen(ST77XX_BLACK);
    return p;
  } else {
    tft.println("Unknown error");
    return p;
  }

  tft.print("ID # "); tft.print(id); // D v6 commenting this line
  p = finger.storeModel(id); // D v6 commenting this line
  if (p == FINGERPRINT_OK) {
    {
      int sum();
    }
    tft.println("Stored!");
    delay(1500);
    tft.setCursor(0, 0);
    tft.fillScreen(ST77XX_BLACK);
  } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
    tft.println("Communication error");
    delay(500);
    tft.setCursor(0, 0);
    tft.fillScreen(ST77XX_BLACK);
    return p;
  } else if (p == FINGERPRINT_BADLOCATION) {
    tft.println("Could not store in that location");
    return p;
  } else if (p == FINGERPRINT_FLASHERR) {
    tft.println("Error writing to flash");
    return p;
  } else {
    tft.println("Unknown error");
    return p;
  }
  return true;
}

// D v6 search fingerprint
uint8_t getFingerprintID() {
  uint8_t p = finger.getImage();
  switch (p) {
    case FINGERPRINT_OK:
      // tft.println("Image taken");
      break;
    case FINGERPRINT_NOFINGER:
      tft.println("No finger detected");

      //arcada.display->setTextColor(ARCADA_RED); // D v4
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
      //tft.println("Communication error");
      return p;
    case FINGERPRINT_IMAGEFAIL:
      //tft.println("Imaging error");
      return p;
    default:
      // tft.println"Unknown error");
      return p;
  }

  // OK success!

  p = finger.image2Tz();
  switch (p) {
    case FINGERPRINT_OK:
      //tft.println("Image converted");
      break;
    case FINGERPRINT_IMAGEMESS:
      //tft.println("Image too messy");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
      //tft.println("Communication error");
      return p;
    case FINGERPRINT_FEATUREFAIL:
      //tft.println("Could not find fingerprint features");
      return p;
    case FINGERPRINT_INVALIDIMAGE:
      //tft.println("Could not find fingerprint features");
      return p;
    default:
      // tft.println("Unknown error");
      return p;
  }

  // OK converted!
  p = finger.fingerSearch();
  if (p == FINGERPRINT_OK) {
    tft.setCursor(0, 60);
    tft.println("Found print match!");
    /*    delay(5000);
      tft.setCursor(0, 0);
      tft.fillScreen(ST77XX_BLACK);*/
    //arcada.display->setTextColor(ARCADA_GREEN); // D v4
  } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
    //tft.println("Communication error");
    return p;
  } else if (p == FINGERPRINT_NOTFOUND) {
    tft.println("Unknown fingerprnt");
    //arcada.display->setTextColor(ARCADA_BLUE); // D v4
    return p;
  } else {
    //tft.println("Unknown error");
    return p;
  }

  // found a match!
  //tft.print("Found ID #"); tft.print(finger.fingerID);
  //tft.print(" with confidence of "); tft.print(finger.confidence);

  return finger.fingerID;
}

// returns -1 if failed, otherwise returns ID #
int getFingerprintIDez() {
  uint8_t p = finger.getImage();
  if (p != FINGERPRINT_OK)  return -1;

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

  p = finger.fingerFastSearch();
  if (p != FINGERPRINT_OK)  return -1;

  // found a match!
  //tft.print("Found ID #"); tft.print(finger.fingerID);
  //tft.print(" with confidence of "); tft.print(finger.confidence);
  return finger.fingerID;
}

void tftPrintTest() {
  tft.setTextWrap(true);
  tft.fillScreen(ST77XX_BLACK);
  tft.setCursor(0, 0);
  tft.setTextColor(ST77XX_GREEN);
  tft.setTextSize(1);
  // tft.println("Hello World!");
}

//D v8 function to start counting the ID number
/*int sum()
  {
  sum1=sum1+1;
  EEPROM.write(sum1, sum1);
  return sum1;
  }*/

//D v19 updating the above logic to store data in eeprom and retrieving the data after reset or poweroff.. Refer to page 27, 28 for code and flowchart
//EEPROM data from : https://roboticsbackend.com/arduino-store-int-into-eeprom/   , https://www.norwegiancreations.com/2017/02/using-eeprom-to-store-data-on-the-arduino/
//https://roboticsbackend.com/how-to-save-values-on-arduino-with-eeprom/     , audrino forum and adafruit forum,
// EEPROM get(): https://www.arduino.cc/en/Reference/EEPROMGet   ; EEPROM put(): https://www.arduino.cc/en/Reference/EEPROMPut ; EEPROM read and write: https://randomnerdtutorials.com/arduino-eeprom-explained-remember-last-led-state/
int sum()
{
  var1 = EEPROM.read(addr2); // D v19 read the value from addr 205 and see if it has any ID already stored in it
  var2 = EEPROM.read(addr3); // D v19 read the value from addr 205 and see if it has any ID already stored in it

  if (var1 != 0 && var2 != 0) // D v19 check if this code is running for the first time. If yes then the ID should be set to sum1 and addr1 would be 0, so that ID is 1. If not continue from where it was left
  {
    sum1 = var1;
    addr1 = var2;
  }
  else
  {
    sum1 = 0;
    addr1 = 0;
  }

  sum1 = sum1 + 1;
  addr1 = addr1 + 1;
  EEPROM.write(addr1, sum1); //D v19 store the ID value in the corresponding addr
  EEPROM.write(addr2, sum1); // D v19 store the sum1 value in address 205
  EEPROM.write(addr3, addr1); // D v19 store the addr1 value in address 205
  return sum1;
}

yes there is a way ... hint: monitor the value of millis()

Hi @jsotola: I have done that but that doesn't fix the issue. Below is the snippet of the  code where I have written it myTime = millis();     if ((unsigned long)(myTime60 - myTime) >= 1)     {       //while (!  getFingerprintEnroll() );       getFingerprintEnroll();     }


text:
Audrino mkr1500 keeps going offline
I am using a MKR1500 with an Arduino SIM. I am able to upload the code on the device using the web editor. But when once I am done uploading the code, the device shows status offline and I am unable to check if the data is changing in the dashboard. I am running the below code to test. Also if i check when was the last time it was active, it generally shows before flashing. Also found that when I detach the device from the web UI and select it again, it shows up the last active timing as when it was detached. But during that time I saw it was inactive. Is there something that i am missing?
Can someone please help me with it.
Thanks!
int readSensor;
void setup() {
  // Initialize serial and wait for port to open:
  Serial.begin(9600);
  // This delay gives the chance to wait for a Serial Monitor without blocking if none is found
  delay(1500);
  Serial.println("Hello world");
  // Defined in thingProperties.h
  initProperties();
  // Connect to Arduino IoT Cloud
  ArduinoCloud.begin(ArduinoIoTPreferredConnection);
  setDebugMessageLevel(2);
  ArduinoCloud.printDebugInfo();
}
void loop() {
  ArduinoCloud.update();
  // Your code here
  int sensor1 = analogRead(A1);
  int carbonMonoxide = analogRead(A2);
  int methaneSensor = analogRead(A3);
  Serial.println(sensor1);
  Serial.println(carbonMonoxide);
  Serial.println(methaneSensor);
  delay(1000);
 }
void onADCvalueChange() {
  // Do something
}

The mkr1500 is not compatible with the sim right only the mkr1400 is working with the sim SORRY!
Check The Page store.arduino.cc/digital/sim

So can I use any other sim to make it work. Seems to be that my other SIM(T mobile, AT & T) also doesnt seem to work. The arduino sim seems to have some activation issue it seems, just heard back from the arduino team

I was able to get the MKR1500 online using a Soracom sim card. Seems to be that the T-mobile nbiot sim are a pian to get them talking to the cloud.. Thanks for all the help!

sorry for the late reply. I think 1500 is not built for GSM capibilitys please check what the mkr board is for


text:
How does one wire OV7670 camera with Arduino Due?
The parts that I want to interface together are:

Arduino Due
OV7670 Camera Module
3.5" TFT Touchscreen LCD (uses MCUFRIEND_kbv library)

My goal is to get the video feed from the camera to the LCD screen. Any help will be appreciated.

I am working with small project same in little bit like what you trying to do..
starting with..
1- Arduino UNO + OV7670 + 2.4" TFT LCD (I got not clear live Image)..
so I made some changes..
2- Arduino DUE + OV7670 Live Image (still working with, having problem in reading Image) want to compile the result Image (convert it to text) then sending the result to (3) by serial Port
3- Arduino UNO + 3.5" TFT LCD (it works)..
by the way  Arduino UNO + OV7670 Live Image (worked perfectly), but I am trying to get same project using DUE.. (faster speed & maybe could deal with Image too..)
here link of how OV7670 work with Arduino DUE..
https://www.instructables.com/How-to-Connect-OV7670-to-Arduino-Due/
.....

I tried the link you provided (and many others) before coming to stackexchange for help. I wanted to use the OV7670 for sending video feed to 3.5" Touchscreen display. As I was short on time, I did move on to using OV2640 with Arducam chipset as it has libraries available for Arduino Due. So far, the process has been smooth with OV2640 module.


text:
How to bring WiFi back up if woken from deepSleep(WAKE_RF_DISABLED)
I'm trying to build a sensor that should update an MQTT broker only if something changes. So every few seconds it's supposed to wake up just enough to check a few inputs, compare them with the last time it woke up, and only if there has been a change should it connect to the broker and write the updates. I don't expect many updates per day, but if I sleep more than 10 seconds, I might miss them.
I'm using WiFi.forceSleepBegin() and WiFi.forceSleepWake(), mainly based on these articles. But there is this tempting option of ESP.deepSleep(n, WAKE_RF_DISABLED)
The API that I found only mentions this:

If you implement deep sleep with WAKE_RF_DISABLED and require WiFi functionality on wake up, you will need to implement an additional WAKE_RF_DEFAULT before WiFi functionality is available.

Do I read this correct if I understand that I would need to make another deepSleep just to wake up again with WiFi back active? Or is there an easier way to boot up the WiFi after such a sleep?
Thank you

WiFi.forceSleepBegin();
delay(1);
WiFi.forceSleepWake();
delay(1);

Source: GitHub
That also works, I tested it December 2020.  Thanks to Erik Bakke for finding it.  It's a bit more clean than another Deep Sleep boot with the modem enabled.  Igrr and I both struggled to find a way to wake the modem, and Erik mixed the magic sauce.  Hopefully it still works today with the changes to the core WiFi files.

This is not really an answer...

Yes, you understood correctly; after using ESP.deepSleep(n, WAKE_RF_DISABLED) to disable WiFi, the most reliable method to re-enable it is to call ESP.deepSleep(1, WAKE_RF_DEFAULT). Then connect to WiFi on the next wake (which should be in 1 second). Apparently, WAKE_RFCAL and WAKE_NO_RFCAL also result in WiFi working.
A cheap way to approach this, is to normally sleep with WAKE_RF_DISABLED but when your WiFi connection fails, sleep with WAKE_RF_DEFAULT to make the next connection more likely to be successful.
If you want a more elegant, but slightly more complex solution, you can use the RTC memory to store the known WiFi state when you sleep; so when you sleep with WAKE_RF_DISABLED, you'll know that you'll have to reset with WAKE_RF_DEFAULT before trying to connect. And, when you wake again, you'll know the WiFi has been enabled.
As mentioned in another answer, after using WAKE_RF_DISABLED, you could call WiFi.forceSleepBegin() and then immediately call WiFi.forceSleepWake() to try to bring the WiFi back up without resetting. While I have actually found this to work, sadly it seems to be unreliable. Seems like it might work while on USB power, but when changing to another power source, it stops working. I'm not sure why. When using that approach, sometimes the MCU will consume only 40 mA when it's supposed to consume 70 mA with WiFi on, so this suggests to me that the WiFi doesn't properly initialize.
All that being said, I would suggest that using WAKE_RF_DISABLED is quite extreme. Like in your original solution, I have found that you can avoid using WAKE_RF_DISABLED altogether if you call WiFi.forceSleepBegin() immediately when the device starts (i.e. at the top of your setup() function), and then WiFi.forceSleepWake() when you want to use WiFi. When the device starts, there is only perhaps 50-100ms when the device is using 70mA before WiFi is turned off. This is probably acceptable for most low power designs.