text:
Pressure Gauge analog reading via RS232
I am trying to read the analog signal from a Pfeiffer TPG 261 Single Gauge (https://www.idealvac.com/files/brochures/Pfeiffer_Single_Gauge_TPG261.pdf)
The pin assignment of the connector I am using is the following:

Here is the circuit I have built:

And here is the code used:
int pressureSensorPin = A0;

int analogValueP = 0;

void setup(void)
{
  Serial.begin(9600);
}
void loop()
{
  analogValueP = analogRead(pressureSensorPin);
  Serial.println(analogValueP);
  delay(1000);
}

Unfortunately the ouput I get with such a build is only 0 with now and then a 1023.
Any idea of what I am doing wrong ?

The Arduino has 5 V TTL Serial. the connector is RS232, possibly +/-12 V. You need a converter. The value read on RS232 would be data to read with Serial.read(), not an analog signal

You have a misconception, which signals get's outputted where. If you want to simply read the analog signal of the sensor, you need to use the "control" connector. There you can find the analog signal on pin 2. But this analog signal goes up to 10V, so you need a voltage divider between the sensor and the Arduino, to divide the voltage down to 5V max.
Currently you are using the RS232 connector. RS232 is a communication standard, which transmits digital data, not analog data. Thus you read only digital values (min voltage and max voltage, nothing inbetween). You can use it do talk with the sensor, change configuration settings and reading data digitally. But to actually do this, you need to consider 2 important things:

RS232 is an interface, which involves it's own voltage levels (namely +-12V), which do not fit the TTL level (0 - 5V) that the Arduino Uno uses. You can very well destroy your Arduino by connecting it directly to RS232. For making this work, you need a level converter chip (I think the MAX232 is commonly used for this), to convert the voltage levels to TTL logic. From there on this communication is normally called UART.
You need to understand and then implement the sensors communication protocol (when to send what data), so that the sensor and Arduino are understanding each other

For me it seems, that the analog signal from the "control" connector is all, that you currently need, so for simplicity you can use this. RS232 is used for more control over the functionality of the sensor.

Even the analog signal from the control connector supplies a voltage range of 0 .. 10V, which requires some treatment (voltage divider) and is not directly applicable to an Arduino.

You are correct, I will add this to the answer

Thanks for all the information, yes I did have a major misconception, I understand better now. So if I wanted to access the digital output something like this could work : https://www.conrad.de/de/p/entwicklungsboard-mikroelektronika-mikroe-222-1221401.html ?

Yes, that would work


text:
Code conversion
Following is the zabbix documentation with the query header format.
Document Zabbix
I have difficulty implementing this header in C ++ (Arduino),
I saw an implementation of what I need in this forum here , however it is in Russian and is implemented in C #, I tried to translate it but to no avail.
So I need someone to help me write the function of the header examples in C ++ (Arduino).
Follows full Arduino code after @EdgarBonet change suggestion
#include <ArduinoJson.h>
#include <SPI.h>
#include <Ethernet.h>

// Config IP
IPAddress ip(192, 168, 0, 130);
IPAddress gw(192, 168, 0, 1);
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
float contador = 0;

EthernetClient client;

//Config Server address
const char* server = "192.168.0.135";
int porta = 10051;

void setup() {
    Serial.begin(9600);
    Ethernet.begin(mac, ip);
}

void loop() {
    // Begin Json
    const size_t capacity = JSON_ARRAY_SIZE(1)
                          + JSON_OBJECT_SIZE(2)
                          + JSON_OBJECT_SIZE(3);
    DynamicJsonBuffer jsonBuffer(capacity);

    JsonObject& root = jsonBuffer.createObject();
    root["request"] = "sender data";

    JsonArray& data = root.createNestedArray("data");

    JsonObject& data_0 = data.createNestedObject();
    data_0["host"] = "ethernet";
    data_0["key"] = "variavel1";
    data_0["value"] = contador;

    String json = "";
    root.printTo(json);

    const uint8_t *dataSend = (const uint8_t *) json.c_str();
    uint64_t data_length = json.length();
    uint8_t packet[13 + data_length];  // 13-byte header + payload

    // Write the 5-byte signature.
    memcpy(packet, "ZBXD\1", 5);

    // Add the 8-byte packet length, LSB first.
    for (int i = 0; i < 8; i++) {
        packet[5+i] = data_length >> 8*i;
    }

    // Add the payload.
    memcpy(packet + 13, dataSend, data_length);
    if (client.connect(server, porta)) {
        Serial.println("Enviando ao servidor");
        delay(1000);
        // Send the packet.
        client.write(packet, sizeof packet);
        delay(1000);
        contador ++;
    }
}

Following server response:
2034:20191003:101411.196 Message size 2066888786 from 192.168.0.130 exceeds the maximum size 1073741824 bytes. Message ignored.

The problem is quite explicit in the error message:

expected 808529969 bytes

You told the server that you were going to give it 808529969 bytes, yet
you provided much less. Why did you tell it you were going to send so
much data? Maybe we can get a clue by rewriting this number in
hexadecimal:
808529969 = 0x30313031
Breaking this into individual bytes, LSB first (as this is how the
server expects it), you have
0x31 0x30 0x31 0x30
These are the bytes you sent to the server, and they all happen to be
ASCII codes for digits, which make up the string "1010". I don't know
how you came up with this, as the code you posted is not the one you
tested (the posted code does not even compile!). But it seems at one
point you tried to convert something to ASCII binary, and indeed
String(10, BIN) produces exactly the string above.
The server expects the data length to be provided as binary bytes,
not as an ASCII string. I personally try to avoid the String
class, which can create memory issues. In this situation I would just
work with an array of bytes, typed as uint8_t (the same as the Arduino
byte type, only more standard). In the code below, I assume for
simplicity that you keep a String for building the payload, but then I
switch to a raw byte array:
const uint8_t *data = (const uint8_t *) json.c_str();
uint64_t data_length = json.length();
uint8_t packet[13 + data_length];  // 13-byte header + payload

// Write the 5-byte signature.
memcpy(packet, "ZBXD\1", 5);

// Add the 8-byte packet length, LSB first.
for (int i = 0; i < 8; i++) {
    packet[5+i] = data_length >> 8*i;
}

// Add the payload.
memcpy(packet + 13, data, data_length);

// Send the packet.
client.write(packet, sizeof packet);

Note that when working with binary, rather than text data, you have to
use memcpy() instead of strcpy(), and client.write() instead of
client.print().

Hello Mr @EdgarBonet, first I want to thank you for the help, finally I put your code inside my project, but the server is reporting another error, now says that the message is still too big, according to the documentation, this message may have in 128MB maximum, and according to the error code code Message size 2066888786 from 192.168.0.130 exceeds the maximum size 1073741824 bytes. Message ignored. is exceeding this limit, as I don`t have enough reputation to answer here in the forum I forwarded my entire code to link[/link]. Thank

@VeniciusBack: You probably have enough reputation to edit your question. And you wouldn't want to answer anyway... unless you do have an answer!

@VeniciusBack: Also, when you provide your code and report an error message, make double sure that the error message your report is generated by the exact same version of the code you are showing. Otherwise you are wasting everyone's time. I am pretty sure the error message and the code your are showing do not match.

I edited the post, with the full code of the arduino I am sending and the response of that code provided by the zabbix server.
Thanks!

@VeniciusBack: Do not edit your answer, which was deleted by VE7JRO for a very good reason (it's not really an answer). Edit your question.

Mr @EdgarBonet, I want to thank you for all the help, finally the code worked correctly, I made the change to ArduinoJson 6, thank you for all the patience you had with me, you did a great job, thank you very much! How do I credit you or close this topic? Thank you one more time! Strong hug!

@VeniciusBack: The way to credit is to “accept” an answer.

source: Stack Exchange

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

sort: votes


text:
Esp8266 esp01 kicks other devices off tplink router
I had an Esp8266 esp01 module programmed to log onto the router and post data.  It worked fine for a few months but all of a sudden it kicks everyone else off the router.
Actually as soon as I connect the Esp and it connects to the ssid, it kicks off my laptop (laptop can no longer even see the ssid) and I see my Google home drop it's connection as well.  It's almost immediate, about 20 seconds after powering up my esp.  Seconds after I unplug the Esp google home comes back on and my laptop sees the ssid again.
What should I check for in my router?  It's a tplink tr-wl945N.

try to set RF TX power of the esp8266,

@Juraj what does that mean?  The Esp now has a dedicated power source.

in esp8266 sketch WiFi.setOutputPower(15.0);

I hope you didn't set the same IP address to the esp8266 as the computer has

I didn't set the ip, the router uses dhcp

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


text:
Sending multi-byte data over I2C between different processors
I have been attempting to read data from an ATTINY84 via an ESP8266. Both are programmed via the Arduino IDE, though as PlatformIO is a proxy for that, I'm not certain what version of the ATTINY core is in use.
I have both devices connected to the I2C bus, with the Arduino as a slave.
The ESP sends a code requesting a particular type of data, then calls Wire.requestFrom() to get 8 bytes of data. I am concerned over both my implementation and about potential endian-ness issues (even if it should turn out not to be an issue on these two particular devices, I'd like to know my future options).
The ATTINY code is a complex function that is called when there is a request (and the right option code, but that's probably not very relevant). It writes eight bytes using Wire.write after uncompressing them from the relevant arrays. (I have a lot of ADC data that technically should not fit in RAM.)
Since this is is a callback function or possibly an interrupt, do I need to be concerned about data corruption if the code is too slow to write the values onto the bus? I have to imagine it's trying to read them even as it writes. I can also provide code snippets if it would help.

I am also unsure if I am running into Endian-ness issues by using bitshift to grab the 2 and 8 bits from the ADC return value. Would this always give me the correct values, or does the C++ compiler (as I assume it does not) simply refuse to handle differences between the data order?
Specifically, if I shift a uint16_t (or any non-trivial datatype) right by 8 bits, and mask out the bottom 8 with &0xFF, do I always get the second-least-significant (in this particular case, high) byte, or can the compiler produce alternate outputs based on byte order?
Does Arduino have an equivalent of network byte order (or does Wire automatically do so for its overrides of the functions) that I can get around this potential issue with?

There seems to be multiple questions in what you are asking. Here I try
to answer specifically this one:

if I shift a uint16_t (or any non-trivial datatype) right by 8 bits,
  and mask out the bottom 8 with &0xFF, do I always get the
  second-least-significant (in this particular case, high) byte, or can
  the compiler produce alternate outputs based on byte order?

Short answer: yes, you get the second-least-significant byte,
irrespective of the platform's native endianness.
Now, I'll expand on this answer by showing the different ways you
can convert an uint16_t to a sequence of bytes, and the implications
on the byte order.
If you want to control the endianness, and you want your code to work
independently of the native endianness of the platform, then bit
shifting is the way to go. Let's assume you want to convert this:
uint16_t data;

into this:
uint8_t bytes[2];

You can do it this way in order to get the least significant byte first:
bytes[0] = data >> 0;  // least significant byte
bytes[1] = data >> 8;  // most significant byte

Or you can instead do the assignments the other way around
(data >> 8 goes to bytes[0]...) if you want MSB first. Note that
there is no point in masking, as the assignment does it implicitly.
In contrast, if you wanted to put the bytes in native endianness (the
endianness of the platform), the traditional way to do it is to cast the
address of the number to a pointer to bytes, then read from this
pointer:
bytes[0] = ((uint8_t *) &data)[0];  // first byte
bytes[1] = ((uint8_t *) &data)[1];  // last byte

You can swap the indices on one side of the assignments if you want to
instead reverse the byte order. But note that this kind of casting is
now frowned upon, as it violates aliasing rules. A common alternative is
to have the number and the byte array share the memory within an
union:
union {
    uint16_t data;
    uint8_t bytes[2];
} x = { .data = some_16_bit_value };
do_something_with(x.bytes[0]);  // use first byte
do_something_with(x.bytes[1]);  // use second byte

These are the main byte-splitting idioms you may come across. If your
purpose is to have an endianness that you control and is independent of
the platform, then stick with the first option: the old good bit
shifting.

That answers most of what I wanted, although the part about pointer-casting doesn't have the results I was hoping to hear. What happens if I send a uint32_t, for example, through Wire.write() (or an equivalent function) directly, though? Does that send in native byte order, or does Wire handle that automatically? I'd like to avoid bit-shifting for some of my more complex messages if possible.

I kinda had three sub-questions, which I'll admit kinda doesn't help matters, but they are also somewhat related. One was what the bit-shifting actually does, the second is if the Wire library handles endian-ness discrepancies on its own, and the third (which is a bit less related) is exactly how/when data is written or requested when the master requests data -- is there a chance of the slave not having it ready in time or writing too slowly (that would cause some later section of the message to be wrong while the first was correct).

@RDragonrydr: Wire.write() doesn't handle endianness. It sends either a single byte (Wire.write(value) sends only the LSB of value) or a byte array when called as Wire.write(const uint8_t *buffer, size_t length).


text:
Arduino Nano burns with ESP-01 in parallel
So I have an Arduino Nano powered in parallel with an ESP-01 (for the ESP there is an extra LM1117-5.0 voltage regulator in series).
+12V ---------+---------+
              |         |
             Reg        |
              |        NANO
             ESP        |
              |         |
 GND ---------+---------+

My problem is that after a while, the Nano burns (my guess is the difference in current that both devices draw).
In any case, what could be the reason and what could I do to fix it?
Thanks!

how are you connecting the 12 V supply to the nano?

I´m using the Vin pin.

"for the ESP there is an extra LM1117-5.0 voltage regulator in series" ... shouldn't an ESP-01 get 3.3V?

please do not crosspost ... https://electronics.stackexchange.com/questions/461286/arduino-nano-burns-with-esp-01-in-parallel

Didn't know, deleted the duplicate one. Thanks.

Use the 5v regulator to power both the ESP and the Nano. Those onboard regulators have minimal heat dissipation and if they burn out you lose the whole Nano. Check how hot your external regulator gets and mount it on a heat sink if it gets too hot to touch.
NB Connect the regulator output to the Nano 5v pin directly

12V is the upper limit for input voltage on an Arduino. With a 12V input the regulator has to convert 12-5, or 7 volts, to heat. (That's how linear voltage regulators work.) As the other poster said, Arduinos don't have much heat dissipation on their voltage regulators.
Like jksemple, I would suggest powering both the ESP and the Nano from the external regulator (You might want to cut a USB cable and wire it to your external voltage regulator, then plug it into your Nano. That way you're not bypassing the power control circuits on the Nano.
By the way, did you build a full voltage regulator with the LM1117 chip? You need some extra components like capacitors and resistors to complete the voltage regulator.
Finally, you might think about using a DC-DC buck converter rather than a linear regulator. That will run a lot cooler and waste a lot less power.


text:
ESP8266 ESP-07 does not respond to commands
I just bought an ESP8266 ESP-07 V1.0 Serial Wifi Transceiver. Similiar to this: https://www.ebay.com/itm/ESP8266-Serial-Wifi-Transceiver-Module-for-Arduino-ESP-07-V1-0-New-/331868488091
I have connect the RX and TX pins to the RX and TX pin of the Arduino (RX to TX and TX to RX), VCC is connected to 3.3V and GND is connected to Arduino ground.
I have used the following code and writing commands to the module using the serial monitor:
#include <SoftwareSerial.h>

int RX_PIN = 3;
int TX_PIN = 4;

SoftwareSerial mySerial(RX_PIN, TX_PIN); // RX, TX

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

    while (!Serial){
    ;
  }

    while (!mySerial){
    ;
  }
  Serial.println("Ready");
}
void loop()
{
    // listen for communication from the ESP8266 and then write it to the serial monitor
    if ( mySerial.available() )   {  Serial.write( mySerial.read() );  }

    // listen for user input and send it to the ESP8266
    if ( Serial.available() )       {  mySerial.write( Serial.read() );  }
}

Whatever I type (for example AT+GMR) in the serial monitor at 9600 baud I don't get any response. What could be the reason? Both NL and CR is added to the command.
When pressing reset on the ESP-module I get this in the Serial monitoring:

Thanks for any help!

pin 1 is TX of hardware Serial. and the esp8266 should be on SoftwareSerial RX/TX pins, not on RX/TX labeled pins

@Juraj Thanks for your reply. I have now updated the code. But still no luck :-/

and the wiring?

@Juraj  Arduino RX (pin 3) => ESP TX, Arduino TX (pin 4) => ESP RX, Arduino 3.3V => ESP VCC, Arduino GND => ESP GND

you changed the baud rate. the AT firmware's default is 115200 baud, but SoftwareSerial can't receive reliably at 115200

@Juraj Is there anyway to fix that then?

the output after reset is bootlog at different baud rate. did you try to send AT after "Ready"?

@Juraj Yes, if I do that I don't get any response. But reading around I see I might need to put a resistor between the TX from Arduino (pin 4) to ESP8266 RX pin since it operates at 3V not 5V? Which means the ESP8266 RX pin might be broken? 100 ohm resistor should be enough if I have calculated correctly.

the esp8266 has no pronlem with  5 V Serial

set the baud rates to 74800 to see the boot log

@Juraj Sweet, that gave me "ets Jan  8 2013,rst cause:2, boot mode:(3,6)". Is it only boot log that works at 74880?

yes only boot log. is it possible that the esp8266 is without AT firmware? even with SoftwareSerial at 115200 you should see "ready" from AT firmware and get some response to AT commands

@Juraj I have asked the seller about the firmware since the information does not say anything about it. As far as I can see there is no way for me to install/update the firmware using the Arduino Uno.

why not? it is simple. https://forum.arduino.cc/index.php?topic=634684.0

@Juraj This is totally new to me. But I tried it out now. Downloaded NodeMCU and wired it up. But get the following when clicking on "flash"Note:Serial port connected.
Note:Begin find ESP8266.
Note:ESP8266 ACK success.
Error:Read ESP8266 register timeout.

NodeMcu? there is nothing about nodemcu in that link. did you set the switch to flashing mode and reset?

@Juraj Got it working now. But a little bit unsure which files I actually need to upload/update. I have used esp_init_data_default_v05.bin and blank.bin

For anyone still confused (like I was), the code should still say Serial.begin(115200) but the Arduino log monitor should be set to 74880 baud.

@Juraj Got it working now thanks to the forum link. So I will accept it as answer if you make one :)

with AT firmware 1.7 you can use my WiFiEspAT library in UNO. the library is in library manager

The esp8266 is without AT firmware. Even with SoftwareSerial at 115200 baud you should see "ready" from AT firmware and get some response to AT commands.
This esp8266 module adapter is simple to flash. It makes the 5 V to 3.3 V conversion for power and RX pin and has a program switch (io 0) and a reset button to put the esp8266 into flashing mode.
Use an USB-to-TTL-Serial adapter or an Arduino with USB chip to connect the adapter to PC. Then switch to "program" and reset it and it will be in flashing mode.
You can download the AT firmware here. I recommend ESP8266 NonOS AT Bin V1.7.1. Don't try 2.0, it is very different (ESP32 AT firmware build for esp8266).
To flash it, use esptool
The command to flash the AT firmware binaries to any module with at least 1 MB flash memory is:
esptool.py write_flash --flash_size 2MB-c1 0x0 boot_v1.7.bin 0x01000 at/1024+1024/user1.2048.new.5.bin 0x1fb000 blank.bin 0x1fc000 esp_init_data_default_v08.bin 0xfe000 blank.bin 0x1fe000 blank.bin

don't wonder about the 2MB-c1 setting and don't change it. The AT binaries are build for 2MB-c1 partitioning. On 1 MB flash it will not support AT firmware OTA update.
If you want to use the Espressif Flash Download Tool, use the same settings as on esptool command line.


text:
Use std::list in Arduino programming
When trying to compile
#include <list>
std::list<byte> l = { 7, 5, 16, 8 };

in the Arduino IDE (with ATtinyCore for ATtiny4313), I get this message:

error: list: No such file or directory
    #include <list>

How to use the standard C++ std::list with Arduino/ATtiny?

I back up Michel Keijzers' suggestion to use a plain array, especially
given the tiny amount of RAM in your MCU (only 256 bytes).
Concerning the removal of items from the list, and given that your list
will be 16 bytes at most, you don't need to get fancy: just move back
the items that are past the one you removed. It will not take long.
Here is a barebones implementation of a list that can hold at most
16 bytes and supports removal:
class List {
public:
    byte length;
    byte data[16];
    void append(byte item) {
        if (length < 16) data[length++] = item;
    }
    void remove(byte index) {
        if (index >= length) return;
        memmove(&data[index], &data[index+1], length - index - 1);
        length--;
    }
};

Note that this only takes 17 bytes of RAM (16 items max plus a
length count). There is not vtable, as it has no virtual methods. You
can get fancier if you want, make this a template parametrized by the
data type and the maximum length, add accessors and such... but if you
are just writing a simple sketch (as opposed to a general purpose
library), I would recommend keeping it as simple as possible.
Example usage, based on your pseudo-code:
List l { .length = 3, .data = { 12, 82, 29 } };
l.remove(1);

This will indeed result in the list [12, 29].

Very useful, thanks a lot! Both answers are now very good, I don't know which one to choose!

PS: what is this syntax: List l { .length = 3 ... }; Is it a shortcut for something else to instanciate a class?

@Basj: It's an aggregate initialization: just filling the data fields, like in plain C. Handy when you are too lazy to write a proper constructor. ;-)

Thanks @EdgarBonet. Do you see a clever/lightweight way to find the index of a given element? Example: L = [12, 82, 29, 128].  L.indexof(29) would return 2. It's the last thing I need on these lists :)

@Basj: I see no clever way. But the list is so small that brute force is OK: just loop through the list until you find the element.

I did this, working!

I don't think that this library is supported by attiny (or even Arduino in general).
However, beyond that, it is not advised to use it, since it is uncertain how much memory and flash overhead it consumes.
Especially the memory is an issue for two reasons:

Internally, you don't know the exact data structures used for the list. In most efficient way, it will only use 4 bytes (4 times 1 byte for the array), however, since it is a class under the hood a vtable is added, and who knows what more memory (maximum capacity, current capacity of the list etc).
Also when adding/removing an item from the list, either the entire list is copied, or some tricks with pointers are used. In the first case you get memory gaps, in the second case maybe (and additional memory for the pointers is used).

My advice is to use just a simple array, and define a maximum of the array at compile time (if possible). Not as flexible, but robust, less memory usage and more reliable with a low SRAM  device like the Attiny (and Arduino in general).
Removing elements
Based on your first comment:
Removing items is indeed an issue, however, note that if you use the standard library it might copy the entire array (excluding) the new item, so temporarily you will have double the array AND a memory gap.
There are some ways to implement it yourself:

If you only want to remove items (and never add), add a new array with booleans that denote which are present and which are deleted (e.g. deleted[4] = 1 means that item 4 is deleted. This only cost 1 bit per element.
Use two arrays with items, and copy them back and forth each time. This will cause not really a memory gap, but you need the storage needed for two arrays. And keep a variable which of the two arrays is the 'current'.

Thank you for your answer. I would be happy to use a simple array (I need a list of 16 bytes maximum anyway). The only thing I cannot do easily with a simple array is this (pseudo-code): L = [12, 82, 29] => L.remove(index=1) => L = [12, 29] i.e. remove elements in the middle or at the beginning. Any idea how to do this easily without reinventing the wheel?

I updated my answer (only works for deleting items, adding items might be more tricky).


text:
How to control segway motor with arduino uno?
I salvaged segway motor with 8 wires. I did completed basic connection of 5 hall sensors and power from 36V lipo battery in the image  below. When I connect self-learning wires then motor starts rotating so connecting must be right. So now how do I control the motor with arduino?
Controller is kkmoon motor regulator 350W - link
didn't find datasheet about motor but here are some Information:-
Type: BLDC Motor
Voltage: 36V
no of wires:- 8 (3 wires  for 3 phase, 5 for hall sensor)
Power:- 300W

please provide a link to the motor datasheet

didn't find datasheet but posted some basic information above.


text:
Homodyne detection for arduino
In your code https://gist.github.com/edgar-bonet/0b03735d70366bc05fc6 for homodyne detection, is there a way to make the frequency detected a range of frequencies? For example detecting between 3kHz and 4kHz?
Thanks in advance!

It may be possible to modify that program in order to get such a large
frequency range:

change the local oscillator frequency to 3.5 kHz
drastically shorten the filter's time constant in order to get a
wider passband

However, the homodyne detection scheme is best suited for building very
narrow band filters. In your case, the upper limit you want is quite
close to the Nyquist frequency (4,808 Hz), so I suggest you use a
high-pass, rather than a band-pass filter. The simplest high-pass you
can get is a numerical derivative:
y[n] = x[n] − x[n−1]
The gain of this filter is 2×sin(π×f/fsamp), so you get the
−3 dB cutoff at fsamp/4 ≈ 2,404 Hz. If you need
something better, you may want to try a higher order filter. But then
you get deep into the territory of digital filter design, which can be
tricky, especially if you have no experience with the z-transform or you
want to implement the filter in fixed point.
Edit: If you really want a bandpass, the simplest I can think of is
this two-pole filter:
y[n] = 0.360 x[n] − 0.885 y[n−1] − 0.552 y[n−2]
It will give you a maximum gain of roughly 1 at about
3.43 kHz, and −3 dB cutoffs at 3 and 4 kHz. A
straightforward floating point implementation would be:
float filter(float x)
{
    static float y1, y2;
    float y = 0.360 * x - 0.885 * y1 - 0.552 * y2;
    y2 = y1;
    y1 = y;
    return y;
}

You should convert this to fixed point if you want to use it, otherwise
I doubt your Arduino will have the processing power to run every sample
through it. Below is a plot of this filter's gain, compared with the
simple derivative, which I divided by 2 in order to normalize its
gain:

Note that the gain gets flat as you approach the Nyquist frequency, and
stays relatively high (above −5.4 dB).

Thanks for your answer, but can you maybe show a code that already has that bandpass implemented in your previous code. We are not really experienced with Arduino so we really cannot figure out what exactly to change in your code... Thank you so much for your answers already though!


text:
Is volatile qualifier needed if shared variable cannot be changed externally during complete function call?
Consider the following example:
int i { 0 };

void incInt() {
    ++i;
}

int readInt() {
    return i;
}

setup() {
    Serial.begin(9600);
    attachInterrupt(digitalPinToInterrupt(D1), incInt, CHANGE);
}

loop() {
    noInterrupts();
    int currI = readInt();
    interrupts();

    Serial.println(currI);
}

By wrapping the call to readInt() with noInterrupts() and interrupts() it is ensured that i cannot be changed externally during the execution of readInt(). i also cannot be changed externally during the execution of incInt(), as long as it is only called as ISR (interrupt service routine). Do I still need to declare i as volatile?
Does the situation change if i is accessed directly in the main loop:
loop() {
    noInterrupts();
    int currI = i;
    interrupts();

    Serial.println(currI);
}

In other words: What is the context in which the compiler expects a variable to not be changed externally if it is not declared volatile?

Declaring a variable as volatile tells the compiler, that it always has to read the real variable and that it cannot use a cached value. Also the compiler cannot optimize this variable, since it is unknown, when the variable will change. For this it is irrelevant, how you actually read the variable in the main sketch, it only matters, that it get's read. Also this has nothing directly to do with doing the read atomically (with noInterrupts()) (though you only garantee correct values, when doing it)
So yes, you need to declare it volatile, or the compiler might think, that the value doesn't change and optimize it out in some way.

What is the context in which the compiler expects a variable to not be changed externally if it is not declared volatile?

Externally here means outside of the main routine. This covers variables, that get changed in ISRs and also registers, that are changed by hardware (so the register definition in the used core are also volatile). The compiler cannot know, when these changes happen, because they are triggered by the hardware, not by the code. It will try to optimize your sketch (which is a rather complex procedure), and might see, that your variable is never changing in the code (the ISR does not get called from the main sketch, thus the compiler does not see it getting called) and will try to optimize it. To ensure, that your sketch works properly, it is your task to tell the compiler, that this variable can change at any time (so that it does not think the other way). You are doing this by declaring it as volatile

Let's forget about atomicity for a moment, which is a separate issue, and
assume i is an atomic type (maybe byte or something equivalent).
Consider the following code:
void loop()
{
    Serial.println(i);
}

Not so long ago I would have expected this to work just fine on Arduino,
as there aren't many ways to compile this function… on its own! However,
since version 1.6.10, the IDE enables link-time optimization.
This means that the compiler (or rather, the optimizer working within
the linker), can see the whole program and notice that setup() and
loop() are called from only one function which belongs to the Arduino
core:
int main()  // slightly simplified
{
    init();      // Arduino core initialization
    setup();     // User's initialization
    for (;;)
        loop();  // User's loop
}

This makes them perfect candidates for inlining:
int main()
{
    init();      // will likely be inlined too

    // Inlined setup():
    Serial.begin(9600);
    attachInterrupt(digitalPinToInterrupt(D1), incInt, CHANGE);

    for (;;) {
        // Inlined loop():
        Serial.println(i);
    }
}

Now it should become clearer that repeatedly reading i from memory
looks like a waste of time, which can be optimized-out. The for loop then
becomes:
register uint8_t cached_i = i;  // save `i' in an internal CPU register
for (;;) {
    // Inlined loop():
    Serial.println(cached_i);
}

And now the program only prints zeros. That's why you need volatile to
prevent that optimization.


text:
Arduino How to Concat Strings
am stuck with something simple which is concating string not sure what am doing wrong , am getting exception (3 ) error due to it
3   LoadStoreErrorCause Processor internal physical address or data error during load or store

my code
    String HOST = "useotools.com";
    String API_URL = "/iot/api.php";   // API URL
    uint16_t HTTPS_PORT = 4000;  // HTTPS port
    uint16_t HTTP_PORT = 4001;  // HTTP port

void https_request_function(){
String HOST_URL = "http://"+String(HOST)+":"+String(HTTP_PORT)+String(API_URL)+"";

}

when first time https_request_function() is called then HOST_URL is displayed correctly and on 2nd time when this function is called by code it trigger exception(3) which is strange .

see CStringBuilderExample in my StreamLib (it is in Library Manager)

related: https://stackoverflow.com/q/308695/3984613 (as this is not entirely specific to Arduino)

@Ghanima thanks i tired like this but still on 2nd call it print weird boxes
snprintf(HOST_URL, sizeof HOST_URL, "%s%s%s%d%s", "http://",HOST.c_str(),":",HTTP_PORT,API_URL.c_str());

@Juraj that string builder lib not exists in esp boards :(

https://platformio.org/lib/search?query=streamlib

@Juraj thanks :)


text:
Arduino Uno board not recognized in IDE. Board is not in device manager!
My arduino uno is not recognized by the Arduino IDE. I'm using 1.8.0, The IDE is not showing the COM. The tool section is showing only COM 1, i.e. the hardware.
I opened Device manager, there is no board for UNO.
Help me please.

Arduino Nano works fine.
I have CH340 driver already installed. My computer do not make any "hardware connected sound". I have 3 arduino IDE versions - 1.8.0, 1.8.9, 1.8.10!.

Bad cable, or power only cable, will show the same thing. Try another one.

If you unplug/plug the USB cable, you might hear the typical "new device" sound. If yes, and there's a unknown usb device appearing,  it's not a real Arduino Uno, and you need an extra usb driver for it.  ( CH340 instead of 16U2 )

Even when I unplug/plug the USB cable, the computer do not make any sound and in addition, it do not even seem to affect the screen at all.(Do not show any change in IDE or Device Manager).

My arduino nano works fine & my computer do have an CH340 driver already for my Nano board.

I had a similar problem with my Arduino. My solution is to unplug it, replug it and do what you need to do before the computer can auto-configure it.
I hope it helps! :)
BTW make sure you are choosing the right board.

