text:
"Stand-alone" serial monitor
I usually use Platformio as IDE for my Arduino projects. I like it as an editor, but I don't like its serial monitor feature. So I often open the Arduino IDE in background to use its serial monitor, but this has some drawbacks (including a significant increase in my computer's CPU usage and battery consumption).
Is there an Arduino-compatible serial monitor application that just works as a serial monitor (and not also as an IDE)? I'm most interested in a MacOS application, but if you know a Windows one please tell me as well.

putty ... http://www.putty.org/ ...

I regularly use GNU screen. For example screen /dev/ttyUSB0 115200 where /dev/ttyUSB0 is the serial port of the Arduino, and 115200 is the baud rate.
What's wrong with the PlatformIO serial monitor, by the way?

you can use any serial terminal, search for them. putty is pretty good. aside: do you get constant CPU usage from the arduino program as well? (thought it was just me...)

You can use almost anything; but the catch with using something not integrated is that it may not automatically get out of the way when you try to upload code.

@tttapa thanks. Is there also some kind of gnu serial port scanner? — the biggest issue (for me) is the fact that I can’t copy the output (I don’t know if it’s an issue of PlatformIO, Atom or something on my computer... but as I select one serial monitor word all the text in the window get selected); a secondary problem is that putting data in is quite tricky (compared to the Arduino ide serial monitor)

@dandavis sorry, what do you mean by “do you get constant CPU usage from the arduino program as well?”

Note also that terminal emulators (putty, GNU screen, ...) are way more capable than the Arduino serial monitor, as they let you use ANSI escape sequences to control the cursor, set colors, etc. C.f. the bar display at the top left of this screenshot.

sometimes the IDE pegs my CPU at 25% even idle (the OS blames java), was wondering if that same nastyness was what caused the battery consumption you mentioned...

@noearchimede of course you can copy from the terminal. It just uses a different short cut. On Linux, this is CTRL+SHIFT+C instead of CTRL+C (CTRL+C sends a break), not sure what the Mac equivalent is.

@dandavis yes, that happens quite often and it probably is the most important battery consumption cause

@dandavis do you get constant CPU usage from the arduino program as well? - I found a while ago that under certain circumstances (failed upload was one I think) that the IDE went to using 100% CPU. The only reason it took a while to notice was that I have a 4-core CPU and the other CPUs kept running. I think it wasn't the IDE per se, but a process running avrdude that was looping. After 4 failed uploads my PC got a bit sluggish. :)

@NickGammon: yup, that's it. if i have several sketches open, sometimes I can close 1+ of them (not all) and the 100% usage goes away.

I use CoolTerm, which is available for Mac, Windows and Linux. It is a great serial app, and you can have several windows open at the same, for each serial pipe you may be using (Bluetooth, Arduino Serial, etc).

On macOS, you can use the built-in screen command, e.g.:
screen /dev/cu.usbmodem14201 9600

To exit, control-A followed by control-\

Consider building your own monitor in Python. This gives you flexibility since Python is cross platform and you can tailor the monitor to your needs.

Install Python.
Install pySerial (pip install pyserial).
Write a Python script to read and/or write to the Arduino across the serial port. There are some great examples out there such as this example and other Stack Overflow answers.

There's a list of serial port sniffers here, if you want to view raw data
 softwarerecs.stackexchange serial-port-logging
And a list here of programs which plot graphs from serial data:
softwarerecs.stackexchange serial-data-plotting-programs


text:
inttypes vs Arduino defined integral types
In my Arduino projects I use both Arduino types and types defined in the "inttypes.h" file, which #includes stdint.h. So far I've always written code only for the ATmega328P microcontroller (either in the UNO board or "standalone").
To be clear, in this question I'm referring to the following types:

"Arduino": char, int, long; byte, word, unsigned long
inttypes: int8_t, int16_t, int32_t; uint8_t, uint16_t, uint32_t

What is the actual difference between e.g. int and int16_t?
Is implicit conversion between corresponding types always possible, or should I avoid it even if the compiler doesn't complain? (quite often in my programs I pass an int16_t as int argument to a function and it always works, but is it good practice to do it, in general?

"Arduino": char, int, long; byte, word, unsigned long
inttypes: int8_t, int16_t, int32_t; uint8_t, uint16_t, uint32_t

A better classification would be:

C and C++: char, int, long, unsigned long
"Arduino": byte, word
inttypes: int8_t, int16_t, int32_t; uint8_t, uint16_t, uint32_t

I generally avoid the Arduino-specific types, as they are quite
non-standard, and do not usually exist outside the Arduino world. As for
the other types, just like Michel Keijzers suggests, I use the C types
when I do not care much about the exact size. int is guaranteed to be
at least 16 bits, but is likely to be 32 bits on a 32-bit architecture.
It is a good default type, as it is supposed to be efficiently handled
on any architecture. These types allow you to write portable code that
automatically selects the "right" integer width for whatever
architecture it is been compiled for.
If you care about the exact size, which can often be the case in a
memory-constrained environment, use the types from inttypes.h. And do
not worry about implicit conversions: as long as both types are wide
enough to hold the numbers you need to store, a type conversion, whether
implicit or explicit, always preserves the value.

int can be depending on the hardware architecture and is mostly 16 or 32 bit.
However, an int16_t is always 16 bit, regardless of the hardware architecture.
It will go wrong when you have a 32 bit architecture (for an int), and you are going to cast it to an int16_t, than you lose the MSB 16 bits. Although I think the compiler will give a warning in this case (so in your case you are ok, but it can prevent a lot of work when you port your code to a 32 bit architecture).
However, all Arduinos have int defined as 16 bit, except the Due and SAMD based boards, see: Arduino reference for int (updated after the comment of per1234 below, thanks for that).
Normally I use integer when I don't care much about the type (and know it will stay under 32768, like for most indices in loops). But if you define a (large) array it's better to use an explicit type, or if you know for sure the value will never be higher than 32768 (int8_t) or nonnegative and 65535 (uint8_t).
Also, for the 'eye' unsigned char for an unsigned 'integer' value upto 255, uint8_t looks better than a 'char' which seems more like a character instead of a value.

"However, all Arduinos have int defined as 16 bit, I think that's even true for the Due's." This is incorrect. See https://www.arduino.cc/en/Reference/Int

@per1234 Thank you, I updated my answer

"or if you know for sure the value will never be higher than 32768 (int8_t) or nonnegative and 65535 (uint8_t)."
Did you mean int16_t and uint16_t?
This topic can generate some confusion and casual errors like this can compound the problem.

source: Stack Exchange

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

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

sort: votes


text:
sbi() and cli() implementation
I've often seen cli() and sbi() in Arduino code. I usually don't mind them as I know what they do (clear or set the bit given as second argument in the register of the microcontroller given as first). I've always thought that those functions where only a clear way to perform simple bit manipulation, which can be quite error-prone. Something like that:
#define cli(reg,bit) (*reg &= ~(1 << bit) and #define sbi(reg,bit) (*reg |= (1 << bit)).
Then I found out that the actual implementation is as follows:
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))

It's quite like I used to think... but with two extra macros.
I looked for them in the Arduino libraries:
#define _BV(bit) (1 << (bit))

and
#define _SFR_BYTE(sfr) _MMIO_BYTE(_SFR_ADDR(sfr))

which contains
#define _MMIO_BYTE(mem_addr) (*(volatile uint8_t *)(mem_addr))

and
#if _SFR_ASM_COMPAT
#if (__SFR_OFFSET == 0x20)
#define _SFR_ADDR(sfr) _SFR_MEM_ADDR(sfr)
#elif !defined(__ASSEMBLER__)
#define _SFR_ADDR(sfr) (_SFR_IO_REG_P(sfr) ? (_SFR_IO_ADDR(sfr) + 0x20) : _SFR_MEM_ADDR(sfr))
#endif
#else  /* !_SFR_ASM_COMPAT */
#define _SFR_ADDR(sfr) _SFR_MEM_ADDR(sfr)

Further research took me to definitions I couldn't understand (for example because they are explained in comments using a lot of acronyms I don't know).
So I have the following questions:

Why is sfr casted to *(volatile uint8_t *)?
What do the acronyms used in that code mean? (ASM, SFR, MMIO)
Under what circumstances is __ASSEMBLER__ defined, and where (in which file)?
Why can't we simply write #define cli(reg,bit) (*reg &= ~(1 << bit) and #define sbi(reg,bit) (*reg |= (1 << bit))?

Why is sfr casted to *(volatile uint8_t *)?

Because you want the content (the first *) of a memory address that you specify, and you need it volatile so it doesn't cache it. Oh, and it's an 8-bit value.

What do the acronyms used in that code mean? (ASM, SFR, MMIO)

ASseMbly, Special Function Register and Memory Mapped Input/Output

ASM means assembly language.
A Special Function Register is something like DDRB.
Memory Mapped IO is a way of interacting with peripherals by reading from and writing to locations in the normal memory address space.

Under what circumstances is __ASSEMBLER__ defined, and where (in which file)?

It is defined by the compiler when you are compiling an assembly file.

Why can't we simply write #define cli(reg,bit) (reg &= ~(1 << bit) and #define sbi(reg,bit) (reg |= (1 << bit))?

Because reg is just an address. You need to convert that into a variable in memory that you can reliably access (hence the volatile). Further to that, not all chips use MMIO for all peripherals - some can be accessed by more efficient IO instructions. That said, in many cases yes you can just use simpler code. After all, things like DDRB |= 0x04 works fine. It all depends on how the value to pass as reg is defined originally. By forcing a specific volatile cast you can ensure that whatever way it was defined (with or without volatile, etc) it will work.

Thanks for the quick answer. I’m realizing I forgot the * before reg, it’s a stupid copy-paste error. I’ll add it to the question (the edit will influence only the last part of your answer)

On Atmel (now Microchip) AVR microcontrollers, the sbi, cbi, sbis, and sbic assembly language instructions can only address the 32 IO ports at addresses between 0x20 and 0x3f. The Atmega168 and 328 (used in Arduinos prior to the Leonardo) has WAY more than 32 IO registers, so only a subset of them can be addressed by sbi and cbi (the AVR instruction set was nailed down YEARS ago, when 32 IO registers seemed like more than enough).
As a result, operations that set or clear a single bit in those 32 IO registers can be performed by a single instruction which executes in two clock cycles, but the same operations on the remaining IO registers require a full-blown load-operate-store sequence that takes at least three cycles to execute.
From what I recall, AVRlibC had multiple macros that did almost the same thing, but had different use cases:

