text:
Why am I getting "expected primary-expression before '.' token"?
I know this is a common question but the truth is every code is different. Sometimes it's hard to apply the concept to your code, it does not work. So please help me. What is wrong with this code? I got it from GitHub. I'm trying to compile it first before I can do a little modification, it sends temp and humidity data to ThingSpeak cloud servers.
#include <DHT.h>  // Including library for dht
#include <ESP8266WiFi.h>

String api_key = "YOUR API KEY"; // Enter your Write API key from ThingSpeak
const char *ssid = "YOUR WIFI SSID"; // replace with your wifi ssid and wpa2 key
const char *pass = "YOUR WIFI PASSWORD";
const char* server = "api.thingspeak.com";

#define DHTPIN 1 // pin where the dht11 is connected
DHT dht;

WiFiClient client;

void setup() {
  Serial.begin(115200);
  delay(10);
  pinMode(2, OUTPUT);
  digitalWrite(2, 0);
  Serial.println("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, pass);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
}

void loop() {
  int chk = DHT.read(DHTPIN);
  float hum = DHT.humidity;
  float temp = DHT.temperature;
  if (isnan(hum) || isnan(temp)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }
  if (client.connect(server, 80)) {
    // "184.106.153.149" or api.thingspeak.com
    String data_to_send = api_key;
    data_to_send += "&field1=";
    data_to_send += hum;
    data_to_send += "&field2=";
    data_to_send += temp;
    data_to_send += "\r\n\r\n";
    client.print("POST /update HTTP/1.1\n");
    client.print("Host: api.thingspeak.com\n");
    client.print("Connection: close\n");
    client.print("X-THINGSPEAKAPIKEY: " + api_key + "\n");
    client.print("Content-Type: application/x-www-form-
    urlencoded\n");
    client.print("Content-Length: ");
    client.print(data_to_send.length());
    client.print("\n\n");
    client.print(data_to_send);
    delay(1000);
    Serial.print("Temperature: ");
    Serial.print(temp);
    Serial.print(" degrees Celcius, Humidity: ");
    Serial.print(hum);
    Serial.println("%. Send to Thingspeak.");
  }
  client.stop();
  Serial.println("Waiting...");
  // ThingSpeak needs minimum 15 sec delay between updates, I've set it to 30 seconds
  delay(10000);
}

When I compile I get this error,
  Arduino: 1.8.10 (Windows 10), Board: "NodeMCU 1.0 (ESP-12E
  Module), 80 MHz, Flash,
  Legacy (new can return nullptr), All SSL ciphers (most
  compatible),
 4MB (FS:2MB OTA:~1019KB), 2, v2 Lower Memory, Disabled, None, Only Sketch, 115200"

    C:\Users\Agent 96\Desktop\thingspeak\thingspeak.ino: In function 'void loop()':

   thingspeak:37:20: error: expected primary-expression before '.' token

  int chk = DHT.read(DHTPIN);

                ^

  thingspeak:38:22: error: expected primary-expression before '.' token

  float hum = DHT.humidity;

                  ^

  thingspeak:39:23: error: expected primary-expression before '.' token

  float temp = DHT.temperature;

                   ^

  Multiple libraries were found for "DHT.h"
  Used: C:\Users\Agent
  Not used: C:\Users\Agent
  Multiple libraries were found for "ESP8266WiFi.h"
  Used: C:\Users\Agent
  exit status 1
  expected primary-expression before '.' token

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

Please help, I'm kind of a beginner.

Change three lines right after loop() to these:
  int chk = dht.read(DHTPIN);
  float hum = dht.humidity;
  float temp = dht.temperature;

Change 'DHT' into lower case letters. DHT is the class and dht is the object of the DHT class.
Also you have multiple copy of these libraries: DHT.h and Esp8266WiFi.h. Check your cuurent directory where your Arduino code is and also Documents->Arduino->Libraries directory. These libraries should be in the  Documents->Arduino->Libraries directory.

You defined DHT as dht. So you'll have to replace those DHT with dht and you'll be good to go.


text:
How can I interface EEPROM in websocket via Arduino?
I am at beginner level and I wanted to implement EEPROM write after receiving data from a websocket. If the websocket doesn't receive any data within 5 seconds then I want to write to EEPROM the value I sent via websocket to turn on and off the led.
Here is my code please if you can help me out to solve this problem. Thank you. I have modified the code for my need, but I need EEPROM for websocket if possible.
#include <ESP8266WiFi.h>
#include <WebSocketsServer.h>
#include <Hash.h>
#include <ESP8266WebServer.h>
#include <EEPROM.h>

WiFiServer server(80);
WebSocketsServer webSocket = WebSocketsServer(81);

const int pin_led = 5;
unsigned int value;
String data;
const char *msg_toggle_led = "toggleLED";
const char *msg_get_led = "getLEDState";
char msg_buf[10];
int led_state = 0;
int counter = 0; // for EEPROM testing

char* ssid = "esp8266websocket_1";
char* password = "123456789";

void setup() {
  // EEPROM.begin(512);
  pinMode(pin_led, OUTPUT);
  digitalWrite(pin_led, LOW);
  Serial.begin(115200);
  Serial.println();
  Serial.println("Serial started at 115200");
  Serial.println();
  // Connect to a WiFi network
  Serial.print(F("Connecting to ")); Serial.println(ssid);
  WiFi.mode(WIFI_AP);
  IPAddress apLocalIp(10, 50, 1, 1);
  IPAddress apSubnetMask(255, 255, 255, 0);
  WiFi.softAPConfig(apLocalIp, apLocalIp, apSubnetMask);
  WiFi.softAP(ssid, password);
  WiFi.setSleepMode(WIFI_NONE_SLEEP);
  Serial.println("");
  Serial.println(F("[CONNECTED]")); Serial.print("[IP "); Serial.print(WiFi.localIP());
  Serial.println("]");
  // start a server
  server.begin();
  Serial.println("Server started");
  webSocket.begin();
  webSocket.onEvent(onWebSocketEvent);
  //Serial.print(webSocket.localIP());
}

void loop() {
  webSocket.loop();
}

// Called when receiving any WebSocket message
void onWebSocketEvent(uint8_t client_num, WStype_t type, uint8_t * payload, size_t length) {
  // Figure out the type of WebSocket event
  switch (type) {
    // Client has disconnected
    case WStype_DISCONNECTED:
      Serial.printf("[%u] Disconnected!\n", client_num);
      break;
    // New client has connected
    case WStype_CONNECTED:
      {
        IPAddress ip = webSocket.remoteIP(client_num);
        Serial.printf("[%u] Connection from ", client_num);
        Serial.println(ip.toString());
      }
      break;
    // Echo text message back to client
    case WStype_TEXT:
      Serial.printf("[%u] Text: %s\n", client_num, payload);
      webSocket.sendTXT(client_num, payload);
      // data = webSocket.getData(payload);
      Serial.printf("[%u] Received text: %s\n", client_num, payload);
      // Toggle LED
      if ( strcmp((char *)payload, "toggleLED") == 0 ) {
        counter++;
        led_state = led_state ? 0 : 1;
        //sprintf(msg_buf, "%d", led_state);
        Serial.printf("Toggling LED to %u\n", led_state);
        digitalWrite(pin_led, led_state);
        // webSocket.sendTXT(client_num, msg_buf);
        // Report the state of the LED
      } else if ( strcmp((char *)payload, "getLEDState") == 0 ) {
        sprintf(msg_buf, "%d", led_state);
        Serial.printf("Sending to [%u]: %s\n", client_num, msg_buf);
        webSocket.sendTXT(client_num, msg_buf);
        // Message not recognized
      } else {
        Serial.println("[%u] Message not recognized");
      }
      break;
    // For everything else: do nothing
    case WStype_BIN:
    case WStype_ERROR:
    case WStype_FRAGMENT_TEXT_START:
    case WStype_FRAGMENT_BIN_START:
    case WStype_FRAGMENT:
    case WStype_FRAGMENT_FIN:
    default:
      break;
  }
}

I am not using SPIFFS. I am calling a webpage in HTML which is:
<style>
input[type="text"]{
width: 90%;
height: 3vh;
}

input[type="button"]{
width: 9%;
height: 3.6vh;
}

.rxd{
height: 90vh;
}

textarea {
width: 99%;
height: 100%;
resize: none;
}

</style> <script> var Socket; function start() { Socket = new WebSocket('ws://10.50.1.1:81/'); Socket.onmessage = function(evt) { document.getElementById("rxConsole").value += evt.data; } } function enterpressed() { Socket.send(document.getElementById("txbuff").value); document.getElementById("txbuff").value = ""; } </script>

<textarea id="rxConsole" readonly></textarea>

Please help to implement EEPROM in websocket because if the websocket starts it stays there as long as clients are connected. So I need help to implement websocket for ToggleLED status to save data after 5 seconds if there is no data coming from the html webpage.

test and learn how to use the EEPROM on esp8266 with a separate test sketch without any other functions

Hello Juraj,I am at beginner level so i have done work around with EEPROM without any function but here its tricky because i am using TCP IP protocol in ESP-8266 and also websocket so if my device gets disconnected then only my EEPROM will initiate or else help me with interrupt ISR how to implement it.Kindly help thank you!

what ISR? in the sketch in the question there is no code working with EEPROM

Hello Juraj, I would like to implement it but i need some help regarding it i know i haven't used in code and that is my question sir. ISR is Interrupt Service Routine.

if you can use EEPROM in test sketch what is the problem to use it a sketch in question? and how should we know where and how in the sketch do you want to use it? and what has an ISR to do with this? there is no ISR in the sketch in question? this is a Q&A site not a forum for project guidance. https://arduino.stackexchange.com/tour

I am sorry sir but i required some guidance regarding EEPROM implementation inside my websocket sketch so kindly help me where should i have guidance regarding it. Thank you sir.

https://forum.arduino.cc/

source: Stack Exchange

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

sort: votes


text:
How to connect HC-06 BT module without pins?
So, from one popular Chinese  store I ordered a HC-06 module that I received... and due to some mistake from a store, I received a HC-06 without connecting pins. So usually HC-06 looks like this (with blue plate underneath where 4 pins are available to solder or connect):

I just received the one without this blue plate and pins:

How do I connect it to Arduino if there are no pins? Where are usual GND, TX, RX pins (is this schematics correct?)? Is it okay if I just solder a wire to some of them without this blue under-plate?
Also do I need to add some resistors or other components if I connect wires directly to these half-circle pins?
Thank you!

The small green PCB is the real HC-06 board. The blue board has 2 functions:

It breaks out the contact pads of the HC-06 to the bigger pins.
It has a voltage regulator on it so that you can provide it with 5V power, which then get's converted to 3.3V for the HC-06 (which is a 3.3V device).

The next steps depend on what Arduino board you have:

If you have a 3.3V Arduino Board, you can directly connect the pads on the HC-06 (by soldering pins or wires to them) to the corresponding Arduino pins:
Arduino <--> HC-06
  3.3V  <--> 3.3V
  GND   <--> GND
  TX    <--> RX
  RX    <--> TX

Also you can connect a fitting LED to the LED pin. I spontaneously cannot find data about the max current of this pin. But I guess it is in the range of 10 to 20 mA. Use a corresponding combination of an LED and a resistor.
If you have a 5V Arduino, you need to consider the voltage difference. On the Uno and Nano you have a 3.3V regulator on board. The regulator itself is rated for 150mA, but since it is not cooled, the limit is more like 50mA (see this forum thread). This datasheet of the HC-06 states, that it draws at max 30-40mA, so you can get away without an extra 3.3V regulator, just by connecting the both 3.3V pins on Arduino and HC-06. If the voltage regulator overheats despite being under 50mA, you need to buy an extra 3.3V voltage regulator, that can handle the current.
Don't forget to use a voltage divider on the Arduino-TX --> HC-06 RX line to divide the Arduinos 5V down to 3.3V. This line isn't even regulated by the blue breakout board, so you would need this voltage divider either way.
Ground connection and the LED are the same as in the first case.

So all in all you can still use the HC-06, just with a little bit less ease than with the blue breakout board.

So in order to use my voltage divider I have to connect 3.3V of HC-06 to the same 3.3V on my Arduino Nano board? Will it overheat then?

Connecting both 3.3V pins between Arduino and HC-06 is for the power supply. My guess is, that it won't overheat. But I have to state, that it goes rather near the limit of 50mA. I wrote it the way above, to state, that I cannot be sure about it. With an extra voltage regulator, that can provide more current, you will definitely be safe. It is your decision, if you want to try it without.

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


text:
Inserting myself in serial communication
I am assigned on a project involving Arduino and Raspbery PI. I have plenty of experience with Arduino and 0 with Raspbery or Linux. Person working quit and there are some problems that need me to start debuging.
The project involves control of input and output by Arduino and a touch screen and SMS aplication in Raspbery. They comunicate with standard Serial port using USB.
I want to read that communication on my PC terminal. What would be the simplest way of inserting myself without modifying anything on Raspbery?

What kind of Arduino?

It is not clear who is doing the talking.  Only that communications is over a USB.  So, simplest answer is to use a USB bus protocol analyzer.  Most cost hundreds of dollars.

If you use an Arduino with no native USB support, you can tap the RX and TX pins, that are connected to the USB Serial chip (some Arduino boards have multiple Serial interfaces, so you need to connect to the right one)

@Majenko Arduino Mega2560

@st2000 Raspbery sends commands and expects a reply to them, and Arduino regularly (every 300ms) sends status report

@chrisl Can I just add another pair of wires to used RX and TX pins and read it without interruption?

As st2000 stated in the comments, tapping on USB is a complex task and certainly not the way to go.
Maybe there is a program for Raspbian, that pipes the Serial data to 2 programs simultaneously. (I don't know one and that would be off topic here)
So your best way would be to tap the Serial (UART) communication between the USB-Serial chip (which translates USB to real serial UART) and the Atmega2560 (the main chip on the Arduino Mega). Reading Serial (UART) is a completely passive action. You don't disturb the communication with it; only if you try to send something from your tapping device. The Mega uses the first Serial interface for communication over USB, meaning that you need to tap the pin 0 and 1 (marked with TX and RX).
Now about the tapping device: You have multiple possibilities here. You could use the RX pins of 2 other Arduinos or of 2 USB to UART adaptors. But I would suggest to directly buy a logic analyser. That is a small USB device, that let's you plot digital signals (like the serial communication) on your PC. I use one with the software Pulseview. It can also analyse the digital signal for different communication protocols, for example UART. With the logic analyser you would reach your goal of tapping the serial communication, but you would also have a very capable tool for your future Arduino projects (you can analyse all sorts of digial signals with it). They are rather cheap (I got one with little clamps to attach it to a circuit for about 15€).
In the end, it's up to you to decide, which way you want to go and what you want to buy.

You may be able to sniff the communication from the Raspberry Pi itself,
with no extra hardware. Assuming the program on the Pi can be configured
to use a serial port other than /dev/ttyACM0, a sniffing
program could create a pseudo-terminal pair, then forward data back and
forth between /dev/ttyACM0 and the master pseudo-terminal, while
logging everything. If you point your Pi application to the slave
pseudo-terminal, you have your man-in-the-middle logger:
Arduino --(/dev/ttyACM0)-- logger --(pseudo-tty)-- application

The interesting thing about a slave pseudo-terminal is that, as far as
the application is concerned, it behaves exactly like a regular serial
port.
There seem to be quite a few implementations if this idea. C.f. the
answers to these other stack exchange questions:

How can I monitor serial port traffic?
Sniff serial port on Linux

Just as an example, the README of
interceptty states:

interceptty is designed to sit between a serial port (or other
  terminal device, or program, or socket, or something connected to a
  file descriptor) and a program which is communicating with that
  device, recording everything that goes back and forth between the two.
  It does this by opening the real device, creating a pseudo-tty, then
  forwarding everything between the two, recording whatever it sees.

If all you want to do is monitor what is going on then you can take a pair of USB to UART adaptors and connect the RX pin of each to the Arduino - one to the RX pin to see what the Arduino is receiving, and one to the TX pin to see what the Arduino is transmitting.
You then have to open both COM ports in separate applications (unless you can find an application that will allow you to open both together) to see what each channel has going through it.


text:
Resetting Arduino UNO code (newbie)
So today I started to learn Arduino uno. I have an LM35 temperature sensor and I got what I needed from it. Now it's just keep calculating till I plug it off.
I know there is a reset button. When I press it or hold it, it's closing and opening again to do the coding again. I want it to completely stop. Like when I first plug led was flashing to show arduino is connected.
And I know I can just upload another code. But I don't want that.
If it's possible please let me know.

Actually, it already did something when you turned it on when you got it: it was blinking a LED. It did not mean it was connected. A microcontroller (or controller) always does something. Although you can consider an empty endless loop as 'nothing'.
And now you overwritten that sketch with your LM35 sketch.
However, you can put the Blink sketch again in your Arduino, and it can be found here:
https://www.arduino.cc/en/Tutorial/Blink
You don't need to connect the LED, it will use the built in LED.
If you don't want the Arduino to do anything, just switch it off (disconnect the power).

When a microcontroller or a computer is powered on, it always does something. A program on a computer will return and the OS will run again. On a microcontroller there is no OS to return to, so every microcontroller program has an infinite loop.
The void loop() function of the Arduino framework is such an infinite loop. If you want your LM35 temperature code to be only run once, you can put it into the void setup() function, which is run once before going to loop(). When the loop() function is empty, the Arduino will do nothing after it returned from setup().
Otherwise, if you want to put your code into loop() for whatever reason, you can insert an infinite loop whereever you want it:
while(true);

This loops forever and does nothing. Your temperature code will only be executed on the next reset or power on.


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

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

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

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

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

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

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

@JonathasMoreira 5.23V is perfectly safe

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

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

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

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

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

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

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


text:
Why is Toolchain Not Updated with Arduino IDE Install on Mac
I have not been doing any Arduino work for about a year.  The last time I ran the Arduino IDE was in the previous version of MacOS.  Now that I have updated to the latest MacOS Version Catalina (10.15.2) I discovered that the IDE will not compile because the avr-g++ compiler is 32 bit and will not execute on the now 64-bit required MacOS.
So I did the obvious thing.  I went to the arduino.cc web site and downloaded the latest version of Arduino IDE thinking that this should solve the problem.  I updated to version 1.8.11 of the IDE but the 32-bit problem persisted.
I finally decided that the IDE was updating (new Arduino IDE app) but that the avr toolchain was not being updated.  To force this update, I deleted the entire avr toolchain from my ~/Library folder.  Now, re-running the IDE is all it took:  It discovered the toolchain missing and re-installed and installed with the correct 64 bit binaries (which were part of the new Arduino App all the time).
Perplexing -- why was the toolchain not updated with the install?  Is it a requirement to delete the existing toolchain before doing a new install of the Arduino App?

The boards packages maintained by Boards Manager and associated tools are installed in .arduino15 folder. The AVR boards package bundled with IDE is only used when there is no AVR boards package version in the .arduino15 folder.
To locate the .arduino15 folder open Preferences in IDE and there at the bottom of the window is displayed the location of the preferences file with full path to .arduino15 folder.
The content of .arduino15 folder is not changed with IDE update.

If content is not changed in .arduino15 folder than how is it installed in the first place.  I never explicitly installed that folder.  It is certain that Arduino app does indeed install it because after deleting the folder a new copy was indeed installed merely by re-running Arduino (rerun, not install).

@K7PEH, of course the folder is created if it doesn't exist and the preferences file is stored there. but boards packages are installed there only if you install them with the Boards Manager in IDE


text:
Powering Arduino and transistors with one power supply > 12V
So say you want to use transistors with your Arduino Nano to power components, which require greater than 12V. If your power supply is more than 12V, is there a way to safely use the same power supply to power the Arduino?

power components, which require greater than 12V More specific info leads to better responses.

The voltage regulator (on the Vin pin) is supposed to be provided with 12V at max, since it is not cooled (it is a linear regulator, that dissipates the excess voltage as heat). If you have significantly more, you should at best buy a little switching regulator, to directly get a regulated 5V to feed to the 5V pin of the Arduino (that's what I suggest). Be sure to use a regulator, that can provide the needed current (which also depends on what else you provide over the Arduino).
If you really don't want to use an extra regulator and you don't have much more than 12V (maybe like 15V), you might get away by cooling the voltage regulator on the Arduino. The voltage regulator on a genuine Arduino will go into emergency shutdown, if it overheats, but it will not be damaged easily. Here you could try a bit. But be careful to not stress it too much. The clones from china often have different/cheaper regulators, that will mostly be fried if you overheat them. But they are very cheap.

If powered with 12V, do those output pins still output 5V?

The output pins of the Arduino still use 5V, since the Arduino still works with 5V. The 12V only get regulated down, when you provide them to the Vin pin or the barrel jack. A dedicated voltage regulator takes the 12V and outputs 5V for the Arduino to run on. The only question is, if the voltage regulator can stand the power to dissipate, which depends on the provided input voltage and the drawn current.

Even the 5V Pin provides 5V only :) You should not connect load to it, if Vin is 12V or even higher.

The recommended input voltage for the Arduino Nano is 7-12 V, the max. 20 V.
So you could use upto 20 V, but this is indeed not advisable.
What you can do, is to use a so-called step down/boost down converter which converts the voltage back to a voltage that your Arduino Nano can (easily) handle. The voltage drop will be changed into heat, but I guess considering you are using a higher voltage power supply, you are not using battery power.
Note: this is only true for some (cheap?) converters, see the comment of DataFiddler below.

Recommendable step down converters do not turn the excess voltage into heat, but use a fast switching regulation mechanism with a better efficiency.

@DataFiddler I didn't know that, thought it was not advised to have a too much difference between input/output voltage.

That's correct for linear regulators like the one onboard Arduino.

If I understand your question you have external devices say lamp, motor, etc. There are several ways of doing it. My preferred way is to use a N-Channel MOSFET where the drain is the output, the source is ground (both the logic and power grounds need to be connected together) and the gate Is connected to the port pin that also has a 10K pull down resistor. You can use the 12V to power the Arduino via Vin as you suggested. Be sure the MOSFET is avalanche rated and will turn on at about 3V or less.
You can do the same thing with an NPN Transistor where the port pin connects to the base with a 300 Ohm resistor (you need to calculate this based on the load), emitter to the connected grounds and the collector is your  output.


text:
Where are the traces connected to RESET-EN leading?
Once again, I am following this schematic, and I am confused as to where RESET-EN connects:

This is how I have it mocked up it Fritzing, but I feel like this is incorrect:

This is the DTR output of the ATmega16u2 which is connected to RESET pin of the ATmega2560 for reset by avrdude over DTR signal before upload of the sketch. There is a trace by default. Cutting the trace disables the auto-reset. Soldering a bridge on  RESET-EN pads re-enables the auto-reset.

the schematics part you quoted in question misses the long unconnected line for the RESET label. It leads here:

So this connects RESET to gnd?

not directly. this enables the USB chip (an ATmega16u2 with a firmware) to pull-down the reset pin of the ATmega2560.

So where does the other side of the trace connect in the diagram linked above?

I enhanced the answer

Ah, so the reset pin of the Atmega 2560 is connected to the reset pin of the Atmega16u2?

And also doesn't the 16u2 come loaded with firmware or would I have to flash it myself via ICSP?

The DTR output from the 16U2 is used to Reset the 328P, 2560, etc.  The 16U2 runs the USB interface program, which can be found in one of the Arduino folders.

Again, so are the reset pins of the Atmega 2560 and the 16u2 connected?

if the reset were connected the 16u2 would reset itself too while resetting the 2560.

So then where does the RESET pin of the 2560 go, and where does the RESET pin of the 16u2 go?

@3ddavies a line with a loose end and a label in electrical schematics goes to other line(s) with a loose end with the same label

to me that would mean that the two reset pins are attatched.

RESET pin of 16u2 has a line labeled RESET2


text:
Is there an Adafruit function to invert the colors of my screen for Arduino language?
I am trying to invert the color of my OLED display screen once a button is pushed. I have the button situation figured out but I can not find a function that inverts the color. I am using these two libraries to handle my screen on the Arduino IDE.
Adafruit_GFX.h, Adafruit_SSD1306.h
Any help would be much appreciated.

When there is no such function in these libraries, then there is most likely not an Adafruit function for that. You will have to do it yourself. It depends on what exactly means inverted here. koronas answer to this question on stackoverflow states, that you just need to invert the bits of the color components. The question is about C#, but the syntax in the answer is the same in C++. Please try, if that does, what you want.

Another answer of that question states, that you would need to do a transformation in the HSV color space.

There is a function that invert the colors of your screen, you can pick either black on white or white on black, I have tried it and I have quite experience with your display, I think you should try this piece of code.
At the beginning of your Arduino code be sure that you declared the object using the same name.
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

To invert the display
display.invertDisplay(true);

To return the display again
display.invertDisplay(false);

As you said that you want a button to invert the display you might use this code I made
if(digitalRead(BUTTON_PIN)){
    display.invertDisplay(true);
}
else{
    display.invertDisplay(false);
}

Or you might use Interrupts for better performance depending on your code.
As you couldn't find on the internet, I am student and I learn alot from the internet, to for example search for such a function in an Arduino library, try searching it's documentation or it's page on GitHub then afterwards see the function you want through the pages, but don't just search the function directly it will sometimes won't work as they are not that popular.
As a last thing Here is the documents where I got the function with it's parameters from.
I hope I've helped you out. any edits in the answer is well appreciated, as I am a student.


text:
Help with Receiver / Transmitter (nRF24L01+)
Dear fellow Arduino users,
My two friends and I are having trouble on an Arduino project we are working on. We are using two Arduino Uno's and trying to have one of them send a signal to another one by a press of a button using NF24L01+ (with the antenna). Our transmitter code is as follows:

// create an RF24 object
RF24 radio(9, 8);  // CE, CSN
// the number of the pushbutton pin
const int buttonPin = 3;
// variable for reading the pushbutton status
int buttonState = 0;
//address through which two modules communicate.
const byte address[6] = "00001";
void setup()
{
  Serial.begin(9600);
  Serial.println("nrf24L01+ Transmitter Starting!\n");
// initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
radio.begin();
  radio.setRetries(15, 15);
//set the address
  radio.openWritingPipe(address);
radio.setPALevel(RF24_PA_MAX);
//Set module as transmitter
  radio.stopListening();
}
void loop()
{
  buttonState = digitalRead(buttonPin);
if (buttonState == 1) {
    Serial.write("Sending the following message: \n");
//Send message to receiver
const char text[] = "\t Hello, friend!";
Serial.write(text);
Serial.write("\n\n");

radio.write(&text, sizeof(text));

delay(1000);

}
}

On the receiver side, we have the following:

//create an RF24 object
RF24 radio(9, 8);  // CE, CSN

//address through which two modules communicate.
const byte address[6] = "00001";

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

  radio.begin();

  //set the address
  radio.openReadingPipe(0, address);
  radio.setPALevel(RF24_PA_MAX);

  //Set module as receiver
  radio.startListening();
}

void loop()
{
  //Read the data if available in buffer
  if (radio.available())
  {
    Serial.print("hello");
    char text[32] = "";
    radio.read(&text, sizeof(text));
    Serial.println(text);
  }
}

However, we are not receiving any signal on the receiving end. We are pretty sure all our pins are correct. We are wondering if anyone had any advice on how we could troubleshoot. Thank you.

you need code running on the receiver end

You also need to check wiring on both devices.


text:
Which board has the highest max current via 3.3v pin?
Is there any arduino board which can deliver 600-800ma via 3.3v pin? Maybe the Arduino due or the nano 33 ble?

Uno Plus 3.3V 800mA https://www.waveshare.com/product/arduino-2/boards-kits/arduino/uno-plus.htm

Yes, that's what i am looking for. Unfortunately, the size of the board is not ideal for my application. The nano 33 ble would be great but i can not find any information about the max current of the 3.3v pin.

why do you mention Due then? it is huge

Yes, you are right. I mentioned it because it can probably deliver around 800ma. https://www.mouser.de/arduino-due/ But I am still hoping there is a smaller board.

yes it can. better source of information is the product page at Arduino. https://store.arduino.cc/arduino-due. but like on all 3.3 V boards the MCU is on this regulator too.

why not just switch the 3.3v input with a mosfet?

Sorry, i am not familiar with mosfets. But in this case I need an extra 3.3v power supply, right?

Your USB will output only 500mA or max to max 1A in some cases. Even if your board is rated for higher output you will be restricted by your source. First step is to increase your source. Secondly check which 3.3V regulator is present on which board and check the datasheet of the regulator to get information about it.
Either ways you can externally add a high current 3.3V regulator and connect it to your 3.3V pin on the arduino. As voltages are equal no current will flow between them.
But remember your source needs to output the higher current first


text:
make servo stay at the current position when attach() is called
I use a small SG90 servo with arduino.
When I call attach() servo moves to its default position or whatever I set with write() before it.
I’d like to make servo stay at the current position when I call attach() in setup().
How can I achieve it?
I believe I can simply store last position in EEPROM. It’ll help a little. However, I’m afraid that EEPROM won’t last long.

Why would you call attach() time and again?

You can't read the servo's position, so your sketch has no chance to know the real current position.
And you found that you have to set up the initial value of the servo "driver" to the one your sketch thinks is the last known position of the servo.
So your problem boils down to these questions: "How do I store a value during power-down times?" This leads to the common solution of storing the value in the EEPROM. This is a well-known and widely accepted solution, but you already found a problem: "How could a value be stored in the EEPROM without over-stressing it?"
You need to look up the guaranteed number of write cycles for a EEPROM cell. Then you need to think about the rate you would like to save the value. Divide the values and you know how long this will work. However, in reality the EEPROM will have much better endurance.
Some ideas how to "get better":

Reduce the rate of saving. I see at least two factors: The refresh rate of the servo controlling pulse is just 50 Hz. And a servo will move between (extreme) positions only a few times per second. There might be no need to save more than once per second, or even slower, depending on your application.
Don't save if the value has not changed. Well, this should be done already at the driver level of the EEPROM. It won't hurt to read its documentation and/or its source code.
Use an as large as possible array to store the value. You will store a marker for "invalid" in all but one cell, and only this cell holds the real value. This will put the "load" of two writes per save on the EEPROM, but distribution over more than two cells will lower the average load. If you select an all-1s value as "invalid", it is actually just the same value as the erased value of the EEPROM, which is necessary the next time anyway.
Add a circuit that detects the power loss before the CPU stops. This is the most chosen solution, but only usable when the hardware can do it. You need just a few milliseconds to save the value, look up the documentation. If you implement an ISR that catches the coming power loss, save the value and await the end.


text:
ESP32 - NTP inaccuracy after deep sleep
I'm trying to create a sensor sampling project using ESP32 ( battery, solar panel and temperature affects are not part of test right now to reduce external effects that may cause/ increase such behaviour ).
In current phase, I'm only testing the sleep & waking up process.
A short description: System wakes up after deep sleep cycle, connects to Wifi, MQTT, NTP - and checks if wake up time ( wake up value is stored in ׳RTC_DATA_ATTR long calc_waketime׳ variable from previous cycle ), posting IFTTT, goes to deep sleep for another 10 min. cycle.
The phenomena I wish to share is: The longer deep sleep is the NTP has few seconds drift which gets longer (again - NTP sync has a drift and not RTC clock).
I'm aware that wake time/ RTC drifts during deep sleep ( especially in ESP8266 chips that wake up can be not accurate in terms of minute - I'm using ESP32). Since ESP32 uses RTC, waking up is very accurate ( matter of seconds ). In order to wake up in exact time ( 18:00, 18:10, 18:20... every hour ) code connects to Wifi& NTP, and verify that wake time was as intended (comparing the epoch value that was stored during the end of previous cycle and current epoch time ) if it woke up earlier, it will got to sleep for that missing time.
But - What puzzles me is why updated NTP time ( which is not related what so ever to RTC drifts ), is drifted the longer to sleep is ( for comparison : when less than a minute - almost no drift, when sleeping for 10 minutes, 3 seconds drift, 20 minutes get up to 5 seconds drifts ).
Please see NOTE(1) to witness the drift in 10 min sleep.
Posting terminal output:
some explantions: NOTE (1) displays the 3 seconds drift , NOTE(2) calculated time that was stored at previous wake cycle, NOTE (3) shows that that drift get synced during the code run - 594 sec for next wake 18:50:00.
18:39:58.032 -> 09B⸮⸮L⸮1U1V(⸮⸮⸮1m1m1F⸮Connecting to Xiaomi_D6C8 .... // WAKING UP
18:39:58.595 -> 192.168.3.186
18:39:59.013 -> now is: 1580575203               **// NOTE (1)**
18:39:59.013 -> sleep time was: 1580574611
18:39:59.048 -> expected wake time: 1580575200   // NOTE (2)
18:39:59.085 -> total time delta: 3
18:39:59.122 -> OK - WOKE UP after due time:
18:39:59.419 -> Attempting MQTT connection...connected
18:40:04.544 -> Connecting to maker.ifttt.com
18:40:04.855 -> Request resource: /trigger/send_reading/with/key/cFLymB4JT9tlODsKLFn9TA
18:40:05.376 -> HTTP/1.1 200 OK
18:40:05.376 -> Date: Sat, 01 Feb 2020 16:40:05 GMT
18:40:05.414 -> Content-Type: text/html; charset=utf-8
18:40:05.447 -> Content-Length: 52
18:40:05.480 -> Connection: close
18:40:05.515 -> X-Top-SecreTTT: VG9vIGVhc3k/IElmIHlvdSBjYW4gcmVhZCB0aGlzLCBFbWFpbCB1cyBhdCBqb2JzK3NlY3JldEBpZnR0dC5jb20uIFdlIHdhbnQgTWFrZXJzLg==
18:40:05.619 -> Server: web_server
18:40:05.619 ->
18:40:05.619 -> Congratulations! You've fired the send_reading event
18:40:05.689 -> closing connection
18:40:07.007 -> Last Sleep: 1580574611
18:40:07.007 -> Time left: 594                 // NOTE (3)
18:40:07.041 -> Going to DeepSleep for [594] sec

Relevant code:
void sleepNOW(int sec2sleep = 2700)
{
  char tmsg[30];
  sprintf(tmsg, "Going to DeepSleep for [%d] sec", sec2sleep);
  Serial.println(tmsg);
  // mqtt_pubmsg(tmsg);
  Serial.flush();
  esp_sleep_enable_timer_wakeup(sec2sleep * uS_TO_S_FACTOR);
  esp_deep_sleep_start();
}
bool getTime()
{
  delay(200);
  if (getLocalTime(&timeinfo))
  {
    time(&now1);
    delay(200);
    return 1;
  }
  else
  {
    return 0;
  }
}

bool check_awake_ontime()
{
  getTime();
  if (timeinfo.tm_year >= 120) // year 2020
  {
    if (lastsleeptime != 0)
    { // not first boot
      long current_boottime = now1;
      int t_delta = now1 - calc_waketime;
      // int t_delta1 = TIME_TO_SLEEP * 60 - (t_delta + TIME_AWAKE);
      Serial.print("now is: ");
      Serial.println(now1);
      Serial.print("sleep time was: ");
      Serial.println(lastsleeptime);
      Serial.print("expected wake time: ");
      Serial.println(calc_waketime);

      Serial.print("total time delta: ");
      Serial.println(t_delta);
      if (t_delta >= 0)
      {
        Serial.println("OK - WOKE UP after due time: ");
        return 1;
      }
      else
      {
        Serial.println("FAIL- woke up before time: ");
        sleepNOW(-1 * t_delta);
        return 0;
      }
    }
    else
    {
      return 1;
    }
  }
  else
  {
    return 0;
  }
}

inside setup()
#if USE_WIFI
  if (startWifi())
  {
    mqttConnect();
    startNTP();
#if USE_SLEEP
    check_awake_ontime();   // PLEASE PAY ATTN ONLY THIS LINE
#endif
  }

inside loop()
#if USE_SLEEP
  if (millis() >= TIME_AWAKE * 1000)
  {
    getTime();

    Serial.print("Last Sleep: ");
    Serial.println(lastsleeptime);

    long clockCount = TIME_TO_SLEEP * 60 - (timeinfo.tm_min * 60 + timeinfo.tm_sec) % (TIME_TO_SLEEP * 60);
    // Serial.print(timeinfo.tm_hour);
    // Serial.print(":");
    // Serial.print(timeinfo.tm_min);
    // Serial.print(":");
    // Serial.print(timeinfo.tm_sec);
    // Serial.println("");
    Serial.print("Time left: ");
    Serial.println(clockCount);

    lastsleeptime = now1;
    calc_waketime = now1 + clockCount;

    sleepNOW(clockCount);
  }

I'm not posting entire code, but only relevant parts.
Appreciate any help,

the NTP only sets the RTC. and NTP is not immediate

@Juraj would you recommend a delay ? since getTime() has 2 delays of 200 mili's

5 seconds is usually enough. you can do a trick. reset the RTC time to 0 and then you can check if it is set by NTP already

@Juraj can you please explain how?

sorry, I forgot that there is no API for setting the RTC time on esp32. https://arduino.stackexchange.com/questions/72010/set-the-wall-clock-time-or-change-gmt-offset-without-ntp-server/72019#72019

As Juraj commented, a 2.5 [sec] delay, solved it, and NTP update was correct.

It's OK to accept your own answer as the solution to the problem.


text:
Why does my program stop working? (MPU6050)
I'm using the DMP example from Jeff Rowberg's MPU library (with Arduino UNO) and it works well. But with this simple modification it works for a while and then stops. I don't understand why this is happening. If someone knows this will help me a lot. Thanks!
//GND - GND
//VCC - VCC
//SDA - Pin A4
//SCL - Pin A5
//INT - Pin 2

#include "I2Cdev.h"
#include "MPU6050_6Axis_MotionApps20.h"
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
#include "Wire.h"
#endif

MPU6050 mpu; //Declaramos el sensor en la dirección por defecto (0x68),AD0 a LOW

#define INTERRUPT_PIN 2 //Definir el pin de interrupciones
#define LED_PIN 13
bool blinkState = false;

//Variables de control y estado del MPU
bool dmpReady = false; // Es true si la inicialización del DMO es exitosa
uint8_t mpuIntStatus; // Mantiene el estado actual del byte de las interrupciones
uint8_t devStatus; // Devuelve el estado después de cada operación del dispositivo(0 = exitoso, !0 = error)
uint16_t packetSize; // Tamaño esprado del paquete (por defecto es 42 bytes)
uint16_t fifoCount; // Cuenta todos los valores actules en el FIFO
uint8_t fifoBuffer[64]; // Buffer de almacenamiento

//Variables de orientación y movimiento
Quaternion q;           // [w, x, y, z]
VectorInt16 aa;         // [x, y, z]
VectorInt16 aaReal;     // [x, y, z]
VectorInt16 aaWorld;    // [x, y, z]
VectorFloat gravity;    // [x, y, z]
float ypr[3];           // [yaw, pitch, roll]
float yaw;
float pitch;
float roll;
int izquierda = 0;
int derecha = 0;

volatile bool mpuInterrupt = false;
void dmpDataReady() {
  mpuInterrupt = true;
}

void setup() {
  //Iniciar comunicación con el bus I2C
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
  Wire.begin();
  Wire.setClock(400000); // 400kHz I2C clock. Comment this line if having compilation difficulties
#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
  Fastwire::setup(400, true);
#endif
  Serial.begin(38400);
  // Iniciar MPU6050
  Serial.println(F("Initializing I2C devices..."));
  mpu.initialize();
  pinMode(INTERRUPT_PIN, INPUT);

  // Comprobar  conexion
  Serial.println(F("Testing device connections..."));
  Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));

  // Iniciar DMP
  Serial.println(F("Initializing DMP..."));
  devStatus = mpu.dmpInitialize();
  // Valores de calibracion
  mpu.setXGyroOffset(219);
  mpu.setYGyroOffset(75);
  mpu.setZGyroOffset(-19); //85
  mpu.setZAccelOffset(1688);
  // Activar DMP
  if (devStatus == 0) {
    Serial.println(F("Enabling DMP..."));
    mpu.setDMPEnabled(true);
    // Activar interrupcion
    attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), dmpDataReady, RISING);
    mpuIntStatus = mpu.getIntStatus();
    Serial.println(F("DMP ready! Waiting for first interrupt..."));
    dmpReady = true;
    // get expected DMP packet size for later comparison
    packetSize = mpu.dmpGetFIFOPacketSize();
  } else {
    // ERROR!
    // 1 = initial memory load failed
    // 2 = DMP configuration updates failed
    // (if it's going to break, usually the code will be 1)
    Serial.print(F("DMP Initialization failed (code "));
    Serial.print(devStatus);
    Serial.println(F(")"));
  }
}