I really uninstalled and reinstalled arduino ide because of this problem. I tried replugging my board then too it does not work.

And I also have 3 Arduino IDE versions:- 1.8.0, 1.8.9, 1.8.10

According to https://www.arduino.cc/en/Guide/ArduinoUno, you may need to install a separate driver for the Arduino Uno because it does not have a true USB port. The details are in the link.

My arduino UNO chip says AtMega16u2..A97VB.


text:
Battery solution Nano 33 iOT
Since the Nano 33 boards are quite new right now, I haven't found any details on how to hook one up with batteries.
I'm pretty daft when it comes to electronics (I'm a software man), and I read that the new Nano 33 requires 3.2V, which is a bit of a departure from the 5V the old models supported.
From what I can tell, I might be able to use a single LiFePO4 cell. Am I correct in this assumption? And if so, are there any pitfalls in going this route?
EDIT: I might have misunderstood the difference between operating voltage and input voltage. Does this mean that I can plug any AA battery pack in as a power source?

The regulator can take up to 21 V. Use 2 x 18659 Li-Ion batteries in series.

You can either use the 3.3V pin to supply power to the board, or use the Vin pin.
By using the VIN pin to power goes through a (step down) voltage regulator, that provides a nice stable 3.3V to the board. The regulator in the Nano 33 IoT is the MPM3610, which requires an input voltage of at least 4 - 4.5 Volt. Which is more that a LiPo or LiFePo single cell can supply. You could use a multi-cell battery pack. Or a USB power bank. So this solutions is not really ideal.
The other option was to connect the battery directly to the 3.3V pin. The voltage of a LiFePo however changes as it is being discharged. The voltage is around 3.65V when full, and 2.5-2.75V when "empty". The 3.2V rating is called the nominal voltage (kind of an average voltage).
So it's a bit too high when full, and too low when empty. The voltage also isn't regulated, so it can fluctuate a bit, based on the amount of current that's being used.
The maximum voltage for the SAMD21 on this Nano is 3.63V. Maximum voltage for the gyro (LSM6DS3) is 3.6V. The absolute maximum voltage for the radio (NINA-W10) is 3.6V.
So a full LiFePo is slightly too high for the Nano. Though I think you should be fine. But don't try this with a regular LiPo of Lion battery (4.2V when full).