One would compile to the fastest and most efficient instruction(s) available for that particular IO address.
One would always compile to sbi/cbi, and would throw a compiler error if you tried to access a register outside of 0x20-0x3f
One would ALWAYS compile to the load-act-store sequence, without regard to whether or not it could have used sbi/cbi instead.
One would always compile to the load-act-store sequence, but would throw a compiler error if you tried using it on an address between 0x20 and 0x3f.

Basically, the choice enabled you to decide between optimized (but variable) performance, uniformly-slow (but deterministic) execution time, or the fastest-possible (but deterministic-at-compile-time) variant [which required that the programmer be aware of whether the register in question was within or above 0x20-0x3f].

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

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


text:
How to change the I2C address of the AS5048B?
I saw this video from James Bruton. See the links to the GitHub repos in the video description.
I bought a few AS5048B boards from AMS, so I can measure the position of my stepper motors.
In the sosandroid repo, I ran program_address and was able to get one of them working, but they all have the same I2C address, and because I want to have 6 of them running simultaneously, it of course won't work. I know I could get an I2C multiplexer...
I also tried setting the A1 and A2 pins on the AS5048B to high and low, which change the I2C address (for a total of 4)... But I want to change the I2C address permanently for each board.
It looks to me like program_address is supposed to permanently program the I2C address, which the user can specify in the .ino file:
// Construct our AS5048B object with an I2C address of 0x40
AMS_AS5048B mysensor(0x40);

But no matter what I set it to (e.g. 0x40, 0x41, 0x42, 0x43, 0x44), the Arduino I2C scanner always finds 0x44, which is the default address, so the program_address must not be working.
EDIT: the default address is actually 0x40. I must have programmed it to 0x44 without knowing (I was playing around with this board trying to figure this all out).
I know that normally the I2C addresses cannot be changed, but it looks like this one can:
Here's a snippet from the link above. It says the OTP bits can be programmed/burned (only once!). My understanding is that the I2C address is saved in the OTP bits.

Program the OTP bits permanently:

Write dec.253 into the OTP control register (dec.3) to enable the special programming mode
Set the Burn bit (dec.8) in the OTP control register (dec.3) to enable automatic programming procedure
Write dec.0 into the OTP control register (dec.3) to disable the special programming mode

I am using the Teensy 4.1 using PlatformIO in VS Code, and I also tried using an Arduino Uno in the Arduino IDE.
My wiring is as follows:

So how do I program the I2C address on the AS5048B boards?
EDIT:

I changed an image to text, and cleaned things up.

As @6v6gt requested, I used the I2C scanner and it is still showing 0x40 (on this particular board), so it must not have been programmed (unless it's possible to program it to 0x40 even though 0x40 is its default value). The only thing I changed from the program_address repo is this line in the .ino file:
// Construct our AS5048B object with an I2C address of 0x40
AMS_AS5048B mysensor(0x48);

I changed the 0x40 to 0x48. But now I am getting this in the serial monitor:
Angle degree : I2C error: 2
359.9780273437

Since I must have programmed the other board to 0x44 successfully, I am trying to think of what I did differently, but I don't remember.
There are hundreds of lines of code in program_address (and the .h and .cpp file), so I probably shouldn't post all of it here. But here's the GitHub repo.

Or is this whole OTP bit programming only meant for the manufacturer, thus it has already been burned and I cannot change it, meaning I would have to resort to using the A1 and A2 pins? If this is the case, it would only allow 4 addresses, but I need 6, which means I would need a second I2C bus (which the Teensy 4.1 can do), but I don't know how to do that, or if the library supports it. I'm only 19 years old and don't have a lot of experience with this.

To whoever down voted my OP, please explain why

I don’t know why someone would downvote you; you posed a very thorough well-researched question.

probably for posting pictures of text, instead of posting the text  ... makes it difficult for visually impaired people to read the post

Don't worry about downvotes. I'm a moderator and my answers get downvoted! It goes with the territory. Some people enjoy making downvotes. :)

To me, it looks like the default address is 0x40 (assuming the 2 hardware pins are unset) so I can't understand why you are seeing 0x44. Show the command(s) which you used to put the MSBs of your desired address in register 0x15. Did you invert the MSB as is shown in the linked product document ?

@6v6gt Yes, it looks to me like the default address is 0x40. I think the OP programmed a new I2C address of 0x44 by using the example.

@jsotola I get that but a downvote because of that without an explanation isn't going to help anyone. I'd tend to complain about pictures of text rather than downvote because of them. I'm happy to downvote truly crappy questions though.

Thanks. I'll be more careful to paste in the text instead of an image

read here https://arduino.stackexchange.com/questions/69654/mcp4725-i2c-address/69658#69658

There is no obligation to provide a reason for a downvote, however it is courteous to do so, if the reason isn't blindingly obvious. Your question was very detailed, the sort of question we like to receive. Good questions tend to get good answers. :)

The device slave I2C address consists of the hardware setting on pins A1, A2 and upper MSBs programmable by the user. It is the setting of the MSBs, in addition to A1/A2 that I believe the OP is after.
The information provided by @Nick Gammon concerning A1 and A2 is correct, but does not consider the other 5 bits (the MSBs). It appears that you can, indeed, permanently set a new I2C slave address on the device.
You need to read the programming application note very carefully, but they explain how to burn those bits into the register....it seems straightforward and is really just four steps, but I suppose it can be a little daunting, e.g.,
"slave address consist of 5 programable bits (MSBs) and the hardware setting of Pins A1 and A2 I²C address <4> is by default not programmed and due
to the inversion defined as '1'"
The application note gives an example of the 4 steps....

It may be the case that you already changed the I2C address default to 0x44 by following the instructions. [edited to add] Can you post the complete program [Arduino IDE code] that you used to try to change the I2C address?

Good point about already having reprogrammed them. I uploaded the I2C scanner scetch and connected a new AS5048B and it said 0x40. So I tried programming 0x41, then uploaded the I2C scanner and it said "Angle degree : I2C error : 2

As I mentioned, if you post the code (preferring the Arduino IDE code that you mentioned), I am confident that we (if not me, someone else here) can figure out what is going on. More than likely, you are doing some inadvertent writes to that register and locking them in or something like that.

Alright, I'll do that when I get home tonight (9 hours from now)

@JohnDoe ". . .So I tried programming 0x41,". It is not possible to set the device to address 0x41 if you also want to avoid using the address pins A1 and A2. 0x41 can only be achieved by leaving the device with the default configuration "0x40" but then pulling A1 high. You could have the following I2C addresses without using A1 and A2: 0x40, 0x44, 0x48, 0x4C, 0x50 and 0x54 etc. Having said that, my own preference would be to keep four of the devices as 0x40 (default) and change two to 0x44 then make use of A1 and A2.

"It is not possible to set the device to address 0x41 if you also want to avoid using the address pins A1 and A2..."   Thanks! I didn't know that. What are the limitations to these address names? Can I just make them up, like can I do 0x51 even though you didn't list it.

Using a AS5048B with an address that was still 0x40, I tried programming the address to 0x48, but the serial monitor says "Angle degree : I2C error: 2". Is it possible to program it to burn the OTP bits to 0x40? I wonder if I did that by accident? I wish there was an easy way to tell if they have been burned already

The error message indicates the subsequent command that you entered failed to address the device with its correct  (possibly changed by the previous command ) I2C address. Check with the I2C scanner what address it shows (probably/hopefully still 0x40). Please show anyway the sequence of commands you used in your attempt to change the address to 0x48 (and also the commands used in your previous, apparently successful, attempt to change the address of another chip to 0x44). Add this information at the end of your OP.

Thanks. I edited my OP.

I must admit I didn't read the datasheet in great detail when I answered. It is clever of them to allow programming the  MSB, because that would give you a big range of addresses. That makes sense for this type of application.

@JohnDoe This is the line in program_address.ino (from the sosandroid repository as in the OP) which changes the I2C address for the chip (assuming A1 and A2 are pulled low) from the default of 0x40 to 0x44 :  mysensor.addressRegW(0x01); changing it to mysensor.addressRegW(0x02); would appear to set the address of a new chip to 0x48. The code appears to follow the data sheet to make the internal changes to the device. I can't explain why you have received the error message from the "Angle degree" test. Were A1 and A2 low (thus ensuring that the new chip had the default address of 0x40) ?

Thanks! That makes more sense. I will try this when I'm done work today. This should solve it. Now I just want to know what the limitations are. Can I set addressRegW(0x99)? How does changing the addressRegW affect the address?

Nice! I programmed it to 0x48 successfully. Thanks! Now I would just like to know the answer to the question I asked above. Also, does the number have to be a positive integer?

but they all have the same I2C address

No, they have 4 possible addresses, based on how you configure A1 and A2. So you can have 4 different addresses immediately.

But I want to change the I2C address permanently for each board.

For each board, set up A1 and A2 differently.
This only gives you 4 different addresses, not 6. You could conceivably connect 8 devices to two different Atmega328 chips, and have them do the readings and forward the results using a protocol you devise, to your "main" board. The Atmega328 chips only cost around $US 5 each so this isn't a big deal.
Another approach would be to run SDA and SCL through a multiplexer chip, so that you enable one batch of 4 chips and then the other batch. Without trying it out, it is hard to say if this would work satisfactorily.


text:
How to tri-state an output circuit?
I need a circuit where an Arduino MCU can set an output to 3 different states.

HIGH (12V)
LOW (GND)
N/A (completely disconnected)

Using transistors seems to be the correct way but I am too much of a noob in this area to be sure.
I’ve been researching “tri-state” online but there seems to be different meanings of this.
I’d appreciate a circuit for this or information that can get me on the right track.
Update:
I did test this schematic and it almost works. Although in the high state I got 2.7V output when the input was 12V. Very odd. I used two NPN transistors.
This is a half h-bridge, right?

Have you tried googling for something like "tri state transistor circuit"? Found this site which seems promising.

Thank you, I will check that out!

In your schematic Q1 needs to be an PNP transistor, not NPN. And keep in mind, that you will loose a bit of the voltage on your diode.

Thank you, I will try this as well!

Q1 will work, it is in the emitter follower configuration. You will lose about 0.7V when fully on. That will be dissipated as heat. The emitter voltage will follow the base voltage but -0.7V lower referencing ground. You will also lose another 0.7V across the diode. If you put 5V on the  base you lost about 1.3V across the resistor, something is not correct.

Have you looked at 74Cxx buffers? Input is appears on the pin about the same as tri-state, you may be able to get by with two states.

The simplest solution could probably be an H-bridge, like the ones you
have on motor driver shields. Actually you only need half an H-bridge.
You will typically be driving two inputs of the chip: “input 1” and
“enable”:

if you set “enable” to LOW the bridge output will be in the high
impedance state (your “completely disconnected” state)
if you set “enable” to HIGH, the output will be HIGH or LOW,
mirroring “input 1”.