void loop() {
  // Si fallo al iniciar, parar programa
  if (!dmpReady) return;
  // Ejecutar mientras no hay interrupcion
  while (!mpuInterrupt && fifoCount < packetSize) {
    // AQUI EL RESTO DEL CODIGO DE TU PROGRRAMA
  }
  mpuInterrupt = false;
  mpuIntStatus = mpu.getIntStatus();
  // Obtener datos del FIFO
  fifoCount = mpu.getFIFOCount();
  // Controlar overflow
  if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
    mpu.resetFIFO();
    Serial.println(F("FIFO overflow!"));
  } else if (mpuIntStatus & 0x02) {
    // wait for correct available data length, should be a VERY short wait
    while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();
    // read a packet from FIFO
    mpu.getFIFOBytes(fifoBuffer, packetSize);
    mpu.resetFIFO();
    // track FIFO count here in case there is > 1 packet available
    // (this lets us immediately read more without waiting for an interrupt)
    fifoCount -= packetSize;
    // Mostrar Yaw, Pitch, Roll
    mpu.dmpGetQuaternion(&q, fifoBuffer);
    mpu.dmpGetGravity(&gravity, &q);
    mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
    yaw = -ypr[0] * 180 / M_PI;
    pitch = ypr[1] * 180 / M_PI;
    roll = ypr[2] * 180 / M_PI;
    if (yaw > 90) {
      izquierda = 1;
      derecha = 0;
    }
    if (roll > 90) {
      derecha = 1;
      izquierda = 0;
    }
    if (yaw < 90 && roll < 90) {
      derecha = 0;
      izquierda = 0;
    }
    Serial.print("ángulos\t");
    Serial.print(yaw);
    Serial.print("\t");
    Serial.print(pitch);
    Serial.print("\t");
    Serial.print(roll);
    Serial.print("\t");
    Serial.print("izquierda");
    Serial.print("\t");
    Serial.print(izquierda);
    Serial.print("\t");
    Serial.print("derecha");
    Serial.print("\t");
    Serial.println(derecha);
  }
}