Thanks so much for replying to my question. Do I understand correctly that I could use three 1.5 volt AA batteries connected in a serial fashion to power the nano via the VIN pin?

Not quite. If you take 4V as the low point for voltage regulator, it would stop working if the batteries reach 1.33V, using only around 10% of the AA's total charge. I'd use at least 4 AA cells. Since it's a switching regulator it doesn't really matter what voltage you give it as long as it's between 4V/4.5V and 21V (unlike a linear regulator that just wastes the extra voltage). I'd go for 6 AAs. That way you can run them totally flat. The regulator is also a bit more efficient at a higher voltage.

Thanks a lot! That's exactly what I needed to know.

I tried running the board with  ~9.5V from 6 AA batteries, and while it did power up, the BLE module seems not to be working. I'm trying to figure out where to go from here by posting in the official Arduino forums.

You used the VIN pin, right? Do you have a multimeter, so you can measure the 3.3Volt rail?

I did use the VIN pin indeed! As mentioned, it managed to power a sketch that didn't use the BLE module. I'm not quite sure how to use a multimeter to measure the rail. (hence me being pretty daft with electronics :D)

If you can run some kind of blink sketch, while powered from batteries, the 3.3V is probably fine, but measuring can definitively rule that problem out. To measure, set the multimeter to measure voltage. If it has multiple range settings, select the smallest range that's still above the 3.3Volt. Then connect the black probe to the GND pin on the Nano, and the red prove to the 3.3V pin.