Edit: your transistor circuit looks slightly similar to half an
H-bridge. However, in order to operate from 12 V, you typically need at
least three transistors, one of them being a PNP. See for example this
discussion in the Arduino forum. I suggest you use a ready-built
H-bridge, as this will simplify things for you.

Another possibility is a tristate buffer with enable. There are lots available, just make sure the voltage can be 12 volts (eg MC14503B)

The MC14503B is not suitable: if supplied with 10 V, its inputs are only guaranteed to read HIGH if they are driven above 7 V. You have to find a tri-state buffer that can drive 12 V while being driven by 5 V logic. H-bridge chips are designed for this: they typically have dual supplies (one for the logic inputs, one for the driver outputs).

Thank you for your input Edgar!

Another option is to use a pair of opto-mosfets arranged as half bridge.
The opto's LEDs could easily be controlled by logic levels.
Another option is to use complementary pair of PNP and NPN transistors again arranges as half bridge (joined collectors as ouput, PNP emitter at +12V, NPN emitter at GND.
The NPN transistor is controlled directly; the PNP via an auxiliary small NPN (collector driving the PNP base)

Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.


text:
Ethernet library compilation error
I'm trying to connect my Arduino to the internet, but my Ethernet connection config code fails when I try to verify it, and I'm not sure why.
I'm using an Ethernet shield and have installed the Ethernet library v.2.0.0.
This is the running code:
WANStatus initialiseWAN() {
  // Enter a MAC address for your controller below.
  // Newer Ethernet shields have a MAC address printed on a sticker on the shield
  byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
  WANStatus res;

  Serial.println("[INFO]: Initialising WAN");
  // Try to initialise Ethernet connecion

  if (Ethernet.begin(mac) == 0) {
    res.error = true;
    res.retry = true;

    if (Ethernet.hardwareStatus() == EthernetNoHardware) {
      res.message = "Ethernet shield was not found";
      Serial.print("[ERROR]: "); Serial.println(res.message);
      return res;
    }

    // If all component are present try assigning a static IP address
    IPAddress ip(192, 168, 0, 177);
    IPAddress myDns(192, 168, 0, 1);
    Ethernet.begin(mac, ip, myDns)
    Serial.print("[INFO]: Assigned static IP: "); Serial.println(Ethernet.localIP());

    if (Ethernet.linkStatus() == LinkOFF) {
      res.message = "Ethernet cable is not connected";
      Serial.print("[ERROR]: "); Serial.println(res.message);
      return res;
    }
    if (Ethernet.linkStatus() == Unknown) {
      res.message = "Ethernet link status is 'Unknown' check the cable";
      Serial.print("[ERROR]: "); Serial.println(res.message);
      return res;
    }

    // Static IP assigned
    res.error = false;
    res.retry = false;
    res.message = "Static IP Address";
    return res;
  } else {
    // Received IP address from DHCP
    Serial.print("[INFO]: Received DHCP IP: "); Serial.println(Ethernet.localIP());
    res.error = false;
    res.retry = false;
    res.message = "DHCP IP Address";
    return res;
  }

  // ToDo: check WiFi modules here

}

And the error message:

[Starting] Verifying sketch 'controller\controller.ino'
[Warning] Output path is not specified. Unable to reuse previously compiled files. Build will be slower. See README.
Loading configuration...
Initialising packages...
Preparing boards...
Verifying...
In file included from C:\Program Files (x86)\Arduino\libraries\Ethernet\src\Dns.cpp:8:0:
C:\Program Files (x86)\Arduino\libraries\Ethernet\src\Dns.cpp: In member function 'uint16_t DNSClient::BuildRequest(const char*)':
C:\Program Files (x86)\Arduino\libraries\Ethernet\src\utility/w5100.h:457:25: warning: result of '(256 << 8)' requires 18 bits to represent, but 'int' only has 16 bits [-Wshift-overflow=]
#define htons(x) ( (((x)<<8)&0xFF00) | (((x)>>8)&0xFF) )
                      ~~~^~~
C:\Program Files (x86)\Arduino\libraries\Ethernet\src\Dns.cpp:164:18: note: in expansion of macro 'htons'
twoByteBuffer = htons(QUERY_FLAG | OPCODE_STANDARD_QUERY | RECURSION_DESIRED_FLAG);
^~~~~
Sketch uses 22574 bytes (69%) of program storage space. Maximum is 32256 bytes.
Global variables use 1467 bytes (71%) of dynamic memory, leaving 581 bytes for local variables. Maximum is 2048 bytes.
IntelliSense configuration already up to date. To manually rebuild your IntelliSense configuration run "Ctrl+Alt+I"
[Done] Verifying sketch 'controller\controller.ino'

Everything is alright. There is no compiler error and your sketch is ready to upload.
The compiler warning "result of '(256 << 8)' requires 18 bits to represent, but 'int' only has 16 bits" from the Ethernet library source code is nothing you have to worry about.

the warning is fixed in Ethernet 2.0.1 released Jul 6, 2022


text:
IDE / Plugin / Compiler / Language: Which combination is closest to best-practice embedded development in C or C++?
Currently I'm pretty far out to sea with a combination of Visual Studio Code, the Platform.io extension, while writing new code in C++ using avr-gcc.
I'm hoping for a combination that would offer the most crossover educational value, in the event that I potentially experiment (if only to prove the Arduino platform's superiority to any doubters) with non-Arduino-specific embedded development.
The default IDE seemed to present me with less information about the remarkably sound underpinnings and marvelous overall artistry with which they've woven the many different design techniques and languages together. I'm mainly curious about other (inferior to Arduino, mind you), more widely used combinations / tool chains in the world of embedded programming.

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

A great deal of what you learn with any comprehensive IDE will transfer to another one, if you need to. The IDEs that come to mind are Eclipse (listed first, only because it is my personal choice and has a broad range of application), Visual Studio, and others I have no experience with.
The Arduino IDE is as limited as you found it, primarily because it was written as (1) a learning tool for (2) AVR-based Arduinos, and goes to some lengths to offer an easier entry into embedded systems programming for non-programmer hobbyists. To that end, it achieves its goal very well. But as you have observed, you quickly run into its limitations, especially when your goal is to branch out onto other processors and other tool-sets.
Once someone is over the hump of basic programming and debugging, more advanced tools like a full-on IDE take most of those limitations out of your way, at the cost of less hand-holding, but by that time, you presumably need the freedom much more than the help!
I don't want to outright tell you "You need to use FiddleFoo 18.4 or you'll never get anywhere" - one (or a couple) of the industrial strength IDEs will appeal to your view of programming and your personal work-style. Try a few of them, paying attention to what toolsets and processors each one can target with OEM or third-party support, for the processors you think you might become interested in. It's quite likely T-H-E right IDE for you will stand out from the rest.
Update:
Eclipse will need a plug-in to target Arduino and other embedded system boards. The one I use - and the only one being maintained AFAIK - is Sloeber by Jan Baeyens, who occasionally posts here as jantje. It is pretty comprehensive, including the ability to write and import new board descriptors.
Memory limitations come with the hardware, and while compiler advances can help this out, it's pretty much governed by the numbers. An Arduino Uno still has only 2K of RAM and 32K of Flash minus whatever the bootloader uses (if you choose to use a bootloader). Heap is still problematic for all the usual reasons - fragmentation of free memory (positioned, as it is, between static area and the bottom of the stack), and reduction of available stack and/or data space. There are, of course, more embedded boards available, with larger memories, but that just helps you put off the inevitable. I view the use of heap in an embedded system as a reliability issue even more than as a memory limitation; it is all too easy for fragmentation and memory leaks to eventually take down your system, and a Blue Screen Of Death is a big no-no in embedded systems.

I appreciate the input, JRobert. It's been some years since I used Eclipse, and the only reason I stopped then was due to insufficient RAM, which shouldn't be an issue these days. I take it there isn't any plug-in / extension required? Also, since posting the original question last night I was able to find an older, but interesting, discussion concerning language use and memory limitations of various boards. Have these last five years changed that consensus (avoid the heap, C is best) with the increases in available onboard memory?


text:
Switch loops with SPDT switch
I have made a drone/car quadruped robot thing and I need help with the code. I have found two codes to use to control each aspect of it but I need help to connect them. I have made a radio controller with a Xbee 3 Pro that has a spdt (two position switch) and I want to use it to switch the modes. I want the car to be LOW and the drone to be HIGH (If it helps the switch is on pin digital pin 9 of a Arduino Nano). I am a beginner at the coding aspect of the project and I would appreciate all the help I can get.

https://www.youtube.com/watch?v=enT-O4NwCzc

please add your code to the post

There is no need for a SPDT switch. A SPST works just as well.
If you have a SPDT switch with 3 positions (pole 1 closed, open, pole 2 closed) you can use it to activate one pin or the other, or neither.
Let's pretend your switch is an SPST. Ignore one of the poles (pole 2, say.)
Connect a digital pin to pole 1. connect the common (center) pin to ground.
Set your digital pin to INPUT_PULLUP. Now, when the pin is LOW, the switch is closed (mode A). When the pin is HIGH, the switch is open (mode B).

Thank you I just checked back in and this is very helpful. Do I need a resistor like as if it were a pushbutton

If you use INPUT_PULLUP mode then the Arduino connects the pin to +5V through an internal restistor, so you don't need an external resistor. That is true for pushbuttons as well. (However, when you use  INPUT_PULLUP, the pin reads HIGH when the switch is open, and goes LOW when the switch is closed.)


text:
Motor keeps spinning crazily after UNO board reset
I'm using a NEMA 17 stepper motor with A4988 motor driver and Arduino Uno board. I have used full microstepping (1/16th, so one revolution = 3200 steps).
I'm coming across this strange problem. Whenever I upload any code, for example
void loop()
{  delay(20);
   digitalWrite(stepPin, HIGH);
   delayMicroseconds(100);
   digitalWrite(stepPin, LOW);
   delayMicroseconds(100);
}

the motor spins rapidly for about 1000 steps clockwise (before "avrdude done. Thank you." appears), and then executes the code. When a similar code is placed in void steup() with an empty void loop (), the same thing happens - motor spins rapidly, executes what's written and then stops. The initial rapid spinning is always the same speed and direction, no matter what code is uploaded.
When I upload empty code -
void setup() {}
void loop() {}

the motor continuously spins rapidly with the same speed, same direction. If I add a delay(1000) anywhere in the above program, same thing happens. When I long/short press the reset button on the board, same thing happens. When I upload programs unrelated to the motor, like the example Blink program, same thing happens. Buddy of mine told me to upload the eeprom_clear program from Examples, same thing happened.
I tried uploading this program -
void setup(){
for (int i=0; i<=13; i++)
  {pinMode(i,OUTPUT);
  digitalWrite(i,LOW);

  }

}
void loop(){}