What simple modification? And where does it stop? Have you tried to hunt down the problem by using Serial prints?

this is my modification:                                                                                yaw = -ypr[0] * 180 / M_PI;
pitch = ypr[1] * 180 / M_PI;
roll = ypr[2] * 180 / M_PI;
if (yaw > 90) {
izquierda = 1;
derecha = 0;
}
if (roll > 90) {
derecha = 1;
izquierda = 0;
}
if (yaw < 90 && roll < 90) {
derecha = 0;
izquierda = 0;
}

I've used the serial monitor to print the yaw, pitch and roll. I think it stops in this line :      if (!dmpReady) return;                                                                                But I don´t know why the dmp doesn't work.


text:
L298N Gradual Voltage Drop
I have connected my motors to L298N and it in turn to arduino. My battery is ~18 V and i used a boost converter to get 12.99V. When I run my program on Arduino Mega, I check the output voltage from the motor drive and observe that it begins from somewhere 11.99V and goes gradually down like 11.70,11.63,11.55..... till 4.03 V then it does not go down. I am attaching my circuit as a photo here. I hope sonebody could help me to find my mistake

Are you measuring voltage across motor's two terminal?

@Fahad yes, I measured voltage on the output of the motor driver. So without connecting the motor. But even when I connect the motor to the drive the motor begins to turn and because of the gradual voltage drop it stops then.