Thanks a bunch! Will do that when I get back to work tomorrow. (Can't believe I get to do this kind of stuff at work! Next up in the series: Me doing things I have no idea how to do)

I do have a second Nano 33 BLE that I can try. Tomorrow I will also try with a normal lithium power bank through the USB to see if that works. The price you pay for being an early adopter huh?

So the BLE only works when powered via USB?

That's what it seems like to me. Tomorrow I will use LED blink codes to debug the BLE sketch. I want to see how far the code execution reaches before it stops.

Haha! I think it was me leaving the "wait for serial" code in the example, which doesn't go past while(!Serial). Sorry, that's a stupid mistake from my part.


text:
Flash size in boards.txt ATmega 328p 32u4
The ATmega328p and ATmega32u4 microcontroller have 32Kb of flash memory (as datasheet). Bootloader for each microcontroleer has different size (about 512 byte for 328p and 4kb for 32u4).
Why in boards.txt the "upload.maximum_size" parameters is 32256 for 328p and 28672 for 32u4?
I we have to consider bootloader size, the "upload.maximum_size" parameter for 328p must be about 31.5k and not 32k. And, if we do not have to consider bootloader size, as the default boards.txt configuration (above) for 328p, the "upload.maximum_size" parameter for 32u4 must be 32k not 28k. Correct?
Thank you

1KB is 1024 bytes, not 1000 bytes.
Therefore 32kb = 32768 bytes.
32768-512=32256, which is exactly the value used for upload.maximum_size for the 328p.
4kb=4096 bytes. 32768-4096=28672 which is the value for the 32u4.

You are right @Gerben. Excuse me for my attention fault. I found this thread about 32u4 flash size. Is it possible the available flash (with bootloader) be less then ~28k because USB stack (as questioned in thread)?

Yes, you are correct. The 32u4 bootloader has to implement the USB stack, which the 328p only has to do UART, which is a lot simpler.


text:
Why Wire.write twice?
I'm checking an example for the MPU6050 and got to this part
Wire.beginTransmission(0x68);           //begin, Send the slave adress (in this case 68)
Wire.write(0x1B);                       //We want to write to the GYRO_CONFIG register (1B hex)
Wire.write(0x10);                       //Set the register bits as 00010000 (1000dps full scale)
Wire.endTransmission(true);             //End the transmission with the gyro

Serial.begin(9600);                     //Remember to set this same baud rate to the serial monitor
time = millis();                        //Start counting time in milliseconds

/*Here we calculate the gyro data error before we start the loop
 * I make the mean of 200 values, that should be enough*/
if(gyro_error==0)
{
  for(int i=0; i<200; i++)
  {
    Wire.beginTransmission(0x68);            //begin, Send the slave adress (in this case 68)
    Wire.write(0x43);                        //First adress of the Gyro data
    Wire.endTransmission(false);
    Wire.requestFrom(0x68,4,true);           //We ask for just 4 registers

Why is there two consecutive wire.write() in the begining and only one later? Is it different somehow?

it is write(byte). to write two bytes to TX buffer it must be called twice

The truth is, the Arduino Wire library sends the data only if endTransmission is called. Until then it collects the data in TX buffer. The version of the write function used in your snippet adds a byte to the TX buffer.
With I2C usually the first byte written is the address of the register to write. Then the data follow. In case of the first part in your snippet the data are only one byte long.
In the second part, first the register address is sent with write and then the data from this register and 3 following registers are requested.


text:
'TCCR1B' was not declared in this scope
I'm trying to use a MS5540C (digital pressure sensor)
and the sample code has this line:
 TCCR1B = (TCCR1B & 0xF8) | 1; //generates the MCLK signal

I'm a bit of a noob to the IoT but its not beyond me to check the SPI.h and see that there is indeed no declaration.
I'm using an Arduino UNO WiFi Rev 2.
(Seems like its pins are quit different from an UNO)
I have noted in the comments that Im using pins 32,33,34 instead of 11,12,13
I'm not 100% sure what to ask … other than
Is there a replacement call/function/method that should replace that line? ..or am I missing something else totally. As it stands now...when the program runs its results are inconsistent. I'm just commenting out the faulty line to get it to compile.
Complete sketch
source: Future Electronics
/*
  MS5540C Miniature Barometer Module
  This program will read your MS5440C or compatible pressure sensor every 5 seconds and show you the calibration words, the calibration factors,
  the raw values and the compensated values of temperature and pressure.
  Once you read out the calibration factors you can define them in the header of any sketch you write for the sensor.

  Uno Pins:
  MS5540 sensor attached to pins 10 - 13:
  MOSI: pin 11
  MISO: pin 12
  SCK: pin 13
  MCLK: pin 9 (or use external clock generator on 32kHz)
  CS is not in use, but might be pin 10

  ==[ addendum start]=============================
  Uno WiFi Rev2 Pins:
  MOSI: pin 32
  MISO: pin 33
  SCK: pin 34
  MCLK: pin 9 (or use external clock generator on 32kHz)
  ==[ addendum end ]=============================

  created 29 February 2012
  by MiGeRA
*/

/*
  Calibration of my sensor example ...

  Calibration word 1 = 46958
  Calibration word 2 = 65369
  Calibration word 3 = 39392
  Calibration word 4 = 45914
  c1 = 23479
  c2 = 2074
  c3 = 717
  c4 = 615
  c5 = 1021
  c6 = 25
*/

#include <SPI.h>

const int clock = 9;

void setup() {
  Serial.begin(9600);
  SPI.begin(); //see SPI library details on arduino.cc for details
  SPI.setBitOrder(MSBFIRST);
  SPI.setClockDivider(SPI_CLOCK_DIV32); //divide 16 MHz to communicate on 500 kHz

  pinMode(clock, OUTPUT);
  delay(100);
}

void loop()
{
  Serial.println("=====================================================================");
  TCCR1B = (TCCR1B & 0xF8) | 1; //generates the MCLK signal

  analogWrite (clock, 128) ;
  resetsensor(); //resets the sensor - caution: afterwards mode = SPI_MODE0!

  //Calibration word 1
  unsigned int result1 = 0;
  unsigned int inbyte1 = 0;
  SPI.transfer(0x1D); //send first byte of command to get calibration word 1
  SPI.transfer(0x50); //send second byte of command to get calibration word 1
  SPI.setDataMode(SPI_MODE1); //change mode in order to listen
  result1 = SPI.transfer(0x00); //send dummy byte to read first byte of word
  result1 = result1 << 8; //shift returned byte
  inbyte1 = SPI.transfer(0x00); //send dummy byte to read second byte of word
  result1 = result1 | inbyte1; //combine first and second byte of word
  Serial.print("Calibration word 1 = ");
  Serial.print(result1, HEX);
  Serial.print(" ");
  Serial.println(result1);

  resetsensor(); //resets the sensor

  //Calibration word 2; see comments on calibration word 1
  unsigned int result2 = 0;
  byte inbyte2 = 0;
  SPI.transfer(0x1D);
  SPI.transfer(0x60);
  SPI.setDataMode(SPI_MODE1);
  result2 = SPI.transfer(0x00);
  result2 = result2 << 8;
  inbyte2 = SPI.transfer(0x00);
  result2 = result2 | inbyte2;
  Serial.print("Calibration word 2 = ");
  Serial.print(result2, HEX);
  Serial.print(" ");
  Serial.println(result2);

  resetsensor(); //resets the sensor

  //Calibration word 3; see comments on calibration word 1
  unsigned int result3 = 0;
  byte inbyte3 = 0;
  SPI.transfer(0x1D);
  SPI.transfer(0x90);
  SPI.setDataMode(SPI_MODE1);
  result3 = SPI.transfer(0x00);
  result3 = result3 << 8;
  inbyte3 = SPI.transfer(0x00);
  result3 = result3 | inbyte3;
  Serial.print("Calibration word 3 = ");
  Serial.print(result3, HEX);
  Serial.print(" ");
  Serial.println(result3);

  resetsensor(); //resets the sensor

  //Calibration word 4; see comments on calibration word 1
  unsigned int result4 = 0;
  byte inbyte4 = 0;
  SPI.transfer(0x1D);
  SPI.transfer(0xA0);
  SPI.setDataMode(SPI_MODE1);
  result4 = SPI.transfer(0x00);
  result4 = result4 << 8;
  inbyte4 = SPI.transfer(0x00);
  result4 = result4 | inbyte4;
  Serial.print("Calibration word 4 = ");
  Serial.print(result4, HEX);
  Serial.print(" ");
  Serial.println(result4);

  //now we do some bitshifting to extract the calibration factors
  //out of the calibration words;
  long c1 = (result1 >> 1) & 0x7FFF;
  long c2 = ((result3 & 0x003F) << 6) | (result4 & 0x003F);
  long c3 = (result4 >> 6) & 0x03FF;
  long c4 = (result3 >> 6) & 0x03FF;
  long c5 = ((result1 & 0x0001) << 10) | ((result2 >> 6) & 0x03FF);
  long c6 = result2 & 0x003F;

  Serial.print("c1 = ");
  Serial.println(c1);
  Serial.print("c2 = ");
  Serial.println(c2);
  Serial.print("c3 = ");
  Serial.println(c3);
  Serial.print("c4 = ");
  Serial.println(c4);
  Serial.print("c5 = ");
  Serial.println(c5);
  Serial.print("c6 = ");
  Serial.println(c6);

  resetsensor(); //resets the sensor

  //Pressure:
  unsigned int presMSB = 0; //first byte of value
  unsigned int presLSB = 0; //last byte of value
  unsigned int D1 = 0;
  SPI.transfer(0x0F); //send first byte of command to get pressure value
  SPI.transfer(0x40); //send second byte of command to get pressure value
  delay(35); //wait for conversion end
  SPI.setDataMode(SPI_MODE1); //change mode in order to listen
  presMSB = SPI.transfer(0x00); //send dummy byte to read first byte of value
  presMSB = presMSB << 8; //shift first byte
  presLSB = SPI.transfer(0x00); //send dummy byte to read second byte of value
  D1 = presMSB | presLSB; //combine first and second byte of value
  Serial.print("D1 - Pressure raw = ");
  Serial.println(D1);

  resetsensor(); //resets the sensor

  //Temperature:
  unsigned int tempMSB = 0; //first byte of value
  unsigned int tempLSB = 0; //last byte of value
  unsigned int D2 = 0;
  SPI.transfer(0x0F); //send first byte of command to get temperature value
  SPI.transfer(0x20); //send second byte of command to get temperature value
  delay(35); //wait for conversion end
  SPI.setDataMode(SPI_MODE1); //change mode in order to listen
  tempMSB = SPI.transfer(0x00); //send dummy byte to read first byte of value
  tempMSB = tempMSB << 8; //shift first byte
  tempLSB = SPI.transfer(0x00); //send dummy byte to read second byte of value
  D2 = tempMSB | tempLSB; //combine first and second byte of value
  Serial.print("D2 - Temperature raw = ");
  Serial.println(D2); //voila!

  //calculation of the real values by means of the calibration factors and the maths
  //in the datasheet. const MUST be long
  const long UT1 = (c5 << 3) + 20224;
  const long dT = D2 - UT1;
  const long TEMP = 200 + ((dT * (c6 + 50)) >> 10);
  const long OFF  = (c2 * 4) + (((c4 - 512) * dT) >> 12);
  const long SENS = c1 + ((c3 * dT) >> 10) + 24576;
  const long X = (SENS * (D1 - 7168) >> 14) - OFF;
  long PCOMP = ((X * 10) >> 5) + 2500;
  float TEMPREAL = TEMP / 10;
  float PCOMPHG = PCOMP * 750.06 / 10000; // mbar*10 -> mmHg === ((mbar/10)/1000)*750/06

  /*
    Serial.print("UT1 = ");
    Serial.println(UT1);
    Serial.print("dT = ");
    Serial.println(dT);
    Serial.print("TEMP = ");
    Serial.println(TEMP);
    Serial.print("OFFP = ");
    Serial.println(OFF);
    Serial.print("SENS = ");
    Serial.println(SENS);
    Serial.print("X = ");
    Serial.println(X);
  */

  Serial.print("Real Temperature in C = ");
  Serial.println(TEMPREAL);

  Serial.print("Compensated pressure in mbar = ");
  Serial.println(PCOMP);
  Serial.print("Compensated pressure in mmHg = ");
  Serial.println(PCOMPHG);

  //2-nd order compensation only for T < 20°C or T > 45°C

  long T2 = 0;
  float P2 = 0;

  if (TEMP < 200)
  {
    T2 = (11 * (c6 + 24) * (200 - TEMP) * (200 - TEMP) ) >> 20;
    P2 = (3 * T2 * (PCOMP - 3500) ) >> 14;
  }
  else if (TEMP > 450)
  {
    T2 = (3 * (c6 + 24) * (450 - TEMP) * (450 - TEMP) ) >> 20;
    P2 = (T2 * (PCOMP - 10000) ) >> 13;
  }

  if ((TEMP < 200) || (TEMP > 450))
  {
    const float TEMP2 = TEMP - T2;
    const float PCOMP2 = PCOMP - P2;

    float TEMPREAL2 = TEMP2 / 10;
    float PCOMPHG2 = PCOMP2 * 750.06 / 10000; // mbar*10 -> mmHg === ((mbar/10)/1000)*750/06

    Serial.print("2-nd Real Temperature in C = ");
    Serial.println(TEMPREAL2);

    Serial.print("2-nd Compensated pressure in mbar = ");
    Serial.println(PCOMP2);
    Serial.print("2-nd Compensated pressure in mmHg = ");
    Serial.println(PCOMPHG2);
  }

  delay(5000);
}

void resetsensor() //this function keeps the sketch a little shorter
{
  SPI.setDataMode(SPI_MODE0);
  SPI.transfer(0x15);
  SPI.transfer(0x55);
  SPI.transfer(0x40);
}

Haave you written this code yourself, or did you copy parts of it somewhere? If the least, plase link to that source

@chrisl I added the source above. If you copy the text..take note of a char that is the 'f" and the 'l' combined!...ie in "float"...just retype it.

While writing this answer, I found out about the register emulation of the Arduino Uno Wifi. The Uno Wifi is a different chip, than the Uno, thus you have different registers. But the Uno Wifi was thought as a drop in replacement, so register emulation maps the old register names to the new registers, so that you can basically simply reuse the old code for the Uno. In my Arduino IDE (v1.8.9) I had a buildin Uno Wifi board, which seems to have the register emulation enabled without configuration option (I could compile your sketch even for the Uno Wifi). Through the board manager I installed the "Arduino megaAVR Boards" core, that contains the Arduino Uno Wifi rev2. If you choose this board in the board selection, you get the option to select the register emulation. For old code you need the emulation for ATmega328. With that, your old code should compile.
This makes the rest of my answer unnecessary, but since I already spend some time writing it,  I will leave it in the answer for information and for the case, that you don't want to use the register emulation.

You get the error, because the sketch, that you copied is made for the Arduino Uno, not the Arduino Uno Wifi. While the first uses an ATmega328P chip, the last is build with an ATmega4809 (you can find this information here at the Arduino.cc store). These are different chips, thus you cannot simply reuse code that is made for the Uno on the Uno Wifi.
TCCR1B is the control register B of Timer 1. This name is specific to the ATmega328P chip. The ATmega4809 has even more timers than the 328P, but they seem to get configured via different registers. Refer to the datasheets on the product site of the ATmega4809. The timer hardware and it's registers are described in the more general megaAVR 0 series family datasheet. At the first glance it seems, that not only the register description is different from the 328P, but also the positions of the different configurations. This means, that every code, that uses direct register manipulations for the timer, must be rewritten for the 4809.
Fortunately, I see only 1 line here, that does this: The line, that generated the compiler error. (The SPI library very likely already has fitting definitions inside for the 4809). You have the line
TCCR1B = (TCCR1B & 0xF8) | 1;

That clears the 3 least significant bits (leaving the rest as it was) and setting the least significant bit to 1. According to chapter 16.11.2 of the 328P's datasheet (description of the TCCR1B register), these 3 bits are the clock selection. A bit code of 001 (only least significant bit set) means timer on, but with no prescaling.
To be honest, I'm not sure, if this line really does something, since directly after that, analogWrite() is called and I thought this function would overwrite the timer settings. But other posts (like this one) suggest, that it at least does not overwrite the clock selection.
I don't know, which timer get's used for outputting PWM to that pin, but for now, I will assume the first timer of type B. If you look into the families datasheet (as linked above) the clock source of the second timer (TCB) is configured with the register TCB0.CTRLA (see chapter 20.5.1). Bits 1 and 2 are configuring the prescaler (binary 00 for no prescaler), bit 0 enables the timer. So you can again write binary 001 to this register, leaving the rest untouched. So I suggest, you use this line instead of the old one
TCB0.CTRLA = (TCB0.CTRLA & 0xF8) | 1;

This should do the same with the second timer, that was done in the original sketch. If the first timer is used for this, you would have to change TCB0 to TCA0.SINGLE (I really don't know, why this SINGLE is needed) and change 0xF8 to 0xF0, since TCA has 3 bits for selecting the clock source.

I might be a little over my head. I do have the right board in boardmanager. I had also tried changing the emulation. I still get the error! My initial thoughts were the preprocessor was boogering up the code. The calibration words keep changing. I can see now Im going to have to get a grip on registers,clocks..etc..etc.

I think the emulation doesn't cover timers

@Juraj But the old code compiles for me only with register emulation. Doesn't that mean, that it also does the emulation for the timer registers?


text:
SoftwareSerial receives beginning of data mangled
I'm using SoftwareSerial to communicate with a Sigfox module. Documentation for the read function assigns its value to a char. However using it I get mangled characters and also have read in other question that I should assign it to int as it can return -1 for no data and [0;255] for received character.
This is my basic troubleshooting example:
#include <SoftwareSerial.h>
SoftwareSerial Sigfox(11,10);

void setup() {
  Serial.begin(9600); // HW serial
  Sigfox.begin(9600); // SW serial --> sigfox
}

void loop() {
  if(Sigfox.available()) {
    int c = Sigfox.read();
    Serial.write(c);
  }
  if(Serial.available()) Sigfox.write(Serial.read());
}

When c is char, I get -5 instead of OK. Also other output is mangled. When c is int, it receives the data OK.
My question is - why they use char in the example in documentation? Why is char signed in Arduino?
I want to read the entire line of text from serial port and store it into array. How to define that array? I have found an example on web that uses char buffer[32], but then again I get mangled data when I assign to it. If I use array of byte/int/unsigned char, I can't print it as Serial.write(SF_buffer); won't compile because of no matching function for call to 'write(unsigned char [32])'.
So what variable types should I use to receive and store the text from SoftwareSerial correctly?
Here is my function for reading the whole line:
unsigned char SF_buffer [32]; // max length of line to read from serial
bool SigfoxReadine() { // return true when whole line was received and is in buffer
  static int SF_cnt=0;
  while (Sigfox.available()) {
    int c = Sigfox.read();
    SF_buffer[SF_cnt++] = c;
    if ((c == '\n') || (SF_cnt == sizeof(SF_buffer)-1)) {
       SF_buffer[SF_cnt] = '\0';
       SF_cnt = 0;
       return(true);
    }
  }
  return(false);
}

UPDATE:
Trying readBytesUntil - the same result, but I have found that issue is only when I send data to module using println as in this example:
#include <SoftwareSerial.h>
SoftwareSerial Sigfox(11,10);

void setup() {
  Serial.begin(9600); // HW serial
  Sigfox.begin(9600); // SW serial --> sigfox
  Sigfox.println("AT$I=11");
}

void loop() {
  if(Serial.available()) Sigfox.write(Serial.read());
  SF_read();
}

void SF_read() {
  if (Sigfox.available()) {
    char buff[32];
    int l = Sigfox.readBytesUntil('\n', buff, sizeof(buff));
    if (l > 0 && buff[l - 1] == '\r') {
      l--; // to remove \r if it is there
    }
    buff[l] = 0; // terminate the string
    Serial.println(buff);
  }
}

The response to first command (in setup) is mangled. The response to the same AT command manually written into serial monitor (and sent to module via Sigfox.write in loop) is OK.

ӂ*⸮FBB1E27EE7
3430E2FBB1E27EE7

Also maybe I'm little lost in when to use print and when write... Example says to use write() to send back the char that was read(). Juraj's response uses println() to print the null-terminated buffer. What is the difference when I write/println this buffer?

refer to this when dealing with char data type ... http://www.asciitable.com/

yes, using int data type is advisable ... if you use byte data type, then there is a conflict between data and an error flag ... a -1 is equivalent to hex 0xff, which is decimal 255 .... for int type, the decimal 255 is represented as 0x00ff and -1 is represented as 0xffff ... no conflict between those two .... please note that only a single byte is transmitted over serial ... the two byte int is created by the serial library so that your sketch has a way of receiving an error status from the library

Serial.write(SF_buffer, length); or for null terminated char array Serial.print(SF_buffer);

@Juraj if SF_buffer is char type, I get mangled output (SF_buffer[SF_cnt++]=c;). How to assign the int c into the char array correctly?

use byte. does the devices send characters with ascii codes above 127?

@Juraj usually not. But with char I got mangled for example original "OK" into "-5". I think I tried byte yesterday, but will try again when I get home.

did you wire ground? Serial.write(Sigfox.read()); must work

@Juraj yes I did :) That one works. It breaks when I save the value from read to variable and try to write that variable back. If I save it to char, "OK" prints as "-5". If I save it as byte or int, it prints OK, but then I have issue how to save whole line into array of chars.

what Arduino do you use?

@Juraj Arduino Pro Mini, Serial is connected to FTDI and USB. SoftwareSerial is Sigfox Wisol module. Arduino 1.8.9.

I like the readBytes or readBytesUntil function. It doesn't end on a small gap between received bytes and fills the buffer. This functions are blocking with timeout, but if read some other device the input is usually fast and terminated reliably.
example for readBytesUntil:
if (Serial.available()) {
  char buff[32];
  int l = Serial.readBytesUntil('\n', buff, sizeof(buff));
  if (l > 0 && buff[l - 1] == '\r') {
    l--; // to remove \r if it is there
  }
  buff[l] = 0; // terminate the string
  Serial.println(buff);
}

does readBytes exist also for SoftwareSerial? Documentation mentions it only for Serial

it is in the Stream base class

@Marki555, did it help?

testing... seems more strange now :) the issue from yesterday now seems to exist only when sending data to via Sigfox.println and not when using Sigfox.write...

edited the question with new findings

Found the issue! Thanks for troubleshooting help.

Last test showed it mangles data only when using println() and doesn't depend on the char type. Then I remembered something about CRLF in the Sigfox datasheet:

Is recommended to use full duplex UART. In case of using half duplex, AT
  commands has to be ended only with one of ‘\r’ or ‘\n’ not both. Because if you send
  “AT\r\n” the Sigfox devkit starts sending “OK” instantly after it receive ‘\r’, but
  microcontroller is still sending byte ‘\n’.

SoftwareSerial is in fact half-duplex only (although I didn't find it in the reference documentation) and println() sends both '\r' and '\n', so while sending the later, Sigfox module is already trying to send back the answer, which gets mangled by SoftwareSerial.
Feel free to add your answer to explain why char is signed in Arduino and when to use print() and when write() with serial port.


text:
Alternative for Particle Photon's Timer
I am converting a program made for particle photon to a Mega, everything is working except for the interrupt timer. The code that is of concern is (it's a .cpp file being included in the main .ino)
MyClass::MyClassConstructor(){
    messageTimer = new Timer(20, &MyClass::send, *this);
}

The documentation for this method is here.
Does anyone know a way to convert this to Arduino? There is the Timer library, but I can't really use the update method as the timer is in an instance of a class.

why do you need to convert code? ... why don't you instead describe how you want the code to function

The code, that you show us, only instantiates the timer with an interval and it's callback function. This also can be done for example with the Timer1 library. Please describe further where exactly you have a problem with that

try TimerOne library


text:
SIM800L GSM module is not working
I'm testing SIM800L GSM module with Arduino UNO and module is blinking 3 times every 15 seconds or sometime every 45 seconds. Why this is happening?
In serial monitor it shows Message Sent Successfully! but I'm not getting any message.I tried with multiple numbers. Still not getting any message.
I have tested several codes which shows outputs of AT commands. Nothing was working. Power supply is 5V 5A.
/*
 *   Author@ExploreEmbedded
 *   Example to Send messages Interactively using GSM Sim800L
 *
 *   LIBRARY CREDITS:
 *   Thanks to Cristian Steib(steibkhriz@gmail.com) for the library.
 *
 *
 *
 *      PINOUT:
 *        _____________________________
 *       |  ARDUINO UNO >>>   Sim800L  |
 *        -----------------------------
 *            GND      >>>   GND
 *        RX  10       >>>   TX
 *        TX  11       >>>   RX
 *       RESET 2       >>>   RST
 *
 *
*/

#include <Sim800L.h>
#include <SoftwareSerial.h> //is necesary for the library!!
Sim800L Sim800L;  //to declare the library
char text[161]=""; //buffer to store message
char number[11]=""; //phone number to send message
int cnt;
bool error; //to catch the response of sendSms

void setup(){
    Sim800L.begin(); // initializate the library.
    Serial.begin(9600);
}

void loop(){

      //Read the Number
      Serial.print("\nEnter 10 digit Phone Number:");
      while(Serial.available()<=0);
      cnt = Serial.readBytesUntil('\n',number, 11);
      number[cnt] = '\0';
      Serial.println(number);

      //clear the serial input buffer so that no typed characters are pending

      delay(1000); //delay required before clearing the input buffer
      while(Serial.available()>0) //clear buffer
      {
        Serial.read();
      }

      //Read the Message to be sent
      Serial.print("Enter Message:");
      while(Serial.available()<=0);
      cnt = Serial.readBytesUntil('\n',text, 160);
      text[cnt] = '\0';
      Serial.println(text);
      delay(1000);

      while(Serial.available()>0) //clear buffer
      {
        Serial.read();
      }

      //Send the message and display the status
      error = Sim800L.sendSms(number,text);
      if(error)
      Serial.println("Error Sending Message");
      Serial.println("Message Sent Successfully!");

}

I found what's happening. Module was shutdown due to over voltage.


text:
Relay board not working with nodemcu

This is the relay board
I am using nodemcu to make a home automation project which is controlled by google assistant. This is the code i am using is this one
#include <ESP8266WiFi.h>
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"

#define Relay1            D0
#define Relay2            D1
#define Relay3            D2
#define Relay4            D3

#define WLAN_SSID       "Subhodip"             // Your SSID
#define WLAN_PASS       "09003244135"        // Your password

/************************* Adafruit.io Setup *********************************/

#define AIO_SERVER      "io.adafruit.com"
#define AIO_SERVERPORT  1883                   // use 8883 for SSL
#define AIO_USERNAME    "SubhodipRoy"            // Replace it with your username
#define AIO_KEY         "50a98bb44f6b48b69e645badadf8fb577894"   // Replace with your Project Auth Key

/************ Global State (you don't need to change this!) ******************/

// Create an ESP8266 WiFiClient class to connect to the MQTT server.
WiFiClient client;
// or... use WiFiFlientSecure for SSL
//WiFiClientSecure client;

// Setup the MQTT client class by passing in the WiFi client and MQTT server and login details.
Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);

/****************************** Feeds ***************************************/

// Setup a feed called 'onoff' for subscribing to changes.
Adafruit_MQTT_Subscribe Light1 = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME"/feeds/Relay1"); // FeedName
Adafruit_MQTT_Subscribe Light2 = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/Relay2");
Adafruit_MQTT_Subscribe Light3 = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/Relay3");
Adafruit_MQTT_Subscribe Light4 = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/Relay4");

void MQTT_connect();

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

  pinMode(Relay1, OUTPUT);
  pinMode(Relay2, OUTPUT);
  pinMode(Relay3, OUTPUT);
  pinMode(Relay4, OUTPUT);

  // Connect to WiFi access point.
  Serial.println(); Serial.println();
  Serial.print("Connecting to ");
  Serial.println(WLAN_SSID);

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

  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

  // Setup MQTT subscription for onoff feed.
  mqtt.subscribe(&Light1);
  mqtt.subscribe(&Light3);
  mqtt.subscribe(&Light2);
  mqtt.subscribe(&Light4);
}

void loop() {

  MQTT_connect();

  Adafruit_MQTT_Subscribe *subscription;
  while ((subscription = mqtt.readSubscription(20000))) {
    if (subscription == &Light1) {
      Serial.print(F("Got: "));
      Serial.println((char *)Light1.lastread);
      int Light1_State = atoi((char *)Light1.lastread);
      digitalWrite(Relay1, Light1_State);

    }
    if (subscription == &Light2) {
      Serial.print(F("Got: "));
      Serial.println((char *)Light2.lastread);
      int Light2_State = atoi((char *)Light2.lastread);
      digitalWrite(Relay2, Light2_State);
    }
    if (subscription == &Light3) {
      Serial.print(F("Got: "));
      Serial.println((char *)Light3.lastread);
      int Light3_State = atoi((char *)Light3.lastread);
      digitalWrite(Relay3, Light3_State);
    }
    if (subscription == &Light4) {
      Serial.print(F("Got: "));
      Serial.println((char *)Light4.lastread);
      int Light4_State = atoi((char *)Light4.lastread);
      digitalWrite(Relay4, Light4_State);

    }
  }

}

void MQTT_connect() {
  int8_t ret;

  // Stop if already connected.
  if (mqtt.connected()) {
    return;
  }

  Serial.print("Connecting to MQTT... ");

  uint8_t retries = 3;

  while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
    Serial.println(mqtt.connectErrorString(ret));
    Serial.println("Retrying MQTT connection in 5 seconds...");
    mqtt.disconnect();
    delay(5000);  // wait 5 seconds
    retries--;
    if (retries == 0) {
      // basically die and wait for WDT to reset me
      while (1);
    }
  }
  Serial.println("MQTT Connected!");

}