and motor spun like crazy while uploading (same ~1000 steps, clockwise direction) and then stopped. Uploading any program after this has same behaviour. If it an empty/delay only program, motor spins crazily forever. If it is a specific program (example - run for 1000 steps), it spins crazily while uploading, executes the main program, then stops.
As I'm typing this, the motor is spinning like a crazed maniac even though I just uploaded an empty void setup() {} void loop() {} program.
I've tried changing the computer that the Arduino is connected to, I've changed the motor driver and plugged in a brand new one, I've changed the USB cable, I've changed the motor and I've reset all Arduino and breadboard connections. I went to Device Manager > Ports (COM & LPT) > USB-SERIAL CH340(COM5) and updated driver. Current Arduino IDE is Arduino 1.8.10 on Windows 10.
No change in outcome. This problem has been spoiling my sleep for the past few nights as I can't upload anything to the board without the Arduino either spinning crazily endlessly or spinning crazily just while uploading and then behaving properly.
Any solutions? Thanks a lot!
Edit - Added schematic of the electronics connections. Original image from www.lastminuteengineers.com

How do you have it connected to the Arduino?  You aren’t using pins 0 or 1 are you?

Maybe the pins are floating during programming and the motor driver sees this as valid input? An exact schematic would help.

Pins 9,10,11 are for microstepping (all HIGH for 1/16 stepping). Pin 2 for direction, pin 3 for Step mode. Also using 5V pin and GND pin from the POWER section of the Arduino Uno board, connected to the appropriate pins of A4988 motor driver.

@MaximilianGerhardt - I've added the schematic of the connections.

Most pins are floating while programming. Do some pull-up or pull-down resistors help?

You should try to use the EN (enable) pin of the motor driver. The driver is only active when EN is low. You should connect EN to a digital I/O of the microcontroller, and add a pull-up resistor (e.g. 10K) to +5V on the line. In the sketch then pull the EN line low. This should protect against "I/O line is floating", if that is the problem.

@thebusybee Can you explain in more detail? What resistors do you want me to use and where?

So you don't know what a pull-up/down resistor is, do you? Then please show some effort and learn that. See @MaximilianGerhardt's comment: one end of the resistor belongs on the connection that will float otherwise, the other end connects to VCC for pull-up or GND for pull-down. The value depends on the input impedance of the circuit to be controlled; in your case the motor driver. As a rule of thumb make it 1/10 of that input impedance.


text:
where to get Arduino WIFO101 library that supports WiFi.beginAP() on board MKR1000
The sketch example from page "Wifi.beginAP()" causes compiler error because the return values are not defined for -WL_AP_LISTENING or -WL_CONNECT_FAILED.
Board: Arduino MKR1000 WiFi
Compiler:  Arduino IDE
Library: Github WiFi101 v0.9.1
Missing:  definition of "WL_AP_LISTENING" and "WL_CONNECT_FAILED"
ERROR....
beginAP.ino: In function 'void setup()':
beginAP:55: error: 'WL_AP_LISTENING' was not declared in this scope
if (status != WL_AP_LISTENING) {

              ^

Arduino WiFi101-MKS1000 examples\beginAP\beginAP.ino: In function 'void loop()':
beginAP:78: error: 'WL_AP_CONNECTED' was not declared in this scope
  if (status == WL_AP_CONNECTED) {

                ^

exit status 1
'WL_AP_LISTENING' was not declared in this scope

It is AP_SimpleWebServer.ino at Github Wifi101 release 0.9.1 examples.
It builds ok by using the old definitions for .beginAP return values.
Problem is Arduino .beginAP page has example that relies on the LATEST Github WiFi101 ("0.9.1++" not released yet).
Also example AP_SimpleWebServer is missing from Arduino Wifi101 page.


text:
ESP8266 - AT Command for Network Requiring Username AND Password
I have been using my ESP8266 module with my Arduino on my university's Wi-Fi network, which only requires a password to log on to.
The university will soon terminate that Wi-Fi network and replace it with one that requires a username and password to log on.
What would that AT command be to connect to such a network?
Edit: I have since found out that the university has changed the network so that a user can "connect" to the network and then enter their university id/password in a captive portal to gain internet access (and perhaps other features of the network). Also, I have since learned how to overwrite the firmware on my esp-01 so that I no longer need to use the AT commands -- in fact, I can program it in the Arduino IDE just as I would with another esp8266-based device, such as the NodeMCU.

sounds like you'll need WPA2/Enterprise - read this and this - though I'm not sure if the latest AT firmware has any support - but I haven't read those links too much

Get a wifi router, and make a local "development" network. (If you don't need internet on the ESP8266)

We can't tell without more information but it sounds rather like you will need a [WiFi_SSID, WiFi_PASSWORD] pair for the ESP to connect to the WiFi, and a [Network_USERNAME, Network_USERPASSWORD] pair for their network to let you use the network (as if you were logging onto it by hand from a terminal).
If so, you'd provide the first pair as you do now, with the AT+CWJAP... command, to get your device connected to the WiFi. For the second pair, your Arduino will probably need to interact with a user logon screen to provide the second pair. You'll need to get those details from the school's IT department, and possibly mimic a terminal.
Update:
As above, you need to find out whether the network requires 2 sets of credentials - the SSID and WPA2 key and network username and password. If it requires the latter, then your ESP can get you onto the WiFi but your Arduino will then have to mimic a user sitting at a terminal - read the network ID and Password challenges and provide the appropriate responses. Without know that, you can't know how to write the login code, nor can we. It sounds as if there are people on site who have already done what you're trying to do. They and their experience can be far more helpful than we, who have no knowledge of the school network.

The network will be WPA2 secured. When logging on with my Windows 10 PC, I am prompted to enter credentials in a web browser. When using the ESP8266, might I need to send an HTTP request to the AP containing login credentials?

That seems at least possible.  We really don't know enough yet to do more than guess.

I'm using an ESP-01, interfacing with it using softser. The network is WPA2 secured, which is supported by the ESP8266. I will have to connect to Eduroam to use the network.

I did not understand the changes to the network at the time. To the best of my knowledge, the network is WPA2 secured. To gain internet access, users must now enter credentials in a captive portal. I don't know how, but others at my school have been able to navigate this using  a NodeMCU programmed in the Arduino IDE.

If you are using Arduino+ESP8266 version 1(ESP-01)module. You can connect ESP module to the internet, using AT commands as follows:
Normally, AT+CWJAP="ssid","password"
If your Internet requires ssid, username and passowrd(usually in universities- eduroam) then
1) Connect to eduroam or university wifi using ssid, username and password from
   your laptop.
2) Install Connectify Hotspot software in your laptop.
3) Open "Connectify Hotspot" application and open settings tab, then create
   wifi-hotspot.
4) Give eduroam(or your wifi)-->"Internet to share" field , Give your own
   Hotspot name and password. Then click on "start Hotspot" button.
5) Now your esp01 module can detect this new hotspot using AT+CWLAP. Connect to
   it using AT+CWJAP="HOtspot ssid","HOtspot password".
This way you can overcome the problem of extra Authentication.
Hope it helped. Enjoy Programming.


text:
Can I power an NodeMCU trough VIN providing 5v
I have a spb 8266 board, an ESP-12E NodeMCU.
I broke my micro USB.
There's this piece of information but my case is unclear:
Can I use the micro usb's 5v to power the board through the VIN or do any solution require more equipment than that ?
(The board only has 3.3V and no 5V)

Can I use the micro usb's 5v to power the board through the VIN or do any solution require more equipment than that ?

Yes. That is the pin's purpose.  You can use any voltage from about 4.5V up to 20V, although higher voltages will cause more heat from the on-board 3.3V regulator.
VIN just connects to the 5V of the USB.

through a diode... On many (all?) ch340g-based nodeMCU, that pin does does something else, I'm not sure what, but it reads about 1.6v when powered by USB, which means we can't use it to power a sensor.

Stove have a diode on that pin, stone have it on the usb power. Without knowing exactly what model and who made it is impossible to know.

If you are working with the "v3" (Lolin) pcb, USB v5 pin is not directly connected to Vin, but to VU. Vin has a S4 SMD diode (aka Schottky 40V1A 1N5819) between it and the USB v5 pin.


text:
esp8266 not getting programmed
I am working on an esp8266 and I am connecting it with Arduino Uno. I have programmed the Arduino but when I write AT command on the serial monitor it doesn't show anything.The connections which i have made are:
tx uno - rx esp
rx uno - tx esp
gnd uno -gnd esp
vcc and ch_pd - 3.3v supply

I am using an external supply and not the 3.3v from the Arduino.
I need help with this.

And how exactly do you think the ESP8266 is connected to the USB-UART bridge?

It is connected via the connections which i have mentioned.

No, it isn't. It is connected backwards.

what do u mean by backwards?

You have RX of the bridge connected to RX of the device, and the same with TX.

While it is true that the TX/RX are running at 5V, I have been playing around with it without issue (so far!). But yes, connect the RX to RX and TX to TX. I got mine working. Also check the baud rate. I was convinced mine was running at 9600, but then it worked at 115200...

I have connected RX to TX and it is working.There was a problem in my wifi module.I changed it and now it is working.

Be careful, you could fry your ESP like that.  You need to get the signal lines down to 3.3V, not the 5V used by the Arduino Uno.  There are many ways to do this, from voltage dividers, to transistors, or you can use a 3.3v Arduino Pro Micro.  I would also recommend starting out with just a 3.3v FTDI board, and interface that directly to the ESP to remove the Arduino and its code from the picture.
I would also make sure that your grounds on the external supply and the Arduino are tied together, or just power the ESP from the 3.3v out of the Arduino.
Other than that, double check your baud rate, some come shipped at 9600, some at 115200, and i'm sure that there are others out there too shipping at different baud rates.

Sorry if these are stupid questions but these are the things I would check.

Why are you connecting to an Arduino, why not connect directly to the
HOST and use a terminal emulator program?
What ESP8266 are you using?
Are you connecting the Vcc connector of the ESP8266 to 3.3v?
I think you need to pull the RST pin high to enable normal running,
is it high?


text:
How to randomize the delay in Arduino Stepper code?
How does one add a random DELAY between 10 and 20 seconds?
For example in the following stepper logic I have a delay of 11 seconds - expressed in milliseconds as: delay(11000).
What would I need to add (or modify) so this is randomized between 10 and 20 seconds?
//#define IN1  8
//#define IN2  9
//#define IN3  10
//#define IN4  11

int Steps = 0;
boolean Direction = true;
unsigned long last_time;
unsigned long currentMillis ;
int steps_left=4095;
long time;