How about voltages on battery and buck converter? What happens if you wire logic levels to run the motor directly (without arduino)? Anyway you should count with the voltage drop on transistors used inside of L298 and they are two of them for single motor...

@KIIV the battery voltage is near 17.65V and on the output of the buck converter i get 12.99 V. Motors work directly connected to battery very well. And for the L298N there should be max 2 V drop. But it drops gradually until 4 V

So, voltage drops even without connecting the motors?

@Fahad yes, exatly

The connection diagram is correct. It's either a faulty L298 or buck converter. When the voltage drops to 4v check the voltage across buck converter. If it's still 12v, you know what to change.

@Fahad okay, that is a good way of determining the problematic part in the circuit.Thank you !


text:
Image from Arduino with camera ov7670 to Raspberry pi
i am stuck at sending picture to Raspberry pi from Arduino , how can i do this ? One way that i am using now is saving the picture on SD card module on the arduino , how to transfer that image to Raspberry pi? One problem is that the image on the SD card is in very "Raw format" which means , it needs to be converted to HEX and then we need to Add (bmp)headers or something i am not even sure, i have the python scripts that do this but the problem is it will slow down pi , and for my project its not acceptable that way. One other option is if i can stream the video that will be great . Some suggestions ?
Thank yoin
EDIT
About the process of Opening with HEX edtior:
The image data that Arduino is going to write to the SD card is raw image data i.e. just plain byte data-one byte for one pixel. If you try to open it as an image file then it won’t work. It is not in proper format to be read as an image. That’s why you need to write a bmp file with proper headers and use the raw image data to fill in for the pixel data in the bmp file. Now, here is the part where I cheated a little bit. I just opened up the file containing raw image data that Arduino wrote and opened it in a hex editor.
LINK: https://hkalasua.wordpress.com/2017/09/11/ov7670-arduino-sd/