Connecting the pins as stated below
VIN-->VCC
D0--> IN1
D1--> IN2
D2-->IN3
D3-->IN4
Gnd-->Gnd
But only IN2,IN3 and IN4 led of relay board are only glowing the IN1 is not glowing and the relays are not switching on/off...
Anyone please help....
Please give any solution... Why the relays are not switch-on?
Please reply as soon as possible... I am very disturbed... Even cant sleep at night....

not working how? how is it wired? you power the relays with 3.3 V?

Is the signal from the cloud really getting received? Please check that, by doing Serial prints in that case. If the cloud signal is received correctly, please provide a smaller test code without all the MQTT and Wifi stuff, only switching the relays. That would make it way easier to debug

why do you say that your connection uses 6 wires, when the picture shows only 5 wires?

I power relay with the nodemcu with 5v and dine the connections as mentioned above...

Yes data is being recieved from the cloud the led on the relay board are turning on/off except the IN1 LED which is not glowing except that the other 3 led on the relay board are working but the relays are not working

Sorry... I forgot the last pin

Yes I am having no new update anyone please predict the reason of it.

draw a picture with the wiring. this relay board enables a completely separate circuit for relays, signaled over optocouplers.

https://arduino.stackexchange.com/questions/60471/5v-10a-4-channel-relay-to-2-lights15w-light-in-series-in-220v-ac-supply/60484#60484