void setup()
{
Serial.begin(115200);
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
pinMode(IN3, OUTPUT);
pinMode(IN4, OUTPUT);

}
void loop()
{
  while(steps_left>0){
  currentMillis = micros();
  if(currentMillis-last_time>=1000){
  stepper(1);
  time=time+micros()-last_time;
  last_time=micros();
  steps_left--;
  }
  }
   Serial.println(time);
  Serial.println("Wait...!");
  delay(11000);                     // delay timing
  Direction=!Direction;
  steps_left=4095;
}

Forgive the appearance of the code.  Everytime I post it gets butchered.  Hopefully it's understandable.

https://www.arduino.cc/reference/en/language/functions/random-numbers/random/

In setup(), add
randomSeed(analogRead(0));

This reads the value of an analog input pin, which if not connected, will float to relatively random values between 0 and 1023. This "seeds" the random number generator so the pattern of random numbers you will get later doesn't always give the same results each time you start the sketch.
In your delay() call, just replace the fixed value with a call to the random(min, max) function, as:
delay(random(10000, 20000));

But during debug, consider using a constant seed so you can make repeatable results or inspect the result of a single change.

Hey thanks so much you guys.  Much appreciated.  I'm learning as I go and this is a big help!


text:
Wiring multiple LCD displays to Arduino
I have multiple LCD displays and one Arduino and I just want to show some text on each display separately.

Is it possible to Wiring multiple LCD Displays for the single Arduino board?
Or maximum how many display can I connect one single Arduino?

For HD44780 based displays all the data, register select and read/write pins can be shared. A display only exists at the moment the E pin is toggled. They are designed to share a microprocessor's data bus.
So if you have 50 displays then you can (theoretically, see "fan out" below) run them from 50 "E" pins plus 6 (or 10 depending on if you want to run in 4 or 8 bit mode) shared pins.
Here's an example with 2 displays in 4-bit mode - just replicate for more:

simulate this circuit – Schematic created using CircuitLab
Note: power, ground and contrast connections omitted for brevity.
As you can see the LCDs share all their pins except the E pin. A third display will connect to the same pins, except its E pin would be unique.
Fan out
Fan out is an important concept in digital electronics. An IO pin can only deliver a certain amount of current and each device a pin connects to adds "load" to that pin. Too many devices and the IO pin will struggle to control the devices properly.
To combat this a "bus transceiver" (such as the 74HC245) is commonly used. If one IO pin is capable of driving, for the sake of argument, 5 devices, and one bus transceiver is also capable of driving 5 devices then the IO pin could drive 5 bus transceivers giving you control over a potential 25 devices.


text:
Impossible to install the esp_camera library
I cannot install the esp_camera library. When I try to add the .zip, I get "does not contain a valid library.
Everything about this ESP-32 Cam seems to rely on that library, and I can't find a way to install from https://github.com/espressif/esp32-camera or any other way.
Thanks.

It's not a "library" in the way that the Arduino system uses the term. That is, it's not designed to be placed under <sketchbook>/libraries directory way typical Arduino libraries are.
The good news is that you don't need to install it, because you already have it. It comes as part of the SDK files packaged into the ESP32 Arduino core as it is installed through the boards manager.
You'll find the header various places under the <arduino15>/packages/esp32/hardware/esp32/<version-number>/tools/sdk/esp32<architecture>/include/esp32-camera/driver/include/esp_camera.h where arduino15 refers to this, version refers to whatever version of the board package you have installed, and architecture is nothing, or c2, s3, or various other related esp32 suffixes.
The bulk of the code being in <arduino15>/packages/esp32/hardware/esp32/<version>/tools/sdk/esp32<architecture>/lib/libesp32-camera.a

Thank you. It took a bit of time to grasp the difference between platforms when still using Arduino IDE.


text:
Problems sending data to my Arduino from Python using pySerial
I'm trying to send a '1' or a '0' to my Arduino in Python using pySerial so that from my Arduino I can read whatever the Python program sends and then turn a relay on and off depending on what it reads from Python.
Here is the Python code:
import cv2
import imutils
import threading
import time
import serial

Arduino = serial.Serial("COM7")
Arduino.baudrate = 9600

cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)

_, start_frame = cap.read()
start_frame = imutils.resize(start_frame, width=500)
start_frame = cv2.cvtColor(start_frame, cv2.COLOR_BGR2GRAY)
start_frame = cv2.GaussianBlur(start_frame, (21, 21), 0)

alarm = False
alarmMode = False
alarmCounter = 0

def beep_alarm():
    global alarm
    for i in range(5):
        if not alarmMode:
            break
        print("HE MOVIN HE MOVIN")
        Arduino.write(str.encode("1"))
    alarm = False
    Arduino.write(str.encode("0"))

while True:
    _, frame = cap.read()
    frame = imutils.resize(frame, width=500)
    if alarmMode:
        frameBW = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        frameBW = cv2.GaussianBlur(frameBW, (5, 5), 0)

        difference = cv2.absdiff(frameBW, start_frame)
        threshhold = cv2.threshold(difference, 25, 255, cv2.THRESH_BINARY)[1]
        start_frame = frameBW

        if threshhold.sum() > 300:
            alarmCounter += 1
        else:
            if alarmCounter > 0:
                alarmCounter -= 1

        cv2.imshow("Cam", threshhold)
    else:
        cv2.imshow("Cam", frame)

    if alarmCounter > 20:
        if not alarm:
            alarm = True
            threading.Thread(target=beep_alarm).start()

    keypress = cv2.waitKey(30)
    if keypress == ord("t"):
        alarmMode = not alarmMode
        alarmCounter = 0
    if keypress == ord("q"):
        alarmMode = False
        break

cap.release()
cv2.destroyAllWindows()

It's basically a movement detection program. If it detects me moving it should send a '1' to the Arduino where it then turns on a relay.
Here is the arduino code:
int relay = 11;
bool moving = false;

void setup() {
  Serial.begin(9600);
  Serial.setTimeout(1);
  pinMode(relay,OUTPUT);
  digitalWrite(relay, LOW);
}
void loop() {
  while (Serial.available()) {
    if (Serial.read() > 0) {
      while (!Serial.available()) {
        if (moving == false) {
          digitalWrite(relay, LOW);
          delay(100);
          moving = true;
        } else {
          digitalWrite(relay, HIGH);
          delay(100);
          moving = false;
        }
      }
    }
    digitalWrite(relay,LOW);
    delay(100);
  }
}

are you able to send data successfully using serial monitor?

You didn't specify, what the problem actually is, but I already see an error, that is probably the problem here.
You are sending the string "0" or the string "1" from python. This being a string - in contrast to a number in some binary format - means, that it is encoded as ASCII text. Have a look at an ASCII table, for example here. You will find the symbol/character "0" to have a decimal value (DEC) of 48. "1" is decimal 49.
On the Arduino side you have Serial.read() > 0. Serial.read() returns an integer, so a decimal number (or more specific a binary representation of it). So you got either 48 > 0 or 49 > 0, which is always true. Keep in mind the difference between ASCII encoding and binary integer encoding.
You can replace the above with
if(Serial.read() == '1'){

This tests, if you received the character (ASCII encoded!) '1' (the single quotes are for characters).
Note: It seems you want to switching the relay on and off until another character is send. Currently you are switching the relay 10 times a second. That is much for a relay, especially, if you are switching high voltages (like mains power). You should be aware, that this might cause problems with your relay after some time.


text:
50 Hz powerline noise using Arduino and mikroe ECG 2 (ADS1194)
I am trying to take ECG measurements using the Mikroe ECG 2 (ADS1194), connected to an Arduino Uno via an Arduino Uno Click shield.
I am able to measure the ECG, and can read the heartbeats somehow in my channel3 data.
My code for the Arduino is derived from the Github repository.
byte dataReady_Pin = 2;
byte reset_pin = 17;
byte cs_pin = 10 ;

The pins seem to be set correctly, and I used the default settings from https://github.com/MikroElektronika/mikrosdk_click_v2/blob/master/clicks/ecg2/lib_ecg2/src/ecg2.c.
void setup() {
    Serial.begin(250000);
    //delay(3000);
    Serial.println("Starting...");
    if (adc.begin()) {
      Serial.println("ADC started");
      numberOfChannels = adc.getNumberOfChannels();
      if (verbosity) {
        Serial.print("ADS119X Conected") ;
        Serial.println("") ;
        displayRegs ();
        Serial.print("Num Channels: ") ;
        Serial.print(numberOfChannels) ;
        Serial.println();
      }
    } else {
      Serial.print("ADS119X not started") ;
    }

    // Config from https://github.com/MikroElektronika/mikrosdk_click_v2/blob/master/clicks/ecg2/lib_ecg2/src/ecg2.c example
    adc.WREG(ADS119X_ADD_CONFIG1, ADS119X_DRATE_250SPS);
    adc.WREG(ADS119X_ADD_CONFIG2,  0x20);
    adc.WREG(ADS119X_ADD_CONFIG3,  0x40 | 0x80 | 0x0C);
    adc.WREG(ADS119X_ADD_LOFF, 0xE0 | 0x10 | 0x03);

    adc.WREG(ADS119X_ADD_RLD_SENSP, 0x02 );
    adc.WREG(ADS119X_ADD_RLD_SENSN, 0x02 );

    adc.WREG(ADS119X_ADD_LOFF_SENSP, 0x05);
    adc.WREG(ADS119X_ADD_LOFF_SENSN, 0x02);
    adc.WREG(ADS119X_ADD_LOFF_FLIP, 0x00);

    // stop conversion
    adc.sendCommand(ADS119X_CMD_STOP);
    adc.sendCommand (ADS119X_CMD_SDATAC);

    adc.setChannelSettings(ADS119X_ADD_CH1SET, 0x00, ADS119X_CHnSET_GAIN_6, ADS119X_CHnSET_MUX_NORMAL);
    adc.setChannelSettings(ADS119X_ADD_CH2SET, 0x00, ADS119X_CHnSET_GAIN_6, ADS119X_CHnSET_MUX_NORMAL);
    adc.setChannelSettings(ADS119X_ADD_CH3SET, 0x00, ADS119X_CHnSET_GAIN_6, ADS119X_CHnSET_MUX_NORMAL);
    adc.setChannelSettings(ADS119X_ADD_CH4SET, 0x00, ADS119X_CHnSET_GAIN_6, ADS119X_CHnSET_MUX_NORMAL);

    adc.WREG(ADS119X_ADD_GPIO, 0x0F);

    ads119x_pace_detect_odd_channels_select(0x00);
    adc.WREG(ADS119X_ADD_CONFIG4, 0x02);

    adc.sendCommand(ADS119X_CMD_START);
    delay(100);
    adc.sendCommand(ADS119X_CMD_RDATAC);
    delay(100);
}

I tried to connect the Arduino to a battery (but still need the USB for reading out the data, because I do not have a display or anything), and unplug the laptop it is connected to from the powerline.
I am not an electrical engineer, so I am really running out of ideas on what I could to reduce this 50/100 Hz noise.
Here are the images of the measured signal and its frequency spectrum.
I would appreciate any ideas on what to try to fix this problem.
The electrodes I use are LA, RA, LL with good quality gel pins.
I can use a digital filter afterwards, but this does not seem like a satisfactory solution.

you are connecting the electrodes to a large antenna that picks up a lot of electrical noise ... your question is a better fit at https://electronics.stackexchange.com/questions

Log the data to a SD card, or use a radio connection (WiFi, Bluetooth, other), to get the data. Continue to run off a battery.

First of all, I would not recommend connecting electrodes to your body while the device is connected to a computer which is supplied by mains. You said you disconnected the computer from the powerline to reduce noise so that's good. But keep in mind your PC power supply is most possibly not of medical grade.
Using a battery is most possibly the best option as it offers a really low noise voltage source. When using a battery further regulation might not even be required apart from battery protection and some regulation to get a fixed voltage (instead of the decreasing battery voltage).
Using a 50Hz filter as recommended by Rohit works also great especially if you use some (digital) notch filter at 50Hz and 100Hz which offer really high attenuation close to those frequencies. The ECG bandwidth 0.1Hz-30Hz isn't affected much by those notch filters. If you are aiming for higher bandwidth noise will be an even bigger problem as the useful signal decreases with rising frequency.
When it comes to ECG there are multiple reasons for interference of the 50Hz and harmonics. The human body basically acts as an antenna which also picks up mains interference. Even though the ECG electrodes are placed at different positions on the body the interference is mostly common mode on all electrodes meaning it's equal and in phase on all electrodes. Assuming your ECG frontend would have infinite common mode rejection the common mode interference wouldn't matter at all but it’s not. There are multiple reasons for a low common mode rejection but since you are using some development kit I assume the design and layout is rather well done.
But even when you have a well-designed frontend the common mode rejection ratio (CMRR in the datasheet) is limited. That's why there is the driven right leg (DRL) which basically tries to attenuate the common mode interference by actively driving the body. So the question is do you actually use the DRL?
As Rudy suggested logging the data locally or using some wireless data connection would be best and also make sure you don't have that unwanted connection to a PC which is possibly connected to mains in some way. If you want to keep the USB connection, you could try to use some USB isolator which provides a galvanic isolation between the PC and the arduino. There are plenty of different USB isolators on the market for quite a big price range. I wouldn't buy the cheapest from Alibaba but that's up to you. When using a battery you only want the USB isolator to separate (optically isolate) the data connection and ground connection. Some USB isolator also supply an isolated 5V voltage on the slave side by using a small transformer but when using a battery you don't need that.

You are trying to measure very small signals.   Mains noise is everywhere around you.  It is picked up by leads.  It is also transmitted from the power supply.  Standard power supplies are not designed to be medical grade, they are quick and dirty designs.
There are a few ways to improve it.  You may have to try more than one solution.

Use a battery as power source
Design a better power supply, perhaps a switching power supply with good filtering
Use ferrite rings on all leads
Use a digital filter to remove the 50Hz.

There is nothing unsatisfactory about the digital filter, but I would personally try to reduce the noise in the first place (as well).


text:
Get 3-inch e-Paper working on a Nano
Please help!
I purchased a 3-inch e-Paper Display from Waveshare, which appeared to suit my project well. The exemplary little code to show an image was easy to set up and to demonstrate functionality:
#include <SPI.h>
#include "epd3in0g.h"
#include "imagedata.h"

Epd epd;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.print("e-Paper init ");
  if (epd.Init() != 0) {
      Serial.print("e-Paper init failed");
      return;
  }

  Serial.print("White \r\n");
  epd.Clear(white);
  delay(2000);

  epd.Init();
  Serial.print("Image \r\n");
  epd.Display(IMAGE_DATA);
  delay(2000);

  epd.Init();
  Serial.print("Small Image \r\n");
  epd.Display_part(IMAGE_DATA, 0 ,0, 168, 400);
  delay(2000);

  epd.Init();
  Serial.print("Clear...\r\n");
  epd.Clear(white);
  delay(2000);

  Serial.print("Goto Sleep...\r\n");
  epd.Sleep();
}