I edited my question , you can check

you are misunderstanding what HEX means ... it is a human readable representation of a number, specifically a binary number ... it is easier to read FE23 than 1111111000100011 ... the file you mentioned is binary ... there is no hex conversion involved

send the image data to the RPi and use a python script to generate the bmp or png file


text:
Blank output in serial monitor
So my SIM900 GSM Shield is working fine with Netlight LED blinking and Status LED solid light, after I upload the code nothing happens about mySerial() in my serial monitor. Can I take your time for you to check this code out? I wonder if the problem lies here.
#include<SoftwareSerial.h>

//Create software serial object to communicate with SIM900
SoftwareSerial mySerial(7, 8); //SIM900 Tx & Rx is connected to Arduino #7 & #8

/*void SIM900power()
{
  pinMode(9, OUTPUT);
  digitalWrite(9,LOW);
  delay(1000);
  digitalWrite(9,HIGH);
  delay(2000);
  digitalWrite(9,LOW);
  delay(3000);
}*/
void setup() {
  // put your setup code here, to run once:
  //Begin serial communication with Arduino and Arduino IDE (Serial Monitor)
  Serial.begin(9600);
  //Begin serial communication with Arduino and SIM900
  mySerial.begin(9600);

  Serial.println("Initializing...");
  delay(1000);

  mySerial.println("AT"); //Handshaking with SIM900
  updateSerial();
  mySerial.println("AT+CSQ"); //Signal quality test, value range is 0-31 , 31 is the best
  updateSerial();
  mySerial.println("AT+CCID"); //Read SIM information to confirm whether the SIM is plugged
  updateSerial();
  mySerial.println("AT+CREG?"); //Check whether it has registered in the network
  updateSerial();
  mySerial.println("AT+COPS?"); // Check that you're connected to the network;
  updateSerial();
}

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

void updateSerial()
{
  delay(500);
  while (Serial.available())
  {
    mySerial.write(Serial.read());//Forward what Serial received to Software Serial Port
  }
  while(mySerial.available())
  {
    Serial.write(mySerial.read());//Forward what Software Serial received to Serial Port
  }
}

Output:

What is the purpose of SIM900power()? You defined it but never used it.

I've just commented it and yet it only outputs "initializing.."

your code contains a command that forces the arduino to stop and do nothing for 500 ms with every iteration of loop()

look at the arduino software serial example code and compare it to your code

This is the site where I copy the code: link. It didnt explain the part about why it was delay(500) so Im not aware of it how works. @jsotola

I will reconsider your suggestion. :)

Are you sure, that you are using the correct baudrate? When the communication does not work, but the module is behaving correctly otherwise, this might be the problem.

I figured it out! Silly me. I just rewired it. Thanks for all of your opinion. :D

@TechHermit Then please either answer your own question or delete the question. The comments are not permanent. If they get deleted others will think, that this problem wasn't solved

Step 1) Check RX TX connections
Step 2) Change your baud rate to 115200. Turn off your arduino. Turn off gsm. Start your gsm first and then your arduino.
or
Step 3) Upload Software Serial code and just send "AT" without quotes using serial monitor. If your connections are correct you should get reply as AT.
Also make sure to set the baud rates to 115200.
Most of the GSM modules have default baud rate at 115200 or have auto baud adjustment enabled but need to be power cycled.


text:
Arduino Sketch Crashes in working procedure when adding extra call
I am trying to drive a couple of motors to make a car.
I successfully wrote some code then tidied it up to procedurise it and it just kept crashing.
I've put some debug code in and narrowed it down a bit but what I am seeing makes no sense. With the code below I just call the TLeft procedure which works and drives the motor and I get the serial output:
RWheel Forward
1
2
3
4
5
ReTurn L
RWheel Forward
1
2
3
4
5
ReTurn L
RWheel Forward
1
2
3
4
5
ReTurn L
/************************
  Exercise the motor using
  the L293D chip
************************/

#define RW_ENABLE 11
#define RW_DIRA 28
#define RW_DIRB 30
#define LW_ENABLE 10
#define LW_DIRA 48
#define LW_DIRB 50

int i;

void setup() {
  //---set pin direction
  pinMode(RW_ENABLE, OUTPUT);
  pinMode(RW_DIRA, OUTPUT);
  pinMode(RW_DIRB, OUTPUT);
  pinMode(LW_ENABLE, OUTPUT);
  pinMode(LW_DIRA, OUTPUT);
  pinMode(LW_DIRB, OUTPUT);
  Serial.begin(9600);
  Serial.println("Prog Start");
  delay(1000);
}

void loop(){
    //Serial.println("Wheels Forwards");
  //GoForward();
  //delay(2000);
  //Serial.println("Turn Left");
  TLeft();
  Serial.println("ReTurn L");
  delay(5000);
  //Serial.println("Turn Right");
  //TRight();
  delay(5000);
  //Serial.println("Wheels Backwards");
  //Backwards();
  delay(5000);
  //Stop();
  delay(5000);
}

void TRight() {
  Serial.println("LWheel Forwards");
  delay(1000);
  analogWrite(LW_ENABLE, 254); //halfspeed
  digitalWrite(LW_DIRA, HIGH); //one way
  digitalWrite(LW_DIRB, LOW);
  digitalWrite(RW_ENABLE, LOW); //RWheel off

}
void TLeft() {
  Serial.println("RWheel Forward");
  delay(1000);
  analogWrite(RW_ENABLE, 254); //halfspeed
  Serial.println("1");
  delay(1000);
  digitalWrite(RW_DIRA, HIGH); //one way
  Serial.println("2");
  delay(1000);
  Serial.println("3");
  delay(1000);
  digitalWrite(RW_DIRB, LOW);
  Serial.println("4");
  delay(1000);
  digitalWrite(LW_ENABLE, LOW); //RWheel off
  Serial.println("5");
  delay(1000);

}
void Backwards() {
    Serial.println("Both Back");
    analogWrite(LW_ENABLE, 250); //halfspeed
    digitalWrite(LW_DIRA, LOW); //back
    digitalWrite(LW_DIRB, HIGH);
    analogWrite(RW_ENABLE, 250); //halfspeed
    digitalWrite(RW_DIRA, LOW); //back
    digitalWrite(RW_DIRB, HIGH);
  }

void Forwards() {
  Serial.println("Both Forw");
  analogWrite(LW_ENABLE, 250); //halfspeed
  digitalWrite(LW_DIRA, HIGH); //one way
  digitalWrite(LW_DIRB, LOW);
  analogWrite(RW_ENABLE, 250); //halfspeed
  digitalWrite(RW_DIRA, HIGH); //one way
  digitalWrite(RW_DIRB, LOW);
}

void Stop () {
  Serial.println("Stop");
  digitalWrite(LW_ENABLE, LOW); //halfspeed
  digitalWrite(LW_DIRA, HIGH); //one way
  digitalWrite(LW_DIRB, LOW);
  digitalWrite(RW_ENABLE, LOW); //halfspeed
  digitalWrite(RW_DIRA, HIGH); //one way
  digitalWrite(RW_DIRB, LOW);

}

When I uncomment out the call to Backwards as below.....
/************************
  Exercise the motor using
  the L293D chip
************************/

#define RW_ENABLE 11
#define RW_DIRA 28
#define RW_DIRB 30
#define LW_ENABLE 10
#define LW_DIRA 48
#define LW_DIRB 50

int i;

void setup() {
  //---set pin direction
  pinMode(RW_ENABLE, OUTPUT);
  pinMode(RW_DIRA, OUTPUT);
  pinMode(RW_DIRB, OUTPUT);
  pinMode(LW_ENABLE, OUTPUT);
  pinMode(LW_DIRA, OUTPUT);
  pinMode(LW_DIRB, OUTPUT);
  Serial.begin(9600);
  Serial.println("Prog Start");
  delay(1000);
}

void loop(){
    //Serial.println("Wheels Forwards");
  //GoForward();
  //delay(2000);
  //Serial.println("Turn Left");
  TLeft();
  Serial.println("ReTurn L");
  delay(5000);
  //Serial.println("Turn Right");
  //TRight();
  delay(5000);
  //Serial.println("Wheels Backwards");
  Backwards();
  delay(5000);
  //Stop();
  delay(5000);
}