You can try connecting each relay input individually first to the 3V pin of the nodemcu and then to ground. The relay should switch. Place your ear closely to the relay and try to hear the click. If this does not happen, try with 5V. Check, if ground and Vcc are correctly connected to the relay board. If still nothing happens, your relay board might be broken

From the description and comments it looks like the problem is HW related. I recommend you to do a relay module test (wthout NodeMCU):

Try to switch the relays on/off  just by connecting the power source you are using for powering the NodeMCU. Connect VCC–5V, GND–GND and one of the IN channels directly to 5V pin. If the relay switches on, try another channel. If not, try to connect IN to GND instead of 5V (inverted logic).
If 1. did not worked, check the yellow jumper on the right side of the relay board. The jumper must be attached (in case you don't want to use another independent power source just for relays).
If 2. did not worked, check if the relay board is not intended for use with 12 V DC power source (check the relay marking).

At this point you should know if all channels of the relay module are working and also the switching logic (inverted/noninverted). The next step should be connecting the relay module to the NodeMCU and run a "blink" example for all channels. If all is working well, we will be sure the problem is NOT HW related...

1.I am using a power bank how will i connect the jumper wire with the power bank.                2. Where the yellow wire should be connected. 3. Its 5v I am sure.

There is more ways how to connect the power source. The easiest probably is to connect power source to NodeMCU and use GND and 5V pin.
Not a wire, a jumper. It is the yellow thingy on the right bottom corner of the relay board.


text:
Arduino and Processing- Conditionals only executing sometimes in response to IR codes
I am reasonably new to arduino and even newer to Processing so still struggle with trouble shooting my code.
The intention of my sketch is have Processing receive IR codes from the arduino and execute different AppleScript applications accordingly.
It works sometimes! However I would really love it to work all the time :)
-The AppleScript apps definitely work and have been successfully launched
-The processing monitor has been printing the 'Val' variable consistently
The issue is that even though processing is reading from the serial port and assigning the IR codes printed there to the 'val' variable, it only sometimes executes the conditional
I added a delay to my arduino sketch to slow down how much data was entering the port and make it easier for Processing to read but it's inconsistent.
Any help would be greatly appreciated!
Arduino code:
#include <boarddefs.h>
#include <ir_Lego_PF_BitStreamEncoder.h>
#include <IRremote.h>
#include <IRremoteInt.h>