void loop() {

}

I will not just have images displayed, I aim for strings with text and numbers and those partial refreshed. Wild guesses if a
epd.Display_Text('''Hello World''');

might work is pointless. Thus, the existence and usage of possible commands for the epd. appears to me not well documented (or I was unable to find something even after a thoroughly search).
I had a look at other examples using GxEPD libraries and it seemed as a good starting point for me.
Within the GxEPD2 Library it seems a class for 3-inch EPD is missing as it is nowhere declared (I assume there should be something like a GxEPD_300 to set display dimensions etc.).
So, I reckon I need to wrap up something to meet the specs of the 400x168 pixel display but I don't know where to start.
I tried around with the GxEPD_MinimumExample.ino, like

replacing the display specific lib with the epd3in0g.h from the example
adjusted the right pins according to the Waveshare Wiki

// GxEPD_MinimumExample by Jean-Marc Zingg

#include <GxEPD.h>

// select the display class to use, only one, copy from GxEPD_Example
//#include <GxGDEH0154D67/GxGDEH0154D67.h>  // 1.54" b/w -> from org. example.
#include "epd3in0g.h" //my 3-inch display

#include <GxIO/GxIO_SPI/GxIO_SPI.h>
#include <GxIO/GxIO.h>

// constructor for AVR Arduino, copy from GxEPD_Example else
GxIO_Class io(SPI, /*CS=*/ 10, /*DC=*/ 9, /*RST=*/ 8); // arbitrary selection of 8, 9 selected for default of GxEPD_Class
GxEPD_Class display(io, /*RST=*/ 8, /*BUSY=*/ 7); // default selection of (9), 7

void setup()
{
  display.init();
  display.eraseDisplay();
  // comment out next line to have no or minimal Adafruit_GFX code
  display.drawPaged(drawHelloWorld); // version for AVR using paged drawing, works also on other processors
}

void drawHelloWorld()
{
  display.setTextColor(GxEPD_BLACK);
  display.print("Hello World!");
}

void loop() {};

During the verification prior the upload I get errors pointing back to the libs:
error: 'GxEPD_Class' does not name a type; did you mean 'GxIO_Class'?*

I assume this is because the call to initiate the display is not working.
Thank you for any advice!

have you ran HelloWorld example?

Thank you @jsotola for getting back to me. I edited my question in the hope of clearing thins up. It is now shown at which point the HelloWorld example got stuck (probably due to my modifications).

Waveshare examples, by and large, suck. They're usually a bunch of register writes, undocumented. I had to write a library for an EPD once - OEM version, which later popped up on Waveshare's website as their own - and the OEM's documentation and code were good enough (just...) to produce a functional library.
Looking at the example for your specific screen, I see it is indeed the usual SendCommand() crap. Although it seems slightly more evolved, with an Epd class. But still, useless.
EPD code is HARD, and requires a lot of information from the manufacturer. And producing a library that handles text is also a little harder to get right.
I don't think trying to transplant their crappy code onto an existing library is going to work. I figure you have two solutions:

Rewrite a library for this epaper from scratch.
Half-ass something by adding text handling to their code by converting text to pixels in the buffer, and push that.

In both cases, painful.

Thanks @dda for your answer. I was afraid of exactly these circumstances.. However I am unable to write a new library because this would be far beyond my knowledge and skills (for now).
The third option for me is to purchase different displays for my project and taking great care for available libs and good examples this time, which I did naively not for those.

https://www.waveshare.com/3.52inch-e-paper.htm If you want to stick to Waveshare (and recycle the base plate), get this one. It's b&w only but works weel.

Thank you for the suggestion, I will consider the 3.52inch module.


text:
Incorrect reading from DHT22 (on a Nano board)
I have rigged two different DHT22 sensors to an Arduino Nano board. Both temperature readings are more or less comparable but they produce very different humidity readings.
The sensors are:

Sensor No. 1 is an IDUINO-Version of the DHT22 on PIN 2
Sensor No. 2 is a DHT22 in Grove version from Seeeds Studio on PIN 3

The simple code is build on one of the basic examples as followed:
#include "DHT.h"
#define DHTPIN_2 2     // Digital pin connected to the DHT sensor_1
#define DHTPIN_3 3     // Digital pin connected to the DHT sensor_2
#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321
#define DHTTYPE_11 DHT11   // DHT 11  (AM2302), AM2321

DHT dht_1(DHTPIN_2, DHTTYPE);
DHT dht_2(DHTPIN_3, DHTTYPE);

void setup() {
  Serial.begin(9600);   //consider baud in serial monitor!
  Serial.println(F("DHT22 test!"));
  dht_1.begin();
  dht_2.begin();
}

void loop() {
  delay(5000);
  float h_1 = dht_1.readHumidity();
  float t_1 = dht_1.readTemperature();
  float h_2 = dht_2.readHumidity();
  float t_2 = dht_2.readTemperature();

  //Check if any reads failed and exit early (to try again).
  if (isnan(h_1) || isnan(t_1)) {
    Serial.println(F("Failed to read from DHT sensor_1!"));
    return;
  }

  // Check if any reads failed and exit early (to try again).
  if (isnan(h_2) || isnan(t_2)) {
    Serial.println(F("Failed to read from DHT sensor_2!"));
    return;
  }
  Serial.print(F("Humidities: "));
  Serial.print('\n');
  Serial.print(F("s_1: "));
  Serial.print(h_1);
  Serial.print(F(" s_2: "));
  Serial.print(h_2);
  Serial.print('\n');
  Serial.print(F("Temperatures: "));
  Serial.print('\n');
  Serial.print(F("s_1: "));
  Serial.print(t_1);
  Serial.print(F(" s_2: "));
  Serial.print(t_2);
  Serial.print('\n');
}

The resulting output on the Serial Monitor is:
Temperatures:
s_1: 25.30 s_2: 23.40
Humidities:
s_1: 6.20 s_2: 66.40
Temperatures:
s_1: 25.20 s_2: 23.40
Humidities:
s_1: 6.00 s_2: 66.10
Temperatures:
s_1: 25.10 s_2: 23.40
.
.
.

The humidity reading from sensor_1 seems defective, just having the 10th of the value of sensor_2. Is there a fix for that? Is it possible to re calibrate sensor_1 or is it broken?
Thank you!
Edit: swapping the sensors (suggested by jsotola)
The output results in:
Temperatures:
s_1: 22.60 s_2: 24.70
Humidities:
s_1: 67.80 s_2: 7.30