void TRight() {
  Serial.println("LWheel Forwards");
  delay(1000);
  analogWrite(LW_ENABLE, 254); //halfspeed
  digitalWrite(LW_DIRA, HIGH); //one way
  digitalWrite(LW_DIRB, LOW);
  digitalWrite(RW_ENABLE, LOW); //RWheel off

}
void TLeft() {
  Serial.println("RWheel Forward");
  delay(1000);
  analogWrite(RW_ENABLE, 254); //halfspeed
  Serial.println("1");
  delay(1000);
  digitalWrite(RW_DIRA, HIGH); //one way
  Serial.println("2");
  delay(1000);
  Serial.println("3");
  delay(1000);
  digitalWrite(RW_DIRB, LOW);
  Serial.println("4");
  delay(1000);
  digitalWrite(LW_ENABLE, LOW); //RWheel off
  Serial.println("5");
  delay(1000);

}
void Backwards() {
    Serial.println("Both Back");
    analogWrite(LW_ENABLE, 250); //halfspeed
    digitalWrite(LW_DIRA, LOW); //back
    digitalWrite(LW_DIRB, HIGH);
    analogWrite(RW_ENABLE, 250); //halfspeed
    digitalWrite(RW_DIRA, LOW); //back
    digitalWrite(RW_DIRB, HIGH);
  }

void Forwards() {
  Serial.println("Both Forw");
  analogWrite(LW_ENABLE, 250); //halfspeed
  digitalWrite(LW_DIRA, HIGH); //one way
  digitalWrite(LW_DIRB, LOW);
  analogWrite(RW_ENABLE, 250); //halfspeed
  digitalWrite(RW_DIRA, HIGH); //one way
  digitalWrite(RW_DIRB, LOW);
}

void Stop () {
  Serial.println("Stop");
  digitalWrite(LW_ENABLE, LOW); //halfspeed
  digitalWrite(LW_DIRA, HIGH); //one way
  digitalWrite(LW_DIRB, LOW);
  digitalWrite(RW_ENABLE, LOW); //halfspeed
  digitalWrite(RW_DIRA, HIGH); //one way
  digitalWrite(RW_DIRB, LOW);

}

It seems to crash in the TLeft procedure, no motor turns and I get the serial output:
Prog Start
RWheel Forward
Prog Start
RWheel Forward
Prog Start
RWheel Forward
Prog Start
RWheel Forward
Prog Start
I even bought a new Arduino mega thinking it was a hardware fault, downloaded the program to the new mega which has no hardware connections at all just connected to the serial port to download the program and it crashes in exactly the same way.
How can adding another call make it fail in the bit of code that previously ran ok? This is driving me nuts. Can anyone help please?
Also I noticed in the Arduino program installation area there is a program called Arduino_debug.exe, what is this and how does one use it?

which version of Arduino AVR boards you use? I would try the old 1.6.21. The newer versions have have updated compiler and there are problems reported.

Looks so strange that I guess it's a power supply problem when your motor wants to run. Are you sure it happens on a naked Arduino the same way? i.E. you don't see the "1" output after your analogWrite(11,254); ?

Yes it happens on the new naked board. I don't see the "1" output. It just reboots.

did you try to install AVR boards package 1.6.21 in Boards Manager?

Your code (including the Backwards part) runs without issues on my Mega2560 and Arduino 1.8.9.

I had version 1.8.1, I tried downloading 1.6.21 but wouldn't download , so tried 1.8.2, no difference. I then tried 1.6.20 and that made no difference. I then uninstalled arduino and re-installed it, and phew it now works ok.

Thanks for help in assuring me it must have been some environment related issue. I'm thinking it might have been something to do with trying out different learning projects which required installation of different libraries. I installed the pitches library and a remote library. There is plenty of info telling you how to add a new library and sometimes it says one library may interfere with another. But I cannot find any information on how to remove a library to avoid interference. A complete uninstall and re-install is a bit overthe top.


text:
ATmega328P-PU blink example not working
I moved from an Arduino to a bare ATmega328P-PU (to save energy). First I wanted to start a blink-script to verify that it's all working. For this I flashed the bootloader and uploaded the blink-script on the microprocessor. On the arduino the internal pin was successfully blinking. Then I unmounted the ATmega and put it into a breadboard.
I wired everything up. The LED to GND and pin 13, on the other side I put in 5V from a battery, and GND of course. Between the LED and GND I added 220 Ohm and surprisingly if I power it over battery inside the Arduino the internal LED blinks but my own LED (the one with 220 ohms) does not. If I power the arduino over USB both of them blink.
Do you have any ideas on how I can fix this?

Have you attached a 16MHz Crystal with 22 Pico farad capacitors to the Atmega on the breadboard ??? It's essential and you didn't mention this.

Please add your wiring scheme in both of the states when it's blinking succssfully  and when it's not, because it's not very clear what you mean.

I'll do that as soon as I'm at home again. And no I haven't added any of these parts yet. But doesn't the ATmega have an internal 8 MHz clock? How can I use that one?

You will have to "burn the bootloader" to setup the fuses to use the internal 8MHz but if you programed the ATMega328 as an Arduino Uno you will need to attach these components

This might help you alot
The ATMega328 is 8bit AVR microcontroller with a wide variety of things, in order for this IC to work it's essential to have a "Clock Source".as default of Arduino UNO it uses a 16MHz Crystal oscillator with two 22pF capacitors in order to generate the clock signal so, if you took the ATMega328 from the Arduino and put it in a breadboard you should connect these components in order it to work as well as pulling up RESET pin to VCC.
The Atmega328 has a lot of internal calibrated oscillators, from them are 8MHz and 1MHz and alot more, but in order to them to work you need to configure them first by setting up things called "high fuses and low fuses" these control alot of things in the microcontroller from them they determine the clock source.
As how to burn the bootloader to set fuses is not the topic of the question, I won't come to details about it.

Re “a lot of internal calibrated oscillators”: it's actually one oscillator with a programmable prescaler (i.e. frequency divider).

@EdgarBonet Okay maybe I have missed that one ... Thanks for your note. Shall I edit the answer or leave it ?

You may edit if you want. Otherwise do not worry: I am just nitpicking, and yours is a perfectly good answer.


text:
Clock frequency VS cycle time
I am considering switching from Arduino Pro Mini 5V 16MHz to Arduino Pro Mini 3.3V 8Mhz for some project because I would like to run it with a 4.5V input power.
Will the switch from 16 to 8Mhz double the cycle time of my loop() function ?
Edit -- adding precision:
My loop function is simple: it's reading a couple of sensors with analogRead and setting a few pins to HIGH or LOW. It does not use delay().
Thanks.

The execution time of your loop() will be slightly longer when the CPU
runs at 8 MHz v.s. 16 MHz, but I don't expect the difference
to be significant. CPU-bound functions, such as digitalWrite(), will
run at half the speed. These functions, however, are quite fast. In
contrast, analogRead() is slow, as it takes roughly 110 µs to
execute, so this is likely where your loop() spends most of its time.
The execution time of analogRead() does not depend significantly on
the CPU speed. This function spends most of its time waiting from the
analog-to-digital converter to do its conversion. When the CPU is
clocked at either 1, 2, 4, 8 or 16 MHz, the Arduino core sets the
ADC prescaler so that the ADC is clocked at 125 kHz.
This means the conversion time will be the same irrespective of the CPU
frequency.
Note: You may just use your Arduino Pro Mini 5V 16MHz. This board is
based on the ATmega328P microcontroller, which is rated for frequencies
up to 20 MHz when the supply voltage is between 4.5 and 5.5 V.
According to the datasheet (see freq-Vcc graph), it should safely
run at 16 MHz for any supply voltage between 3.78 and 5.5 V.

It depends.
The loop function is handled like a while loop. This means, when the loop function finishes, some framework code  is executed (very small) and the loop function is called again etc.
However, there are some calls that do not depend on the clock speed, the best example is the delay function, but also if you made your own check using e.g. millis this will not depend high likely on the clock speed.
Beyond that, there can be peripheral calls which are not related to the clock speed (although internally in libraries timing functions as above are used to manage this), but you don't see them when used from a library.


text:
How to print stack trace and register dumps on arduino serial monitor?
I want to debug my ESP32 module which is giving an exception using ESP32 exception decoder, but for that, I would need to have access to my stack trace to paste it. But currently, my arduino serial monitor does not print the stack trace. (as shown below)

But I would need stack trace to be printed, like in the below image to debug my exception. How can I print it on the serial monitor?

I think you will need to have access to the processor's debug port such as JTAG.  And likely you will need the particular processor's actual IDE and HW programmer.  The Arduino IDE was supposed to be simple and easy to use for learning.  But I would be interested to know if there are clever ways to get register and call stack information while only using the Arduino IDE.

The second image is on my friend's setup. He is using Arduino IDE too. Also, there are videos on how to use esp exception stack using Arduino, but I'm not sure how they are getting the stack information.

...I have not used an ESP32 yet.  I see what you are talking about.  Guessing, your friend has triggered some built in debugging capabilities of the ESP32's Arduino code on the ESP32.  Further guessing, if you run your friend's code I bet you will get the same debugging output.  Last guess, if this is a SW feature of the ESP32's Arduino code, it may be possible your program breaks in such a way or is running successfully as to not produce the debug information.

Got the required trace logs at the output. All I had to do was enable PSRAM in tools.


text:
Arduino Firebase ESP8266 Connection
I am working on a project that needs data to be stored in cloud db so that I can access the data in a mobile application. For database I have considered Firebase. I am following the following link. But when i try to install the libraries i am getting No such file or directory found errors for memory, queue, Firebase.h, vector, functional, utilities (not all but different packages shows different errors). I tried downloading different packages from github. But still had the errors. Where can I find the correct working program? Thanks in advance.

The sketches in the linked tutorial are missing the includes. The wiring is missing  a wire.

@Juraj Can you please tell me what are the additional wiring that are required?

the tutorial is useless. forget about it. the sketch is for the esp8266, not for Uno so there should be no Uno. the Uno is used for power and the USB chip, but nothing about it is explained. there are no links to resources, nothing about esp8266 arduino core package etc

@Juraj Actually I need an arduino uno because the other part of the project receives data from bluetooth sensor (HC-05), and i need to store the received data in the database. Or is there any way to do this without Arduino Uno. (I am completely new to Arduino Programming. So please dont mind if my questions are silly).

you could not use two serial devices on one Uno..use an esp8266 development board with USB and power regulator. I recommend Wemos D1 Mini. https://docs.wemos.cc/en/latest/d1/d1_mini.html

@Juraj My project is to scan the available Bluetooth signals available and to upload them to the database. For scanning available Bluetooth signals I am using HC-05 AT command (AT+INQ). I have stored the read signals into a string in Arduino Uno. Can you please help me on how to continue further to upload this data to the database?

it is not simple. there is no arduino library for Firebase on Uno. so you must do the communication with Firebase in a sketch on esp8266 and code the data exchange over SoftwareSerial between Uno and esp-01

The usual Firebase library for esp8266 is https://github.com/FirebaseExtended/firebase-arduino.
And there is some new Firebase library in Library Manager in IDE. The "More info" link leads to https://github.com/mobizt/Firebase-ESP8266

I am still getting this error.

 #include <memory>

          ^~~~~~~~