int RECV_PIN = 10;
IRrecv irrecv(RECV_PIN);
decode_results results;

void setup()
{
  Serial.begin(9600);
  Serial.print("Hello");
  irrecv.enableIRIn(); // Start the receiver
}

void loop()
{
  if (irrecv.decode(&results))
    {
     Serial.println(String(results.value,HEX));
     delay(100);
     irrecv.resume(); // Receive the next value
    }
}

Processing Code
import processing.serial.*;

Serial myPort;  // Create object from Serial class
String val;     // Data received from the serial port
String Down = "890";
String Up = "8188A2C8";
String CH1 = "E10";
void setup()
{
  // I know that the first port in the serial list on my mac
  // is Serial.list()[0].
  // On Windows machines, this generally opens COM1.
  // Open whatever port is the one you're using.
  String portName = Serial.list()[2]; //change the 0 to a 1 or 2 etc. to match your port
  myPort = new Serial(this, portName, 9600);
}

void draw()
{
  {
  if ( myPort.available() > 0)
  {  // If data is available,
  val = myPort.readString();         // read it and store it in val

   print(val);

    if(val.equals(Down) == true)
    {launch("/Applications/QlabDown.app");
  }
  if (val.equals(Up) == true) {
    launch("/Applications/QlabUp.app");
  }
  if (val.equals(CH1) == true) {
    launch("/Applications/CH1.app");
  }
}
}
}

what does this mean? Processing receive IR codes from the arduino .... how is Processing receiving infrared signals?

Assuming there are two Arduinos.  One running the "Arduino code" and the other running the "Processing code".  The "Arduino code" has the manditory setup() and a loop() functions.  But the "Processing code" only has the mandatory setup() function and is missing the loop() function.

Sorry for not being clear, the Processing sketch is being ran on my laptop and is receiving the IR codes via the USB serial port created when the arduino is plugged into the laptop.


text:
How to send JSON on a http POST request using an ESP8266?
I'm working on a project aimed on sending alerts via SMS. I signed up for a SMS service that works via HTTP requests (REST standard). I need, then, to send data as JSON, so that their server processes the data and sends the SMS message to a list of recipients.
I am working with an ESP8266 board. I have tried some code, but I couldn't do the JSON part properly, given I have little knowledge on HTTP requests and HTTP libraries for Arduino. I managed to test things using python code (with which I am much more familiar).
In short, I have this piece of code in python that works quite perfectly:
payload = {'sender': '558499999999','content': 'Just a message', 'groupName': 'Recipients_list'}
request = requests.post('https://cheap.sms.sending.guys/sendcontactmessage',
                         data=json.dumps(payload),
                         headers={'content-type': 'application/json', 'auth-key': 'My_authentication_key'})

I tried to write something that does the same thing on a ESP8266, but it is not working and I can't figure the correct way to do it. The code I tried was the following:
#include <ArduinoJson.h>
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

const char* ssid = "my_ssid";
const char* password = "my_password";

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

  //TESTING JSON CREATION
  Serial.println("Starting JSON");
  StaticJsonBuffer<69> jsonBuffer;
  char json[] = "{\"sender\":\"558499999999\",\"content\":\"Just a message\",\"groupName\":\"Recipients_list\"}";
  JsonObject& root = jsonBuffer.parseObject(json);
  if(!root.success()) {
    Serial.println("parseObject() failed");
  } else {
    Serial.println("JSON OK");
  }

  WiFi.begin(ssid, password);

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

  //TESTING POST
  //headers={'content-type': 'application/json', 'auth-key': 'My_authentication_key'}
  String sms_service_URL = "https://cheap.sms.sending.guys/sendcontactmessage";

  Serial.println("TESTING POST");
  //Declare an object of class HTTPClient
  HTTPClient http;

  if (WiFi.status() == WL_CONNECTED) {
    //Specify request destination
    http.begin(sms_service_URL);
    http.addHeader("Content-Type", "application/json");
    http.addHeader("auth-key", "My_authentication_key");

    String data;
    root.printTo(data);
    //Send the request
    int httpCode = http.POST(data);

    //Check the returning code
    if (httpCode > 0) {
      //Get the request response payload
      String payload = http.getString();
      //Print the response payload
      Serial.println(payload);
    }
    //Close connection
    http.end();
    Serial.println(httpCode);
  }
}

void loop() {

}

I am aware that the arduino code is pretty lame. I was just in a trial-failure process, lol.
I'd appreciate any suggestions

What is the problem? What output do you get? Also, why do you first create a JSON string, then parse that string into an JSON object tree, and then convert it back into a string (which should be identical to the first string)? You can just skip those last two steps.

I'm not sure if I have understood your requirements right, but generally JSON is just text and so the actual transmission should ve trivial. It's up to the devices at either end how to handle this data


text:
How much current needed to power arduino uno?
I am planning to build an rc car based on arduino uno. I will use 3S 11.1 V Li-po to power whole circuitry. So my question is;
First, can arduino be powered directly with 11.1V from its Vin pin? Would it be a problem or not? If it is OK, then no need to answer the bold part below.
If it is not, then one solution comes to my mind is to use a voltage regulator which will convert 11.1 V to 5 V. But while choosing a regulator, I saw that max output current is one of the important specs. So what is the minimum amount of current needed to run Arduino UNO?

The maximum voltage at the Vin pin is 12V, so using your battery is fine!
Considering the current consumption:
The arduino itself will usually source less than 200mA, but your whole setup will probably sink more than that.

I was wondering just because of the current limitation of voltage regulator, I would use it only to power arduino. For exampe there was one with max 600mA output current so in that case, if 11.1 V wasn't be a valid input, then 600mA is also capable of supplying arduino based on what I understood from your answer. Thanks!


text:
3v to 3.5v step up?
I would like to run my esp32 on coin cell batteries, tho it needs at minimum 3v, that means if there just is too much resistance in the vires or anything else, stuff like Bluetooth will make it brownout,
So what is the best way to step up 3v to 3.5v?

To be honest you are better off stepping down rather than stepping up. Simply because step down converters tend to be a higher efficiency and can deliver more current than a step up converter.
With step up converters you effectively convert current into voltage. With step down it's the other way around - voltage into current.  Since button cells have very very little current capacity stepping up will reduce it even more and starve the ESP32 of power. By stepping down you increase the current.
Two 3V button cells in series will provide nominal 6V and about 40mA current. By adding a step down converter to 3.3V you are almost halving the voltage, but at the same time almost doubling the current.  Adding a third cell in series will give you even more current output.
It is possible to get some incredibly tiny and high efficiency step-down modules. I myself make and sell one based around the TPS82130SILT which has the ability to run at as low as 3.7V with a 3.3V output (it has a "pass through" mode which allows a zero dropout voltage, but I include a protection diode with 0.4v drop). That means you get the entire 6V to 3.7V range out of your batteries before the voltage starts to droop (assuming the batteries still operate at 1.85V).