Its the sensor it seems.

swap the two sensors around

Thanks,@jsotola, i did and posted the results.

the other thing to do is to connect only one sensor at a time

One sensor at a time delivers the same results as above (depending on which sensor is connected). The IDUINO-DHT22 still has this very low value for humidity returned.

The difference in humidity readings may be traced to any number of reasons including faulty parts, incorrect programming or low voltages (please post at what voltage you are running the sensors at) to name a few.
Let us speculate that one of the sensors is reporting relative humidity and the other absolute.  Absolute humidity does not consider temperature where as relative does.  From this web site we get the following conversion equation:

This equation converts relative humidity to absolute. Finding the saturation vapor pressure measured in pascal is not trivial.  So we will use this web site to calculate this value.
Let us use the sample:

Temperature 1: 22.60 C
Temperature 2: 24.70 C
(assumed) Relative Humidity: 67.80 %
(assumed) Absolute Humidity: 7.30

So, average temperature is 23.65 C.
Using this temperature and the above web page, the vapor pressure is 2923 PA.
AH = (67.80 x 2923) / (462.5 x (273.15 + 23.65) x 100)
AH = 0.014437 Kg/(meter cubed)
As absolute humidity is normally written as grams per cubic meter:
AH g/(meter cubed) = 0.014437 * 1000 = 14.43 g/(meter cubed)
14.43 is not 7.30.  Consider your options.  Check your circuit, voltages and software (does varying the amount of time between samples result in different values). Also consider running more tests in better conditions (placing both sensors inside the same sealed container over a long period of time to mitigate exposure to different conditions).

Added later...
Evidently problems with the DHT11 humidity sensor is a known problem:

Arduino.cc forum
Partical.io forum
Raspberry Pi forum
Another from Arduino.cc form

Thank you so much @st2000 for this detailed answer and the good hints on how to proceed! What I checked: The voltage on the USB to the Nano is 5.06V with 0.023A (no difference if one or both sensors are connected). I tried an USB hub with additional power, no effect. I set the delay(10000), which doubled the time but had no effect. I put the whole setup into a plastic container. After 30 minutes of equilibration the humidity readings are keeping this difference. The temperature however is now 0.1° apart :) . You clearly ruled out that the sensor is reporting AH instead of RH.

The specifications for this sensor in the link above states that it reports RH.
This leaves the programming. Not sure if I am able to go into the DHT.h. I assume the problem is still with the sensor. Coming back to my initial question: is it possible to redo the calibration on that one?

I meant to check the voltage provided the DHT22 sensors. Some Arduinos run at 3.3V and others at 5V. Somewhere I read the DHT22 runs better at the higher voltage. I see the Alexnd webpage says 5V and the Grove web page says 3.3 to 5V.  LOL. Also, you may have a bad sensor. Do you have another to swap out with? Lastly, I've had bad luck w/DHT22 sensors too and switch to Sillicon Lab Si7021 sensors.

Oh! Something you might try. You didn't provide a schematic. But if the internet is anything to go by, about 33% of DHT22 projects posted place a 10K pull up resistor on the DHT22's data pin. This is because most serial interfaces like this one use a open collector output so that multiple devices can share a single digital wire. What about the other 77%? Well, the driver should activate an internal processor pull up resistor. But, these resistors very widely. So, try adding a 10K pull up resistor the the digital pin of the problematic DHT22 ... just to see what happens.

I added some links to some forum discussions about the DHT22 humidity sensor. There are more good suggestions in some of these if you want to go the distance.  But I'd check the voltage at the sensors, I might try the pull up (but I think there's only a slim chance that will work) finally I would switch to some of the recommended sensors and buy from a well established company that has a community of uses who you can ask questions of.

Thanks @st2000 for the further input. As for the additional 10k resistor: The IDUINO version of the DHT22 comes with this little break out board which I assume takes care of that. Like in the schematic here from makerguides.com, such one is not necessary. I am going to try to supply this sensor with a different voltage on the weekend and check out your suggested links. Still I guess it is just broken.


text:
Reading I2C data from SW6106 register
I am using the SW6106 powerbank IC as an I2C but no matter what I have tried I couldn't read something other than "FF".
Datasheet for the IC.
Timing diagram for reading data:

Timing diagram for writing data:

The code I use:
#include <Wire.h>

byte ADDRESS_SLAVE = 0x3C;
byte REGISTER_XY = 0xB0;
byte READ_LENGTH = 1;

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

  Wire.begin();
  Wire.setClock(400000); // set I2C 'full-speed'

  Wire.beginTransmission(ADDRESS_SLAVE);
  Wire.write(REGISTER_XY);  // set register for read
  Wire.endTransmission();
}

void loop() {
   Wire.requestFrom(ADDRESS_SLAVE,READ_LENGTH);
   byte buff[READ_LENGTH];
   Wire.readBytes(buff, READ_LENGTH);
   for (int i = 0; i < READ_LENGTH; i++) {
     Serial.println(buff[i], HEX);
   }
   Serial.println();
   delay(1000);
}

Serial monitor output:

I really couldn't understand anything from that timing diagram and couldn't read anything from the IC. I'd appreciate any help.
Edit:
I edited the code a little bit to see what Wire.endTransmission(); returns.
#include <Wire.h>

byte ADDRESS_SLAVE = 0x3C;
byte REGISTER_XY = 0xB0;
byte READ_LENGTH = 1;

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

  Wire.begin();
  Wire.setClock(400000); // set I2C 'full-speed'
}

void loop() {
  Wire.beginTransmission(ADDRESS_SLAVE);
  Wire.write(REGISTER_XY);  // set register for read
  int x = Wire.endTransmission();
  Serial.println(x, DEC);
  delay(200);
}

And it retruns the following:

I really don't know where I am doing wrong.

Have you tried the I2C scanner to check it's on the right address? Sometimes the quoted address in datasheets is the 7-bit address and sometimes the 8-bit address.

@Majenko Yes, I have tried it and I can confirm it's on the right address.

The way that I2C works on that chip, looking at the diagrams, is perfectly normal. Maybe if you move the write (register select) into the loop to just before the read?

Is pin LED4/I2C connected to ground?

You ignore both the return values from Wire.endTransmission() and Wire.requestFrom(). Please output them to the Serial monitor for debugging. Wire.endTransmission() returns a status code and Wire.requestFrom() returns the number of bytes actually read.

@chrisl I edited the code to see what Wire.endTransmission() returns, and it returns a 0 or 3. I edited the post and added the code with a screenshot of the serial monitor.

Check the clock of the power bank ic

@AderNawfal the datasheet say it is 100/400K. I tried both of them and the results are same for both of them.

What the diagram shows is a write to slave address 0x3C with the value 0xB0, then a read 1-byte request for address 0x3C. Can you try this code? https://hastebin.com/wuxuxulito.cpp

@MaximilianGerhardt I tried your code and it returns the following I2C write ret: 0 I2C slave sent us 8 bytes 0. I really don't know why the ic returns 0.

So the I2C write goes through without any errors (was ACKed on both address and data), and the read returns a whopping 8 bytes (?) but then only 1 byte with content 0x00? What's supposed to be returned as data? I can just see 1 byte, but not the meaning. You can also try to remove the Serial.println() except for the one that print the bytes, and some dividor between.

@MaximilianGerhardt Oh, I am really sorry, I was just editing the code to see the other bytes if I could get anything. The original code returns I2C write ret: 0 I2C slave sent us 1 bytes 0 . So It doesn't returns 8 bytes. And I don't know what it should return because the datasheet doesn't specifies anything about the data.