compilation terminated.```

did you install the esp8266 boards package? the library is for esp8266, you can't compile it for Uno


text:
how to get serial data to wait until a certain length is reached
I have a code that loops through 2 different serial inputs on the arduino mega, and sends them to serial constantly:
int RFIDResetPin = 13;

void setup()
{
  Serial.begin(9600);
  Serial1.begin(9600);
  Serial2.begin(9600);
  pinMode(RFIDResetPin, OUTPUT);
  digitalWrite(RFIDResetPin, HIGH);
}

void loop() {

  char tagString1[13];
  int index = 0;
  boolean reading1 = false;
  boolean reading2 = false;
  ///////////////////////////////////////
  //this reads from the reader installed
  //on serial1, which is pin 19
  //////////////////////////////////////
  while (Serial1.available() > 0) {

    int readByte1 = Serial1.read(); //read next available byte

    if (readByte1 == 2) reading1 = true;
    if (readByte1 == 3) reading1 = false;

    if (reading1 && readByte1 != 2 && readByte1 != 10 && readByte1 != 13) {
      tagString1[index] = readByte1;
      index++;
    }
  }
  Serial.println(String("Reader 7: ") + tagString1); //the tag itself

delay(1);
  clearTag(tagString1); //Clear the char of all value
  resetReader(); //reset the RFID reader
  //////////////////////////////////////////////////
  // This bit reads from serial2, located on pin 17
  /////////////////////////////////////////////////
  while (Serial2.available() > 0) {

    int readByte2 = Serial2.read();

    if (readByte2 == 2) reading2 = true;
    if (readByte2 == 3) reading2 = false;

    if (reading2 && readByte2 != 2 && readByte2 != 10 && readByte2 != 13) {
      tagString1[index] = readByte2;
      index++;
    }
  }
  Serial.println(String("Reader 8: ") + tagString1);

  clearTag(tagString1);
  resetReader();
}

void resetReader() {
  ///////////////////////////////////
  //Reset the RFID reader to read again.
  ///////////////////////////////////
  digitalWrite(RFIDResetPin, LOW);
  digitalWrite(RFIDResetPin, HIGH);
  delay(150);
}

void clearTag(char one[]) {
  ///////////////////////////////////
  //clear the char array by filling with null – ASCII 0
  //Will think same tag has been read otherwise
  ///////////////////////////////////
  for (int i = 0; i < strlen(one); i++) {
    one[i] = 0;
  }
}

when not scanning anything, the serial monitor outputs this:
Reader 1:
Reader 2:
Reader 1:
Reader 2:

When I scan a tag, lets say on reader 1, I get this:
Reader 1: 000004f5
Reader 2:
Reader 1: 000004f5
Reader 2:

it is not possible to scan more than a single scanner at a time. Is it possible to get the first line to wait until a certain number of characters have been scanned (indicating a tag has been scanned), and then output to the serial monitor?After that initial run, the code will loop as I showed above. any help is appreciated.

Your dcode doesn't match your output (e.g. "Reader 7: ") At 9600 baud, you could have lots of time between characters and do simultaneous reads. Try reading the bytes from the separate ports into separate buffers bytewise, and then only acting when you fill up a buffer.

I've tried that in the past, the problem is that I don't get any output at all, including the Reader names. I want them to appear at all times, even when there is no tag. I only want the first line to wait until a tag has been scanned

It looks like index is shared between the tags, and you do a 150ms reset cycle and clear each cycle, Per Bra1n's answer, do consider a state machine, and maybe use a index1 and index2 to track the number of bytes you've read on each, and separate the reporting into something conditional on having a "certain number of characters have been scanned"

@jsotola I have no problem receiving from multiple serial ports at once (or functionally at once), as I explained in the question.  I currently have 8 of these system working properly together. I just need this modification on the first one, to initiate certain functions in a different code. I appreciate the thought.

@daveX that definitely seems like something worth investigating, thank you

So it works for 8 readers?  It looks like if you try to read more readers per loop(), index could go well above 13 and do something ugly.  Maybe clear index before the while loops?

sorry for the late reply! It's not that it works for 8 readers, on the arduino mega there is a max of 4 com ports (not including software enabled ports). on each arduino, I am running the code above, with different reader numbers. eg arduino 1 has readers 1 and 2, arduino 2 has readers 3 and 4. thankfully, I was able to solve my problem using a more downstream method. this prints to a MATLAB code, and I worked it out over there

I would use a programming concept called a state machine. For example an integer variable called State could be used to track the current status which could for example be WAITING_FOR_DATA or RECEIVING_DATA or DATA_COMPLETE and only print when DATA_COMPLETE. I'm sure there are plenty of examples you could find with an appropriate search.

this sounds like a good idea, I'll do some research. Thanks very much

Better use an enum type for State instead of an int (and using a better name, like UartState, or UartState1, UartState2 if you need)

1.prefer using Serial.readStringUntil(); OR Serial.readString() that way its much easy to manipulate.
2.use a static variable in loop function which stores the string or use a global variable to save char array tagString1 before going in println function same goes with the second reader that way the println will show the previous scan until a new scan is not done.
3.print both the tagstrings in the end of the code one after another


text:
Save joystick movement and run a servo motor
I am planning to use a joystick to input joystick stroke directions, save the directions as number in a variable. The idea is to start a servo motor if the directions match the directions in the sketch.
for example, let us say, I perform the following movement on the joystick:
1. two left movement along x axis ( <-, <-)
2. two right movement along x axis ( ->, ->)
3. One Up movement along y axis
and 4. one down movement along y axis.
These movements are as a result of a user solving a clue. (two left strokes could mean an alphabet 'A' or a number 1, not decided yet, and so on..)
I would like to save the 4 or 5 joystick directions in a variable and if it matches the directions declared in the sketch (True condition), then DC servo motor would start and pull a screen up, which will expose 'SOLVED' written behind the screen.
Hope the scenario is clear. Since, I am new to this, I would like to get some help with the sketch and the connections (Arduino Joystick inputs and DC server output are available on web, it will be helpful if someone can give an overall guidance as well.

how do you do two left movements?

Start simple, and try to detect a single joystick movement first. Print this to the serial port and watch the output on the Serial Monitor. Only if this works, think about the next steps.

The format of this site is not good for project guidance. It's a simple Q&A site, so you need to ask a specific question, that can be asked specifically, without  a contineous back and forth between you and the one, that might answer your question. With which part do you have problems and what are these problems specifically? You might want to try and post at the Project guidance section of the Arduino Forum (you can google it). It is meant for such guidance

Consider using (explicitly asking for help with) a simpler / older joystick with only off / on switches. Such as old computer games might use. Using a joystick made from two potentiometers (like when controlling an RC airplane) would be more difficult. Also, using a 4 way joy stick and leaving out diagonal directions would make the code simpler.  Finally, do you really need to servo motor?  Know the position of the motor at all times? Turning an ordinary motor on and off would be much simpler.  Let me know if you want me to edit your question.


text:
Grbl on Arduino Uno (Elegoo) with DM542 + nema24 stepper motor not working
i've already searched and tried for a quite depressing amount of hours, but am not able to solve this problem:
The parts are the following:
 - Elegoo Arduino Uno, on wich i flashed GRBL
 - 24v Power Supply (wich powers the stepper motor(s)
 - Nema24 3nm stepper motor
 - A DM542 Driver
 - bCNC (exe-build on win7 and win10)
Now, i connected one stepper-driver and stepper-motor as x-axis to the arduino.
The wiring is as following:
 - 5v from arduino to the three + Pins (ENA, DIR and PUL)
 - Pin 2 to PUL, Pin 5 to DIR, Pin 8 to ENA
 - 24V go to + and ground port of the driver, the 4 motor-wires are wired accordingly to the driver
I downloaded GRBL from Github and flashed it to the Arduino (i can run grbl-commands from the serial monitor inside the arduino ide, grbl is unlocked), connected everything and opened up bCNC, searched for the arduino on com-port, wich is shown correctly, and connected wich works fine (in the main screen "connected" shows up).
However when i try to move the x-axis under the control-panel in bcnc, nothing moves, on the screen the numbers change correctly and i get an ok in the logs, but the motor does not move a bit.
I double checked the wiring and tried to write a little program in arduino ide to move the stepper motor without grbl (deleted grbl, wrote a little program wich manually set the intervals ecc), without changing the wiring, that worked...
How can i debug this? Any suggestions?
Thanks in advance!

As you wrote, that you connected the positive pins of ENA, DIR and PUL to 5V, I guess you use the common anode connection scheme from the DM542's datasheet (the driver seems to have optocouplers for the inputs). That would mean the inputs are active low (a Pulse would be a transition from HIGH to LOW and then back to HIGH).
GRBL v1.1 has by default an active high pulse signal:

By default, a step signal starts at normal-low and goes high upon a step pulse event. After a step pulse time set by $0, the pin resets to low, until the next step pulse event.

(from the GRBL github wiki). I guess, this is the problem. Please try to set GRBL for inverting the pulse signal with $2 (you may well find a corresponding setting inside bCNC.
Be sure, that GRBL is outputting the signals, that your driver is expecting in your connection scheme.

Hi, chrisl,
thanks for your response!
I'll try it and let you know if it worked ;-) And yes, i use a similar datasheet with the same wiring wich was delivered with the stepper motors =)

Hey chrisl, it worked!!! Thanks man!
I had to invert the ENA-Pin too, but now it works like a charm!
Now i need to figure out how to set the options when the arduino is connected to bcnc, but that's another story.
Thanks again!!


text:
Arduino Uno lag in simple loop
I have a simple Arduino sketch which I have been playing with on my Uno.
The idea is simple, the user turns a potentiate (pin A2), when they pass a certain threshold a LED is turned on (pin 7).
Here is the code:
// Digital pins
const byte ledPin = 7;

// Analog pins
const byte userInputPotPin = A2;

// Potentiometer constants
const int userInputPotMinimumValue = 0;
const int userInputPotMaximumValue = 1023;
const int userInputMinimumValue = 1;
const int userInputMaximumValue = 100;

// Variables
const int threshold = 90;

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

    // Digital pins
    pinMode(ledPin, OUTPUT);

    // Analog pins
    pinMode(userInputPotPin, INPUT);
}

void loop()
{
    int rawValue = analogRead(userInputPotPin);
    int mappedValue = map(rawValue, userInputPotMinimumValue, userInputPotMaximumValue, userInputMinimumValue, userInputMaximumValue);

    String messageText;
    messageText += "Raw:   " + String(rawValue) + "\t";
    messageText += "Mapped:" + String(mappedValue);

    if(mappedValue > threshold)
    {
        messageText += "\tThreshold exceeded!";
        digitalWrite(ledPin, HIGH);
    }
    else
    {
        digitalWrite(ledPin, LOW);
    }

    Serial.println(messageText);

    delay(100);
}

The problem is that when it is run the hardware is very unresponsive - I can turn the pot, but I don't see the light change for several minutes. The log messages in the serial monitor also seem to be lagging behind.
I have tried:
* Removing the Serial statements (so there is no serial communication when the sketch is running), and just observing the LED. This makes no difference.
* Increasing the value in the delay up to 1000. This makes no difference in the responsiveness.
However, when I run the sketch on my Mega2560 the problem goes away and the circuit is as responsive as I expect.
Is there something wrong with my Uno board?

What happens when you also comment out all the code that uses and contructs the String messageText?

Your MCU is busy printing text and waiting.

I can't see anything in your code that could make it so slow. Could you try with just void loop(){Serial.println(analogRead(A2));delay(100);}?

It turns out the problem was the A2 pin on the board.
When I used the A0 pin (or a different board) the problem goes away.
I realised something was wrong when I noticed the values from the pot were strange (I expected values in the range 0 - 1023, but was receiving values from 170-250 ish).

Btw, you can use the Arduino 'map'  command to map a range to another range.

The String+ operator is very expensive. High likely what it does is:

Create a new block of memory to accommodate the old string content and the to-be-concatenated text.
Copy the current String to a new string location
Concatenate the string
Free the old memory

Besides creating memory gaps which can be disastrous for the just 2 KB SRAM of the Arduino Uno, it takes a lot of time.
Some tips:

Do not use Strings
Do not concatenate strings if not needed
To save more time, use short strings instead

If you really need to debug a time critical part, copy numbers you want to print to an array, and AFTER you do all 'real' code, start printing the numbers.

Also there is no reason to concat strings for serial output. Just print the parts one after another. To get "Number: 5 bananas" you could use Serial.print("Number: "); Serial.print(number_variable); Serial.println(" bananas")

@chrisl that's indeed my second tip.

Thanks for the excellent advice.
Unfortunately I can't mark it as the answer to the question as my issue was caused by something else (see my answer).

No problem, btw, you can accept your own answer too.


text:
i need to connect ultrasonic gas MQ2 and IR sensor(as blink counter) to count the number of blinks
im making a drowsiness detection using IR sensor as blink counter less than 30 and ultrasonic sensor distance should be less than 50cm and gas sensor MQ2 if the driver has consumed alcohol the gas will be detected and buzzer will be turned on and if the driver is drowsy the arduino will count the blinks if less than 30 it will turn on the buzzer and display on LCD as drowsy driver and led will blink.
can anyone pls help me with the codes?
i have managed the code
int trigPin = 6;
int echoPin = 7;
int IRSensor = 2; //connect ir sensor to arduino pin 2
int LED = 13;
int LED1 = 12;
int buzzer = 10;
int smokeA0 = A5;
int sensorThreshold = 50;
int sound=250;

void setup() {
  pinMode(trigPin,OUTPUT);
  pinMode(echoPin,INPUT);
  pinMode( IRSensor,INPUT);//sensor pin INPUT
  pinMode(LED1,OUTPUT);
  pinMode(LED, OUTPUT);//LED pin OUTPUT
  pinMode(buzzer, OUTPUT);//Buzzer Pin OUTPUT
  pinMode(smokeA0, INPUT);
  Serial.begin(9600);
}

void loop()
{
  long duration,distance,statusSensor;

  int IRSensor = digitalRead(IRSensor);
  int analogSensor = analogRead(smokeA0);
  Serial.print("Pin 2");
  Serial.println(statusSensor);
  Serial.print("Pin A0: ");
  Serial.println(analogSensor);
  // Checks if it has reached the threshold value
  if (distance<=30)
  if (statusSensor == 10)
  if (analogSensor > sensorThreshold)
  {
    digitalWrite(LED, HIGH);
    digitalWrite(LED1, LOW);
    tone(buzzer, 1000, 200);
  }

  else
  {
    digitalWrite(LED1, LOW);
    digitalWrite(LED1, HIGH);
    noTone(buzzer);
  }
  digitalWrite(LED, HIGH);
    digitalWrite(LED1, LOW);
    tone(buzzer, 1000, 200);
  }

  else
  {
    digitalWrite(LED1, LOW);
    digitalWrite(LED1, HIGH);
    noTone(buzzer);
  }
  else
  {
    digitalWrite(LED, HIGH);
    digitalWrite(LED1, LOW);
    tone(buzzer, 1000, 200);
  }

 else
  {
    digitalWrite(LED1, LOW);
    digitalWrite(LED1, HIGH);
    noTone(buzzer);
  }
  delay(100);
}

And what exactly is your problem?

You cannot use multiple else statements, but probably you want to have conditions there 'else if (condition)', except for the last else maybe.

what does less than 30 mean?


text:
Reduce Sketch Size Help!
I dont know what to do?
Sketch uses 3712 bytes (12%) of program storage space. Maximum is 30720 bytes.
Global variables use 210 bytes (10%) of dynamic memory, leaving 1838 bytes for local variables. Maximum is 2048 bytes.
Program:
String texto;
int flag;
void setup() {
Serial.begin(9600);
pinMode(9, OUTPUT);
pinMode(10, OUTPUT);
pinMode(11, OUTPUT);
pinMode(12, OUTPUT);
pinMode(7, OUTPUT);//luz stop
pinMode(8, OUTPUT);//faros
}
void loop() {
while (Serial.available())//
{
delay (10);
if (Serial.available() > 0) //verifica que este disponible el puerto serie y verifica que haya algun
caracter
{
char c = Serial.read(); //guara cualquier caracter que haya llegado por el puerto serie
texto += c; //concatenamos
}
} ///Sentencias de control///
if (texto == "1") //compara el contenido de la avariable "texto" con el numero 1
{
digitalWrite(7,LOW); //Apaga la luz stop
digitalWrite(11, LOW);
digitalWrite(12, HIGH);
digitalWrite(10, HIGH);
digitalWrite(9, LOW);
}
if (texto == "3") //compara el contenido de la avariable "texto" con el numero 3
{
digitalWrite(7,LOW); //Apaga la luz stop
digitalWrite(11, HIGH);
digitalWrite(12, LOW);
digitalWrite(10, LOW);
digitalWrite(9, HIGH);
}
if (texto == "2") //compara el contenido de la avariable "texto" con el numero 2
{
digitalWrite(7,LOW); //Apaga la luz stop
digitalWrite(11, LOW);
digitalWrite(12, HIGH);
digitalWrite(10, LOW);
digitalWrite(9, HIGH);
}
if (texto == "4") //compara el contenido de la avariable "texto" con el numero 4
{
digitalWrite(7,LOW); //Apaga la luz stop
digitalWrite(11, HIGH);
digitalWrite(12, LOW);
digitalWrite(10, HIGH);
digitalWrite(9, LOW);
}
if (texto == "5") //Compara el contenido de la avariable "texto" con el numero 5
{
digitalWrite(7,HIGH); //Enciende la luz stop
digitalWrite(11, LOW);
digitalWrite(12, LOW);
digitalWrite(10, LOW);
digitalWrite(9, LOW);
}
if (texto == "6") //Compara el contenido de la avariable "texto" con el numero 6
{
if (flag==1)
{digitalWrite(8, LOW);
flag=0;
}
else if (flag==0)
{digitalWrite(8, HIGH);
flag=1;
}
}
texto = "";
}

What‘s the problem, you have lots of space left?

I dont know what to do? ... i think that you are the only one who knows the answer to that question

Next time, select your code and press ctrl-K... Also align your code (indent it well).
However, you don't need help actually as you have plenty of memory left. As as written:

You only use 12% of program storage space. This might seem a lot having such a small sketch, but most of it is because of library usage/framework (such as the digitalWrite call(s).
210 bytes of dynamic memory is also not something to worry. Btw, this is unrelated to the sketch size, but to your use of (global and other) variables.

So unless you know beforehand your sketch will be much bigger, don't change it because of that reason (too less space).
However, there is another reason, to shorten the sketch, and that is because of duplicated code. As you can see, there is in the entire sketch a lot of repetition (or almost repetition), as in:
if (texto == "5") //Compara el contenido de la avariable "texto" con el numero 5
{
  digitalWrite(7,HIGH); //Enciende la luz stop
  digitalWrite(11, LOW);
  digitalWrite(12, LOW);
  digitalWrite(10, LOW);
  digitalWrite(9, LOW);
}

What you can do to improve it is:

Either use a switch statement instead of the if/else statements
Or create a function that incorporates this condition, together with the following item. This solution is in your case the most clear.

What you do is creating a new function:
void setPins(bool condition, int pin7, int pin11, int pin12, int pin10, int pin9)
{
  if (condition)
  {
    digitalWrite(7, pin7);
    digitalWrite(11, pin11);
    digitalWrite(12, pin12);
    digitalWrite(10, pin10);
    digitalWrite(9, pin9);
  }
}

And you call your function with:
setPins(texto == "5", HIGH, LOW, LOW, LOW, LOW);

And the same for all other conditions. I only used 5 as example.


text:
Simultaneous Serial reading and writing
I am trying to read long strings from the Serial, using arduino.
In order to spare some RAM I don’t use Serial.readString().
I use Serial.read() instead.
During the reading, I also print some debug info to the same Serial port.
Let's say I send 90 characters to the Serial from the PC. I read them with Serial.read(). If I call a few times Serial.println() between two calls of Serial.read(), I get only 67 character of 90 (Serial.available()>0 is false).
I read all the 90 character when I don’t call Serial.println() at all.
Why? I was sure that it is possible to write to the serial and read from it simultaneously, that these are independent processes.
Am I wrong?

I don't understand, what you mean by "as much I print ... as shorter read string is". Please explain more and more clear

Please show us the sketch you're using.

I send 90 characters to the serial. I read them with Serial.read(). If between to calls of Serial.read() I call Serial.println() a few times, I read only 67 character of 90. I read all the 90 character when I don’t call Serial.println at all.

@VE7JRO ,I believe I described my issue well enough. The sketch is quite long and it will take some time to cut it out.

what command uses this comparison? ... Serial.available()>0

@jsotola you can read about this on arduino.cc

The Serial buffer size is only 64 bytes. If you take too long for printing and your PC sends the data too fast, you will loose data. But that depends on your sketch, how much data you are printing and what baudrate you use

You can indeed simultaneously read and write through the serial port. At
the hardware level, the serial port (the UART) is a transmitter and a
receiver, which are almost independent. At the software level, they are
both handled through interrupts that read from / write to a software
buffer.
There is, however, a limitation you should be aware of: the software
buffers are not large, typically 64 bytes on AVR-based boards. If
you try to write too much too often, the output buffer will fill out,
and then all subsequent writes become blocking, and run as slow as the
serial port itself. If you receive lots of data and do not read it soon
enough, the input buffer will overflow, and you loose some data.
From your description of your issue, it would seem you are hitting the
limits of both buffers. You Serial.println() too much, too often. Then
these write operations take too long and, in the meanwhile, you do not
Serial.read(). Since your PC is not waiting for you to
Serial.read(), your input buffer eventually overflows, and you only
get slightly more than a buffer worth of characters.

I'm completely satisfied with your answer. Thank you so much indeed!