Generally, to step up voltages you can use a boost converter.
But I doubt that using coin cells to supply an esp32 is a good idea, because they probably won't last very long and are relatively expensive. Even if you use sleep modes, the voltage margin will be small (of course, that depends on the boost converter).

well the esp will only be active 4-6 times a day, and only in a few seconds for sending information to a database, the rest of the time it will be in deep sleep

it's going to run on 2 3v 260mah coin cell batteries, I calculated it to be about 5 months of run time

i could be wrong tho

Alright, I personally just don't like using coin cells and till now I always had enough space for a bigger LiPo. The converter will have some losses, but maybe that's fine...

well i want the final to be as slim as possible, since there already needs to be place for pcb and chip, 2 coin cell batteries on the back of the pcb would be perfect

well, i asked for a good converter, do you have any recormendations?

Well, we don't do product recommandations. Simply go to your prefered distributor's website and search for "switching voltage regulators". Go for a high switching frequency, this will allow you to use small capacitors and inductors

Why not use three button cells and a buck converter to lower the voltage from 4.5V down to 3V?

haven't read on buck converters, is it just a kind of step down?

I want to only use 2 coin cell batteries, for the size, it wouldn't be the biggest disaster to make it a bit bigger to fit 1 more battery, but the buck converters I found online looked pretty big, Too big

@MariusWanscher in general, both buck and boost converters consist of the same components and they both exist in very small dimensions

@MariusWanscher I make a really really really tiny buck converter. You can't get smaller. It will run from 2x 3V cells in series (or 3x if you can) and down to 3.3V on the input for 3.3V output. https://www.ebay.co.uk/itm/183933078163 - however I can't guarantee that the ESP8266 will like the low current output of button cells.


text:
How to send keystroke with shift modifier?
This is a bit of a newbie question, but here it goes anyway. So basically I want to send a keystroke using the DigiKeyboard library, but with shift held down. I looked through the code and saw this comment in scancode-ascii-table.h:
//Format: most signifficant bit indicates if scan code should be sent with shift modifier
remaining 7 bits are to be used as scan code number.

I dont really understand where to specify this, whether it's when you call the sendKeyStroke function, or somewhere in the code. Help appreciated.

what does most significant bit mean to you?

I never used this library, but in the header file there are this constants for modifiers:
#define MOD_CONTROL_LEFT    (1<<0)
#define MOD_SHIFT_LEFT      (1<<1)
#define MOD_ALT_LEFT        (1<<2)
#define MOD_GUI_LEFT        (1<<3)
#define MOD_CONTROL_RIGHT   (1<<4)
#define MOD_SHIFT_RIGHT     (1<<5)
#define MOD_ALT_RIGHT       (1<<6)
#define MOD_GUI_RIGHT       (1<<7)

and a function
void sendKeyStroke(byte keyStroke, byte modifiers)

so I would use this to send a key with Shift like this
sendKeyStroke(KEY_F2, MOD_SHIFT_LEFT);

Oooooh thank you! That works perfectly!


text:
I get the following error when I typed the below code. " Stray'\302" in the programme .I tried to sort it but failed
#include <Keypad.h>

#include<LiquidCrystal.h>

#include<EEPROM.h>

LiquidCrystal liquid_crystal_display(9,8,7,6,5,4,);

char password[4];

char initial_password[4],new_password[4];

int i=0;

int relay_pin = 10;

char key_pressed=0;

const byte rows = 4;

const byte columns = 4;

char hexaKeys[rows][columns] = {

{'1','2','3','A'},

{'4','5','6','B'},

{'7','8','9','C'},

{'*','0','#','D'}

};

byte row_pins[rows] = {A0,A1,A2,A3};

byte column_pins[columns] = {A4,A5,3,2};

Keypad keypad_key = Keypad( makeKeymap(hexaKeys), row_pins, column_pins, rows, columns);

void setup()

{

  pinMode(relay_pin, OUTPUT);

  liquid_crystal_display.begin(16,2);

  liquid_crystal_display.print(" DIYhacking.com");

  liquid_crystal_display.setCursor(0,1);

  liquid_crystal_display.print("Electronic Lock ");

  delay(2000);

  liquid_crystal_display.clear();

  liquid_crystal_display.print("Enter Password");

  liquid_crystal_display.setCursor(0,1);

  initialpassword();

}

void loop()

{

  digitalWrite(relay_pin, HIGH);

  key_pressed = keypad_key.getKey();

  if(key_pressed=='#')

    change();

  if (key_pressed)

  {

    password[i++]=key_pressed;

    liquid_crystal_display.print(key_pressed);

      }

  if(i==4)

  {

    delay(200);

    for(int j=0;j<4;j++)

      initial_password[j]=EEPROM.read(j);

    if(!(strncmp(password, initial_password,4)))

    {

      liquid_crystal_display.clear();

      liquid_crystal_display.print("Pass Accepted");

      digitalWrite(relay_pin, LOW);

      delay(2000);

      liquid_crystal_display.setCursor(0,1);

      liquid_crystal_display.print("Pres # to change");

      delay(2000);

      liquid_crystal_display.clear();

      liquid_crystal_display.print("Enter Password:");

      liquid_crystal_display.setCursor(0,1);

      i=0;

    }

    else

    {

      digitalWrite(relay_pin, HIGH);

      liquid_crystal_display.clear();

      liquid_crystal_display.print("Wrong Password");

      liquid_crystal_display.setCursor(0,1);

      liquid_crystal_display.print("Pres # to Change");

      delay(2000);

      liquid_crystal_display.clear();

      liquid_crystal_display.print("Enter Password");

      liquid_crystal_display.setCursor(0,1);

      i=0;

    }

  }

}

void change()

{

  int j=0;

  liquid_crystal_display.clear();

  liquid_crystal_display.print("Current Password");

  liquid_crystal_display.setCursor(0,1);

  while(j<4)

  {

    char key=keypad_key.getKey();

    if(key)

    {

      new_password[j++]=key;

      liquid_crystal_display.print(key);

    }

    key=0;

  }

  delay(500);

  if((strncmp(new_password, initial_password, 4)))

  {

    liquid_crystal_display.clear();

    liquid_crystal_display.print("Wrong Password");

    liquid_crystal_display.setCursor(0,1);

    liquid_crystal_display.print("Try Again");

    delay(1000);

  }

  else

  {

    j=0;

    liquid_crystal_display.clear();

    liquid_crystal_display.print("New Password:");

    liquid_crystal_display.setCursor(0,1);

    while(j<4)

    {

      char key=keypad_key.getKey();

      if(key)

      {

        initial_password[j]=key;

        liquid_crystal_display.print(key);

        EEPROM.write(j,key);

        j++;

      }

    }

    liquid_crystal_display.print("Pass Changed");

    delay(1000);

  }

  liquid_crystal_display.clear();

  liquid_crystal_display.print("Enter Password");

  liquid_crystal_display.setCursor(0,1);

  key_pressed=0;

}

void initialpassword(){

  for(int j=0;j<4;j++)

    EEPROM.write(j, j+49);

  for(int j=0;j<4;j++)

    initial_password[j]=EEPROM.read(j);

}

https://majenko.co.uk/blog/common-arduino-errors-and-warnings

You should always include the full error message (which also describes the line, where the error happened) into your question. 2. Look at the declaration line of liquid_crystal_dysplay. There is a comma too much


text:
Cannot upload to Leonardo after update to macOS Catalina
I'm not sure this is the right site, but I've spent several hours trying to figure out why I suddenly cannot upload to my Leonardo (actually, a "Pro Micro" with a 32u4) after upgrading to macOS Catalina.
Initially I thought the board was just dead, but I can program it without issues from a Windows machine. I also worked just fine with it a few days ago, before the update to Catalina. Now I'm getting this output:
Arduino: 1.8.10 (Mac OS X), Board: "Arduino Leonardo"

Sketch uses 10226 bytes (35%) of program storage space. Maximum is 28672 bytes.
Global variables use 1000 bytes (39%) of dynamic memory, leaving 1560 bytes for local variables. Maximum is 2560 bytes.

avrdude: ser_recv(): read error: Device not configured
avrdude: butterfly_recv(): programmer is not responding
avrdude: ser_drain(): read error: Device not configured
avrdude: ser_send(): write error: Device not configured
avrdude: ser_recv(): read error: Device not configured
avrdude: butterfly_recv(): programmer is not responding
avrdude: ser_send(): write error: Device not configured
avrdude: ser_recv(): read error: Device not configured
avrdude: butterfly_recv(): programmer is not responding
avrdude: ser_recv(): read error: Device not configured
avrdude: butterfly_recv(): programmer is not responding
avrdude: ser_send(): write error: Device not configured
avrdude: ser_recv(): read error: Device not configured
avrdude: butterfly_recv(): programmer is not responding
Found programmer: Id = ""; type = �
Software Version = .�; Hardware Version = �.�
avrdude: ser_send(): write error: Device not configured
avrdude: ser_recv(): read error: Device not configured
avrdude: butterfly_recv(): programmer is not responding
avrdude: ser_send(): write error: Device not configured
avrdude: ser_recv(): read error: Device not configured
avrdude: butterfly_recv(): programmer is not responding
avrdude: error: buffered memory access not supported. Maybe it isn't
a butterfly/AVR109 but a AVR910 device?
avrdude: initialization failed, rc=-1
     Double check connections and try again, or use -F to override
     this check.

avrdude: ser_send(): write error: Device not configured
avrdude: ser_recv(): read error: Device not configured
avrdude: butterfly_recv(): programmer is not responding
avrdude: error: programmer did not respond to command: leave prog mode
avrdude: ser_send(): write error: Device not configured
avrdude: ser_recv(): read error: Device not configured
avrdude: butterfly_recv(): programmer is not responding
avrdude: error: programmer did not respond to command: exit bootloader
avrdude: ser_close(): can't reset attributes for device: Device not configured
the selected serial port avrdude: ser_close(): can't reset attributes for device: Device not configured
does not exist or your board is not connected

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

My Mega2560 as well as Due work just fine. I even tried re-burning the bootloader into the Pro Micro using the Mega, which worked fine but didn't solve the issue.
I also tried getting into the bootloader mode, by tapping the reset (actually, using a wire to pull RST to GND) button twice. It changes the error to
Found programmer: Id = ">>> SPI"; type = SSoftware Version = >.>;
Hardware Version = >.
avrdude: error: buffered memory access not supported.
Maybe it isn't a butterfly/AVR109 but a AVR910 device?
avrdude: initialization failed, rc=-1
Double check connections and try again, or use -F to override this check.

The bootloader trick is not required on Windows, it just works.

In case people are arriving here from search engines, there is an open issue on the Arduino GitHub tracker: https://github.com/arduino/Arduino/issues/9290