Well so it does correctly see the data I assume. If you have a logic analyzer you can double-check the data trace. Now the translated datasheet (http://ismartware.com/enet_upload/file/20181214/20181214101104_63565.pdf) really doesn't say much more, but it does show that "IRQ" should be connected also. Maybe certain events trigger an IRQ pulse and you're supposed to read the I2C register? But then why are you allowed to write to it? Is it for the LEDs or input? The datasheet gives 0 information about this and withouth that I don't know what you further want to do with this chip..

@MaximilianGerhardt I found this chip on a cheap qc3.0 supported powerbank pcb and when I checked the datasheet I saw that it supports i2c. So I thought to myself maybe I could get some verbose data about the current and voltage output and maybe a battery gauge. But the datasheet is really poor documented. I hope I can get something useful out of it

Next best thing would be to find out a contact email of the chip manufacturer and request details.

I know this post is very old, but I was able to get the register map from the manufacturer, Ismartware. Here's a link to the datapack for anyone else that may end up here while searching for the same thing.


text:
Arduino MKR QoS 1 logging with ArduinoMqttClient
I am collecting data with Arduino MKR GSM 1400 and sending data to Azure Cloud (IOT HUB). Currently I use ArduinoMqttClient ArduinoMqttClient
My question is, how to ensure both parties accepted QoS1 ? Is there any logging (in serial monitor) to see confirmation about delivery, re-transmit and so on? I did not find how to enable logging or whether azure on the other side accept the settings and they communicate each other for QoS 1.
Here is sample of code for publishing in ArduinoMqttClient:
  Serial.println("Publishing message");
  bool retained = false;
  int qos = 1;
  bool dup = false;

  String payload;

  payload += "hello";
  payload += " ";
  payload += millis();
  payload += " ";
  payload += cont++;

  // send message, the Print interface can be used to set the message contents
  mqttClient.beginMessage(outTopic, payload.length(), retained, qos, dup);
  mqttClient.print(payload);
  mqttClient.endMessage();

Here is sample of code for subscribe in ArduinoMqttClient:
  Serial.print("Subscribing to topic: ");

  // subscribe to a topic
  // the second parameter set's the QoS of the subscription,
  // the the library supports subscribing at QoS 0, 1, or 2
  int subscribeQos = 1;

  mqttClient.subscribe(inTopic, subscribeQos);

check if any of the mqttClient functions return a status

Did not find any other reliable as this one...


text:
How to Sort a String with Number by Ascending
I have trouble figuring out how to sort a String that has a Number in it.
The String im sending looks like 112:AAAA and 111:EEEE, how would I sort it so that the 111 will be the first in an array but (and here is what I cant figure out) the sorted array should contain the letters again so it would be a String Array that is sorted by the numbers and look like 111:EEEE, 112:AAAA.
I wanted to use what I have seen on C#, having a key and value, but that does not seem to exist in arduino code. So I improvised by writing everything in 1 char array.
edit: I see I'm mixing up char array and string, im very flexible and its no trouble to change to 1 or the other, currently I use char arrays.
I guess it would also be enough to just sort the strings, but i cant find a function for that also.

Are the numbers always 3-digit long? If so, you can just lexicographically sort the strings.

They can be 2-3 digit long

As Michel Keijzers points out, qsort is the standard sorting function
from the libc. Now, since your numbers can start with either two or
three digits, you can not sort them lexicographically, because if you
did so 111 would sort before 82. Instead I suggest to:

parse the start of the strings as integers
compare the integers
if the integers are equal, then sort the strings lexicographically.

The simplest way to parse the strings into integers is atoi(). Unlike
functions like strtol(), atoi() does no error checking, but it is
good enough if you know for sure that the strings have the right format.
Here is the comparison function:
int compare(const void *a, const void *b)
{
    // Get the strings.
    const char *sa = *(const char * const *) a;
    const char *sb = *(const char * const *) b;

    // First, compare the numeric prefixes.
    int ia = atoi(sa);
    int ib = atoi(sb);
    if (ia < ib) return -1;
    if (ia > ib) return +1;

    // If equal, compare the strings lexicographically.
    return strcmp(sa, sb);
}

And here is an example on how to use it:
#define STR_COUNT 3
const char *strings[STR_COUNT] = { "112:AAAA", "82:FFFF", "111:EEEE" };
qsort(strings, STR_COUNT, sizeof strings[0], compare);

Now the array of strings is sorted as ("82:FFFF", "111:EEEE",
"112:AAAA").

You can use the qsort function (see c-library-function-to-do-sort).
With the user definable comp function you can get the first two or three characters, convert it to in integer and compare it against the converted integer from another element.
I would not advise to use strings, because of the limited SRAM storage of an Arduino, you might run out of memory too fast.


text:
Arduino wait for change in value
I am currently working on a project that involves steering wheels, and I would like a way for Arduino to wait for a change in value. A potentiometer is used and I would like a program to run (say, like lights blinking ) until there is a change in value of the potentiometer ( like an increase in 300).
Thanks in advance.
EDIT
I realized that I did not give enough information about what I want, so here is the actual task I am trying to achieve :
The lights goes on when :
Button is pressed
The lights goes off when :
The button is pressed again
or
Another button is pressed
or
Potentiometer increases or (only one of it) decreases by 300
Plus I didn't mention that the value of the potentiometer will be constantly changing so the old value for the potentiometer should be the one right after the button press.
Soooo sorry for the inconvenience caused. ( I am really bad at programming)

int oldValue;
void setup()
{
    oldValue = analogRead(A1);
}

void loop()
{
    int value = analogRead(A1);
    while( abs(value-oldValue)<300 )
        delay(1);
    oldValue = value;

    // start blinking lights here, as the value has changed by at least 300

}

Gerben thank you but I would like to wait for a change in value, and from my understanding analogRead just reads the value of the pin. Very sorry I didn't mentioned earlier that the analog value must not be zero at the start.

See my edit. It will trigger when the value is increased or decreased by at least 300.

Soo sorry but I updated the question

That's not really how this works (-:  First give it a try yourself (more than 30 minutes). If you can't figure it out, come back, and we'll gladly help.

Figured it out in the end. Although my solution doesn't exactly fit what I wanted but it works in this case. I used the FMS Majenko mentioned like this :
Wait for potentiometer value to go beyond a certain value, then wait for it to come back to the value. If that happens then the lights stop blinking. Thanks guys( this is quite different from what I initially wanted but it is enough for what it is meant to do)

A change in value is nothing more than that.  A change between a value then and the value now.
All you need to do is remember what the value used to be, and compare it with what the value is now. If the two have changed, and the change is big enough, then you do something.
And of course you have to remember that "now" will be "then" "next time".

Thank you Majenko !! ( Gerben basically put your words into c++)

No, Majenko put my code into words q-; (just check the timestamps)

Soo sorry but I updated the question

@SeeJianShin You might find this useful for introducing you to the concepts you need: https://hackingmajenkoblog.wordpress.com/2016/02/01/the-finite-state-machine/


text:
Arduino ISP ATtiny problems
As I was trying to program my ATtiny chip with my arduino, I ran across some problems. Note that I know that this problem is faced almost in every Q and A site and forum so don't flag me as repeat yet. (I was trying to burn the bootloader so my chip runs at 8MHz)
So this is the error code:
C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf -v -v -v -v -pattiny85 -cstk500v1 -PCOM1 -b19200 -e -Uefuse:w:0xff:m -Uhfuse:w:0xdf:m -Ulfuse:w:0xe2:m

 avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
     Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
     Copyright (c) 2007-2014 Joerg Wunsch

 System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

     Using Port                    : COM1
     Using Programmer              : stk500v1
     Overriding Baud Rate          : 19200
avrdude: Send: 0 [30]   [20]
avrdude: Send: 0 [30]   [20]
avrdude: Send: 0 [30]   [20]
avrdude: ser_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x03
avrdude: ser_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x03

avrdude done.  Thank you.

Error while burning bootloader.

* deleted attempt 2 to 9 *
Although a solution to this problem will be very nice, that is not my intention here. I tried almost all solutions I have found and non of them work, and I want to know why. So these are my questions:

What does this code actually mean? The for example the "programmer", is it referring to the Arduino or the ATtiny(or the highly unlikely, laptop that im using.)
How do I access more error codes, if there are any, as I think that these codes really do not tell that much.
[Solved]To prevent Arduino from auto-resetting, almost all tutorials connect the Reset pin to the Ground pin with a 10uF capacitor, and I don't have one. I tried with various other capacitors that I have(22uF, 0.4uF, 0.22uF, 47uF, and 330uF). I do not know how does the capacitance affect the anti auto-resetting function, so some explanation here is helpful.
[solved]

EDIT: I disconnected the ATtiny and the same error code persists. This, I conclude as either I never had a proper connection with the ATtiny, or the problem is with the communication of my laptop with the Arduino.

You need to select the correct programmer in them menu. You need to select Aruino as ISP. Also try the "upload using programmer" option.

@Gerben I am on Arduino as ISP. I just tried the upload using programmer, but same error code.

Re 10μF capacitor, a 22μF should work in its place.    See ArduinoISP on Uno requires 10uF cap -- WHY? on arduino.cc for more.

@JamesWaldby-jwpat7 I have been looking for something like this for ages. Thanks James. Now that's one problem out of the way.

I did not download Arduino as ISP into my arduino. I realize how much of an idiot I am. The capacitor wasn't even needed for some reasons. I might make an intensive tutorial on this project.

I love asian tech culture. NO SHAME IN MAKING A MISTAKE! If LadyAda were asian, the PIs would have pinout text on the boards. +1


text:
Host name is unvalid
I am trying to call a web service from a server but didn't get the correct response on Serial Monitor arduino, i get the error "hostname is invalid". Below is the code along with the result:
Thanks @Edgar Bonet, i have tried as you suggested. Following is the correction and the result, now the error is "The request verb is invalid"
    {
EthernetClient client1;

//second
int inChar;
char outBuf[64];
char params[65];

Serial.print(F("Method 2 connecting..."));

if(client1.connect("198.38.93.76",807) == 1)
{
Serial.println(F("connected"));

// send the header
client1.println(F("POST /JMS_Auth_WebService.asmx HTTP/1.1"));
client1.println(F("Host: 198.38.93.76"));
client1.println(F("Content-Type: text/xml; charset=utf-8"));
client1.println(F("Content-Length: 315"));
client1.println(F("Connection: keep-alive"));
client1.println(F("SOAPAction: \"http://jbscrms.com/GetThresholdOfDeviceForSaud\""));
client1.println();

client1.println(F("<?xml version=\"1.0\" encoding=\"utf-8\"?>"));
client1.println(F("<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"));
client1.println(F("<soap:Body>"));
client1.println(F("<GetThresholdOfDeviceForSaud xmlns=\"http://jbscrms.com\">"));
client1.println(F("<Device_id>2</Device_id>"));
client1.println(F("</GetThresholdOfDeviceForSaud>"));
client1.println(F("</soap:Body>"));
client1.println(F("</soap:Envelope>"));

Serial.println(F("Done Calling New Web Service"));

}
else
{
Serial.println(F("failed"));

}

int connectLoop = 0;

while(client1.connected())
{

if(client1.available())
{
inChar = client1.read();

Serial.write(inChar);
connectLoop = 0;
}

delay(1);
connectLoop++;
if(connectLoop > 30000)
{
Serial.println();
Serial.println(F("Timeout"));
client1.stop();
}
}

Serial.println();
Serial.println(F("disconnecting."));
client1.stop();
}

Following is the result on Serial monitor arduino
Ready
Entered<R_TempData>29</R_TempData>
<R_smokeData>226</R_TempData>
<R_humidityData>36</R_TempData>
Method 2 connecting...connected
Done Calling New Web Service
HTTP/1.1 400 Bad Request
Cache-Control: private
Content-Type: text/xml; charset=utf

-8
    Server: Microsoft-IIS/8.5
    X-AspNet-Version: 4.0.30319
    X-Powered-By: ASP.NET
    Date: Fri, 11 Nov 2016 07:23:28 GMT

Content-Length: 0

HTTP/1.1 400 Bad Request
Content-Type: text/html; charset=us-ascii
Server: Microsoft-HTTPAPI/2.0
Date: Fri, 11 Nov 2016 07:23:28 GMT
Connection: close
Content-Length: 326

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<TITLE>Bad Request</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii">

Bad Request - Invalid Verb

HTTP Error 400. The request verb is invalid.

disconnecting.

Either print("Foo: bar\r\n"); or println("Foo: bar");. println adds the "\r\n" for you.

You need to remove the port (:807) from the Host entry. You can probably remove that entire line. PS. there should be only one space before    HTTP/1.1, not three.

Also, remove protocol, host and port from the POST line: client1.println(F("POST /JMS_Auth_WebService.asmx HTTP/1.1")); And your SOAPAction line is incomplete: the code as posted cannot compile. Please, post here the actual code you are using.

Your Content-Length header is wrong. You are not sending 1000 bytes of data.

I think you need a \r\n between the Post statement and the HTTP statement.
Why are you including the Port number in the Host name?
Your SOAPAction line is wrong, but I guess that's a typo in the post.

Thanks @Matt . You suggested the same as Edhar Bonet. I tried but didn't get a correct response. I have posted the error above.


text:
Can I add my Wi-Fi credentials to ESP module remotely?
I am working on Home automation project and I am stuck somewhere on connecting my smart switch board to internet through my home WIFI. Actually I want to connect my ESP module with my home Wi-Fi remotely.
I was think of something like creating a hotspot through my switch board and connecting the hotspot to my phone, after that I need to send my Wi-Fi credential through that hotspot from my phone to  to ESP. But I dont know actually how to implement it. I didn't find something similar like that so I came here.
If you guys have some different way or you know how to do it , then give me some information about it.

https://github.com/tzapu/WiFiManager