text:
Sending Data between two boards using SoftwareSerial
I'm attempting to connect two Arduino boards to eachother using SotwareSerial as the title suggests!
The two boards are 1) Arduino UNO and 2)MultiWii Controller (MWC) FLIP 1.5 (Uses ATMega328 chip).
The idea, is to get Serial TX on the "MWC" FLIP 1.5 to Serial RX on the UNO.
These are my connections thus far:
MWC Pin ------->UNO Pin
Digital 3 (TX)--->Digital 6 (RX)
Digital 9 (RX)--->Digital 9 (TX)
This is the code on the MWC Chip -- the TX chip. (NOTE: These functions are called to run in a header file)
#include "attout.h"
#include "SoftwareSerial.h"

SoftwareSerial altSerial(9,3); // RX=9 TX=3

void startaltserial(){

  altSerial.begin(9600);

}

void attout(){

pinMode(3,HIGH);
pinMode(9,HIGH);

  altSerial.print('1');

}

NOTE: I also tried altSerial.write('1'). Same result (or lack of one).
Then, the RX Code on the UNO Board:
#include <SoftwareSerial.h>

SoftwareSerial mySerial(6,9); // RX=6 TX=9

void setup()
{
  // Open serial communications:
  Serial.begin(9600);

  // Set the data rate for the SoftwareSerial port
  mySerial.begin(9600);

}

void loop()
{
  while (mySerial.available()>0) {
    Serial.println(mySerial.read());
  }
}

When I open Serial Monitor for the UNO board, I get nothing but zeroes streaming down. Curiously, if I disconnect the TX OUT wire from MWC, the Serial stream stops!
This means, as far as I can tell, that the UNO is doing its job of receiving, and the MWC is doing it's job of transmitting, but something is wrong with the formatting inbetween, so that I end up with zeroes.
Additionally, if I change the baud rate, the Serial Monitor output changes. When I go to 1200 baud, I get nothing but '4' followed quickly by '1' and then carriage return, so it looks like '41'.
Hope we can find a solution to these quandaries. My next course of action is trying I2C, but I'm not sure about it yet...

Do you have a common ground connection? Also please edit the connections in your question you have mentioned TX for both the MWC pins

What's pinMode(3,HIGH); doing? Pinmode accepts INPUT or OUTPUT, not HIGH. Also this line isn't needed.

They are sharing a common ground.. Both plugged in via USB to my laptop. And also, when they're both powered by a battery and the UNO is connected to my laptop, I still get Serial Monitor reading zip. OP edited.
pinMode(3,HIGH); was my attempt to make sure that the pin was actually enabled... I wasn't sure if it was super required or not. Thanks!
Any other ideas?

Out of curiosity, why are you not using hardware serial?

Well, I could use hardware serial on the UNO board, but on the MWC board the hardware serial is already being used by a telemetry radio, so I have to compromise.

Your problem here is that you are streaming out serial data non-stop.
See my answer in this thread: What is Serial.begin(9600)?
Without having a pause, the receiver just latches onto somewhere in the middle of the data stream and tries to make sense of it, often unsuccessfully.
If you add one "character time" delay to the sender, the receiver works fine:
  altSerial.print('1');
  delay (2);

It might get the first one wrong, but now the receiver has 2 ms to resynchronize on the data stream. At 9600 baud the delay should be 1/960 (second) at least, I used twice that to be sure.

Thanks for your fantastic reply! I read the answer in the other thread, and learned a lot there. What you say here helps tremendously in my understanding, and I have attempted the 2ms delay in the sender, but regrettably I am still getting a stream of zeroes in the Serial Monitor... Could this perhaps be a clock sync error? I'm not certain if the clocks on both boards have the same rate. If not, any other suggestions? Thanks Mr. Gammon!

I don't know what speed the MWC runs at, but it seems odd that you are getting zeroes. Either you get data or not, it shouldn't turn 1 into 0.

Thanks Nick! This last comment you made led me to go through all of the MWC's other code (pretty time consuming.. phew!). Turns out it was using direct manipulation of the pins, and bit banging PWM on the pin I was trying to TX out of. All my commands were overridden by the 0 PWM signal. Thanks again, and have a great rest of the weekend!


text:
Is Arduino reliable for serious tasks, such as medical machines?
I'm just getting started with Arduino, and it has a LOT of uses, however, I would like to know how reliable is it? Can it be used for medical purposes (Measure vital signs, or to help surgeons perform surgeries), if it depends on the board, which one is the most accurate and reliable?
I know most robotic tasks will rely on the quality of the servo to interpret the Arduino commands, and sensors, and even the coding/logic, but we can replace/recode all of those things, but when it comes to the main board it gets more complicated

I'd suggest you do background reading specifically on medical device design, then try asking on Electrical Engineering Stack Exchange for more detail on best practices for medical robotics. An Arduino is unsuitable for this sort of work (except very simple concept/demo that will never be used in real surgery.)

You should NOT trust using an Arduino for life safety measures (medical purposes).
This discusses the reliability of an Arduino pretty well- https://electronics.stackexchange.com/questions/15535/reliability-of-the-arduino-platform-for-industrial-use

Althought you should NOT trust Arduino for medical devices, it's perfectly normal to use it to PROTOTYPE your idea and flush it out (without putting human lives in danger).

What kind of board should I use for such task then?

It depends what you want to achieve. Here is a description of the boards https://www.arduino.cc/en/Main/Boards

If you are asking what type of board to use in a medical device, you are not remotely qualified to engineer one.

@ChrisStratton because every good programmer/engineer started by being the best one, not by learning.

@Dodekeract - if you wish to learn by experiment, you must do so in a different field of applications than actual medical devices.  Anyone legitimately prepared to engineer a medical device is going to have a long list of requirements and procedures which every aspect of a design must meet - asking for advice from random internet posters does not remotely figure into it, and indicates that the asker is not qualified to design to this level of reliability requirement.

source: Stack Exchange

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

sort: votes


text:
ATmega 8 wrong timing with Arduino NG bootloader
I have build simple Arduino ISP programmer, which works fine on ATmega 328 chips (when I select Arduino UNO board) and a ton of others (tiny45, tiny2313). But, when I want to program an ATmega8 chip, it writes it succesfuly, but then the chip runs at 1/16 of the desired speed! (for example a delay(1000) in code takes 16 seconds real-life). I have a 16 MHz crystal oscillator with capacitors connected to the chip, so I thought that the problem is not there but... when I remove the crystal, the chip still runs the same, it still takes 16 seconds.
So I assume two possibilities:

the crystal is somehow broken, so the chip runs from some internal
thing? But I tried multiple crystals, all the same,

OR

I am doing something wrong, but I really don't know what...

Does somebody have an idea what may be wrong or how to test it? Or feel free for more details...Thanks
EDIT: In IDE, I am selecting "Arduino NG or older" and then I select ATmega8  as processor. I am uploading the sketches directly, without bootloader.

This sounds like a problem with the fuse bit configuration - specifically, that you are running with an internal oscillator and with a divider configuration that gives you a 1 MHz clock rate.

Second the fuse bits. Try selecting burn bootloader in the arduino menu, as that should set the correct fuses.

I checked it, and in boards.txt, my fuses are set to 0xDF (low) and 0xCA, which, according to this (http://www.engbedded.com/fusecalc) should set to external crystal. I even tried to change low to 0x4C, which should run it at 8MHz internally, but it had no effect...

Gerben: Avrdude returns: "efuse" memory type not defined for part "ATmega8"... I dont know what an efuse is...

Ok, I finally solved it, so I will write it here so somebody may learn from it in the future :) The problem was really in the fuses, thanks Chris Stratton. Most of my chips were bought already modified for working with Arduino. But this ATmega 8 had the factory fuses, which were setting it for working with internal 1MHz oscillator. You can read and your write your fuse settings with avrdude, so I set them to arduino default (lfuse 0xDF, hfuse 0xCA, from boards.txt). Now it works perfectly even without uploading bootloader.

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


text:
How to interrupt a Timer to Change position along a Colour Cycle
I want to have a loop of 4 colours which runs constantly (i.e. red -> green -> blue -> white) each of the colours having their own LED and pin on the Arduino board. There is a 7 second delay between switching the colour and this cycle should run continuously. When I press a button, I want the cycle to immediately switch back to green and continue the cycle (i.e. -> blue -> white -> red) again.
How should I go about this? Can you have a listener for a button press going at the same time as a delay? How do you interrupt the timer and change the active LED?

You could start with the attachInterrupt example sketch and work from there. Here is a possible solution:
enum { GREEN = 0, BLUE = 1, WHITE = 2, RED = 3};
const int buttonPin = 2;
const int ledPin[] = { 4, 5, 6, 7 };
volatile bool reset = false;
int state = GREEN;

void setup() {
  pinMode(buttonPin, INPUT_PULLUP);
  for (int i = 0; i < 4; i++) pinMode(ledPin[i], OUTPUT);
  attachInterrupt(digitalPinToInterrupt(buttonPin), doResetState, FALLING);
}

void loop() {
   digitalWrite(ledPin[state], HIGH);
   delay(7000);
   digitalWrite(ledPin[state], LOW);
   if (state == RED || reset) {
     state = GREEN;
     reset = false;
   }
   else {
     state = state + 1;
   }
}

void doResetState () {
    reset = true;
}

This will not immediately cycle back to GREEN when pressing the button but you can fix that by modifying the doResetState().
Cheers!

The SimpleTimer library would be ideal for this. One timer callback function, the present contents of the loop() function, would advance the lighting state, called by a 7 second timer. Another, your present doResetState() with the modification noted by @MikaelPatel, would read (and debounce) the button on, say, a 100ms timer. The main loop would be reduced to Timer.run();


text:
Simulator for AD8232 Chip
How can I get AD8232 chip in Arduino simulator?
It is because I have my ciruit comprising AD8232 analogue chip but I dont get this chip? I want to make simulatoin of my ciruit.
If it is can not be found in Arduino please direct me in which circuit simulating software can I get it!

I don't think there would be an actual simulator for this chip. Its hard. But there is a way around.
What you are doing eventually is ECG and the output given by this chip is just analog signal i.e. a single float value. So, lets say for now, all you are concerned with is obtaining those float values irrespective of source. And of course you need a lot of them.
What you can do is to use a dataset. As indicated by its name, a dataset contains a large number of (recorded) value of something.
So, you can use a dataset for heart reate to simulate this chip.
There are many related datasets available online for free. just Google it. and find one that suits you.
Hope it help. Thanks.


text:
Error compiling ESP32 Wrover Module in Linux Virtual Machine
SO i have been getting this error window when i compile a simple code to run different LED lights on the ESP32-S2-SOLA (Wrovere) module
Code:
int LED_BUILTIN = 2;

void setup() {
    pinMode (LED_BUILTIN, OUTPUT);
}

void loop() {
    digitalWrite(LED_BUILTIN, HIGH);
    delay(1000);
    digitalWrite(LED_BUILTIN, LOW);
    delay(1000);
}

error:
Arduino: 1.8.15 (Linux), Board: "ESP32 Wrover Module, Default 4MB with spiffs (1.2MB APP/1.5MB SPIFFS), QIO, 80MHz, 115200, None"

Traceback (most recent call last):
  File "/home/student/.arduino15/packages/esp32/tools/esptool_py/3.0.0/esptool.py", line 38, in <module>
    import serial
ImportError: No module named serial
exit status 1
Error compiling for board ESP32 Wrover Module.

"ImportError: No module named serial"

Install python3-serial

The error can be solved by installing Python serial package via these two commands
$ sudo apt-get update -y
$ sudo apt-get install -y python-serial

As Juraj and Majenko pointed out in the comments, your python installation lacks the module serial.
In Linux the best way to install it would be pip or rather pip3 for Python 3:
sudo pip3 install serial

If you don't have pip3 on you system, install python3-pip first, e. g. using apt:
sudo apt install python3-pip

I did both, it still shows the following error

I made it work, thank you for the help

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


text:
Convert character to Integer while leaving encoded

I have two characters, that I get by Bluetooth.
char a = SerialBT.read();
char b = SerialBT.read();

According to the Arduino Reference, decoded data stored in a char gets encoded to ASCII text.
I want to combine them in an Intenger, but the following methods don't work:
int c = a + b;

int c = (int)a + (int)b;

int c = (a - 48) + (b - 48);

and

String c;
c.setCharAt(0, a);
c.setCharAt(1, b);

Thank you

The sentence “decoded data stored in a char gets encoded to ASCII text” makes no sense: a and b contain the received data as is, with no encoding/decoding whatsoever applied. All the methods you show should work, but do different things. What exactly are you trying to achieve by “combining” the characters? Please, show an example of the data you have and the result you want.

@Edgar Bonet, first thank you for the answer. Here is the example: I get the decimal numbers 49 and 50. I save them to two seperate characters, a and b. Now I want to make one number (c) out of two characters (a and b). When I try the methods shown in my post, it don't work.

What do you mean by “it don't work”? What numeric value would you expect c to have?

I expect it to be in ASCII value.

"What do you mean by “it don't work”?" - I get a decimal value, not a ASCII one. Sorry, I didn't write it clearly.

The ASCII value of what? Please, answer my question: if a is 49 and b is 50, what should be the value of c?

@PythonSchlange You still didn't really explain, what you receive and what you want. Are you receiving ASCII encoded data (like the Serial Monitor does)? Or are you receiving simple integers? And what value in what type do you expect as output? The string "4950"? An integer with value 4950? Or are 49 and 50 the decimal values of the two bytes of an integer value?

a is in the example '49', which is 1 in ASCII, and b '50', which is 2. I expect c to be 12 in the end.

You mean something like c = 10*(a-48) + b-48; ?

@StarCat Thank you!

OK, so after the lengthy requests for clarifications, it appears that
you are receiving a number in ASCII decimal ("12") and want to parse
it into an integer.
You may use the parseInt() method of the serial object, like:
int c = SerialBT.parseInt();

This can however make you program quite slow, as parseInt() uses a
timeout to know when to stop expecting more digits.
If you already have read the bytes, you can combine them with simple
arithmetics:
int c = 10 * (a - '0') + (b - '0');

Note that '0' is the same as 48, only it makes more explicit the
intent of your code.

Thank you so much! It's working now. But I recieve a decimal number, just for clearance.

Use an AND mask to convert the character to a digit:
int c = 10 * (a & 0x0F) + (b & 0x0F);

When ASCII was invented, the digits 0 to 9 were encoded in hexadecimal as 30 to 39 to enable easy conversion to/from digits and characters.
To convert a digit to ASCII, OR the byte with 0x30:
byte digit = 5;
char character = digit | 0x30;

To convert a character to a digit, AND it with 0x0F:
char character = '5';
byte digit = character & 0x0F;

These logical operators are faster and more efficient than mathematical operations + and -.

In what way are these operators faster and more efficient? A binary & and a subtraction both take a single clock cycle for an AVR. I.m.o this will only make your code less readable (make it less clear what it is actually doing).

Note also that the byte() conversion has no effect, as it is undone by the subsequent integral promotion. You can simply write character & 0x0f.

@starcat, Regarding readability: yes I agree, but those are the standard transforms since the inception of ASCII and are very well known so are recognised at a glance. Many people write their own macros or inline functions to make them more readable. Regarding speed and efficiency: the & and | circuits in the processor are simpler and use less power, and complete within a smaller fraction of the clock cycle. Regarding the AVR: it's but one of many that may use more clock cycles.

@edgar-bonet, it's for packing the byte into the assembly instruction along with the opcode, as many processors do.

@EdgarBonet, ANDI - Logical AND with Immediate from AVR Instruction Set Manual, Page 36

Re “speed and efficiency”: I doubt you will save a mere picojoule by replacing a subtraction by a bitwise and. You must provide actual measurement data if you want to argue that the difference in energy consumption between subi and andi is at least measurable, let alone relevant in real life. Re “packing the byte into the assembly instruction”: this makes no sense. Semantically, character & byte(0x0F) means int(character) & int(byte(0x0F)), per the rules of the language. Practically, you get the same generated assembly whether you cast or not.

Packing the byte into the instruction is standard practice. For the AVR ANDI instruction, the immediate Konstant byte is split into two nibbles labelled KKKK...KKKK.

What's your point? How is this relevant to the discussion? The same “packing” (called an “immediate” operand) applies to the subtraction instruction subi. And you get the same assembly instruction whether you use a cast to byte or not.

I just compiled a test using bitwise OR | for uint_8 and another for int in VS for x86. It honoured the typecasts, i.e. movzx eax,byte ptr [digit] and mov eax,dword ptr [int_digit], but this is not conclusive because it's a 32-bit processor, so it used a 32-bit | for both, which is still more efficient than using an adder or subtractor circuit. For the 8-bit AVR processor it should use the ANDI instruction. What compiler are you using that doesn't honour the typecasts?

And the power savings are important for extending battery life, for example.

@EdgarBonet, I just compiled the test in AVR gcc 9.2.0. It used lds r24,digit, ori r24,lo8(48) for the byte while it uses lds r24,int_digit, lds r25,int_digit+1, ori r25,3 for the int. So it, too, honours the typecasts. What compiler are you using that doesn't honour the typecasts?

-1 for turning a perfectly good, 5 paragraph answer into a school book report.

Sorry @VE7JRO. It was in response to EdgarBonet's comments.

@VE7JRO, On reflection, I might revert to the previous version because I think StarCat and EdgarBonet were simply trolling. We'll see how it goes for now. I was going to add a section about logic gate efficiency as well... a thesis!

@tim - Why don't you add the max number of chars to your answer to make it even better!!! I think the limit is 30,000 chars per post (HINT: "per post"). Everyone on the planet knows that the longer the answer, the better :)

BTW @VE7JRO, if you thought it was a perfectly good answer why didn't you up-vote it before I added to it? :) And I have a Quartus synthesizer to hand to prove the point about efficiency of a 2-input OR gate versus a full-adder circuit. LOL

@tim - The Arduino Stack Exchange network only gives each user a limited number of votes per day (24 maybe?). I didn't think your answer was worth an up vote when you first posted it, so I didn't up vote it. You've been a member of SO - Stack Exchange for six and one half years, so the up vote / down vote process should not be a surprise to you.

@tim, Trolling? No, it was meant as a genuine comment. I didn’t (and still don’t) see the point of this kind of optimization as an answer to this particular question. It can be useful in other situations where a high level of optimization is essential. Just not here. I just don’t believe this is a useful answer.

I tried with both avr-g++ 5.4.0 (as shipped with Ubuntu 18.04) and avr-g++ 7.3.0 (from Arduino 1.8.13). Both ignore the typecast, as they should per the language rules (read about “C++ integral promotion”). Note that your test is flawed: not only are you changing the typecasts, but also the types and values of the data: the generated assembly obviously has to be different. Read my first comment: I just wrote that character & byte(0x0f) is equivalent to character & 0x0f. That's all there is to compare. PS: it looks like you compiled at optimization level 0. Nobody would ever do that.

Thank you @tim for another soulution, but StarCat's and Edgar Bonet's way is just easier. I don't need the faster soulution in this project as it won't give me any advantage. But anyway, thanks.

@EdgarBonet, I tried int i1 = c1 & char(0x0f); and int i1 = c1 & char(0x0f0f); Both gave andi r24,15 so it honoured the typecast. I also tried int i1 = c1 & int(0x0f); and int i1 = c1 & int(0x0f0f); The former gave andi r24,15 optimised because 15 fits in a byte; the latter gave andi r24,15, andi r25,15.

@PythonSchlange, thanks for the compliment. While it may not be necessary in your particular project, it's essential for battery powered products and low power products in general because it's easier on the power consumption. It's nothing new, & and | have been the efficient method for the last 60 years. The mathematical operators are a degradation of the original design intent of ASCII 30 to 39 hex.

@StarCat, OK you weren't trolling, and I did give you a genuine answer at the time. The OP didn't specify what level of optimisation they wanted, so I simply gave the 60-year-old industry standard method. However, due to compiler optimisations, it's possible to remove the typecasts to make it more readable.

Re “industry standard method”: it was indeed standard in the times when you would do it with dedicated circuitry. If you believe it is still “industry standard” when done today, on a contemporary CPU, please provide some reference. Otherwise I would say it's no more than cargo cult.

Re “it's essential for battery powered products”: Essential? Really? You are visibly not afraid of hyperboles... I performed some actual measurements to see the difference. I invite you to take a look. Spoiler: its far from “essential”.

@EdgarBonet, What is the value of the pull-up resistor inside your Arduino on PD2 for SUBI? And what is the the value your pull-down resistor on PD2 for ANDI? What is the energy consumption of this internal pull-up resistor when shorted to ground via PD2 for the ANDI test?

@EdgarBonet, Rather than being "somewhat surprising", it's highly predictable and obvious to a professional design engineer and hobbyist alike. Although you 'concluded' that a 1% difference (in favour of SUBI) was negligible, you need to consider the bigger picture of the real world. How many ASCII 30 to 39characters are sent across the internet and transposed to/from 0 to 9? What is the energy consumption of that multitude? A 1% fraction of a huge number is still a lot of energy.

The internal (and only) pull-up is about 30 kΩ. There is no pull-down. Note that, for the andi test, I disconnected PD2 before making the measurement in order to not be affected by the pull-up current. Your remark about the energy consumption of the whole Internet is completely out of topic in this Arduino-centric site.

Some (at least) of the current difference looks like that from the internal pull-up resistor left shorted to ground via PD2 throughout the ANDI test. Regarding this site's context, it's completely on-topic to highlight energy reduction especially as it relates to IoT for which Arduinos are used extensively. Besides, you broadened the topic by mentioning "real world applications" on your GitHub link. The principle of using | and &  were sound in 1960 and remain sound to this day - even more so with today's scale of usage.

As I already said, the internal pull-up was disconnected from ground while I was measuring the consumption. 2. I do not intend to broaden the context. IoT, microcontrollers, and even Arduinos are seen in real world applications. 3. I do not dispute that & is a sound option. I dispute that it is “essential” (your word) to choose it over a subtraction. 4. This discussion has drifted way too far. Followup on stackoverflow.

@VE7JRO, I've reverted to the "perfectly good answer". Could you un-down-vote it please?

@tim - No problemo :)  Now we just need a moderator to move these comments to chat where they belong. The SE robot generates a "flag" for the mod's at 20 comments, yet we are now up to 32 comments.

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


text:
Wrong analog reading
I am making a simple Li-Ion battery Tester. Basically its two 5R1 resistor in series and a relay (used to cut off the battery when it reaches cutoff voltage). Arduino is connected with ground to the battery and with A3 to the end of the resistors. But when I try to read the analog value, I receive something like 870, which is about 4.24V. BUT the real voltage is about 3.90V (according to my multimeter). How is that possible? Thanks for any suggestions.

I don't understand the description of your schematic. Please draw it instead.

Basically I am trying to read the battery voltage, using A3 on Arduino Nano, but it show higher value than it is supposed, which is really weird.

How are you powering the Arduino? How are you calculating the voltage?

I am powering it from USB wall socket; I measured it and it outputs 4.92V. Well I am calculation the voltage by multiplying analogRead * 0,00488281

Well, with those figures I calculate it at (870/1023*4.92) 4.184V. How much do you trust your multimeter?

Well, I was thinking about that (my DMM was showing low battery for a while), but my charger is set to charge the batteries to 4.1V, and this is not a fresh battery, so from that reason I thought there must be a mistake somewhere....

I assume both measurements where unloaded?

I don´t fully understand the question... I measured it with the relay closed, if it is what you are asking....

When that relay closes, are you shorting the battery to ground through 10.2 ohms?

@NickGammon That sounds like a bit of an incorrect question there - shorting implies no resistance - the 10.2Ω implies (for a 3.7V battery) a discharge current of (initially) 363mA.  The latter isn't a short, it's a way of draining the battery while remaining well within the allowed current rating.

I have found the answer. I am not an arduino-newbie, but I was thinking that probably I am making a stupid mistake somewhere. But the problem is in my arduino. I tried setting pin D13 (and then all other pins) to HIGH, and I only measured 4.60V! I measured my USB port and it outputs 5.00V exactly, so there must be a problem in the arduino. So the solution - the ADC takes 4.60V as 1023, and therefore if you calculate it you get that the real voltage is 3.90V, which is exactly the same as my DMM said. Thanks Majenko, you were pointing the right way :) By the way, I was using a cheap Arduino Nano from China, I bought it only for 2.2 USD from Ebay. When I used original Arduino, the code and circuit perfectly works. Do you think that this can limit the functionality of my board?


text:
USB 1.1 Low Speed project for Arduino UNO/ATmega328P to learn USB protocol
Arduino UNO is 5V, 16 MHz.
USB 1.1 Low Speed spec operate:

at 5V level - so we avoid to maintain voltage level
at 1.5 Mb/s - so we have 16/1.5 ~= 10 instructions per elementary protocol signal

Is it possible to make Arduino as slave USB device from UART lines connected to USB D+/D- interface with careful timing and assembler programming?
I doesn't familiar with ATmega328P pin I/O capabilities, may be them can't operate at 1.5 MHz so project isn't possible?
UPDATE I found V-USB library that:
implementation of a low-speed USB device for Atmel’s AVR® microcontrollers,
making it possible to build USB hardware with almost any AVR® microcontroller,
not requiring any additional chip.

Still dig into docs to realize possibilities.

The V-USB library is certainly a way of making a Uno act as a low-speed USB device.

Not exactly the answer to your question, but have you tried the typical way to emulate slave devices with Arduino UNO?
It uses the 2nd ATMega present onboard (this applies only to UNO, afaik) and lets you use the main ATMega for other tasks, delegating the USB protocol to the smaller ATMega16.
Do you have any specific reason why you would use the serial lines?

From pointed post: LUFA is an “open source complete USB stack for USB-enabled Atmel Microcontrollers”. I don't fully deep into LUFA docs but pictures show that GPIO pins from microcontroller doesn't directly connected to USB bus and I think that project offloads electrical/protocol USB stuff to corresponding UNO board schematic which does that natively.

specific reason is educational, home DIY.

I have used extensively LUFA on the ATMega16 that is on the Arduino UNO and I can tell you that it does exactly what I said: the ATMega16 acts as USB gadget device. Are you sure that you are not confusing it with the main AVR chip, the ATMega328P? On Arduino UNO R3 there are 2 AVRs. I'm referring to the secondary.

If you look at the schematics, you'll see that the TX & RX lines do not only go to the pin header, they also go to the other AVR, which acts as serial to USB adapter.

With "specific reason" I meant: why do you want to emulate the USB protocol on the ATMega328P when everyone else does it on the ATMega16? From programming perspective, it's identical: they both are AVR, but you have the additional benefit of saving the 328p for implementing some custom functionality.


text:
GPRS shield - Hayes commands to identify a faulty SIM connection
I'm currently battling with a LinkSprite GPRS shield (it's based on the SIMCom SIM900 chip) and seem to have absolutely no luck trying to connect to the network.  I've got two SIMs, both of which should be active, but I cannot get the connection light on.
I've got a serial connection going and it's responding to various AT commands, but I can't connect:

AT+COPS=?

is working, and giving me a list of networks, so I think my antenna is good, but

AT+COPS=-whatever-

immediately gives me +CREG: 3.
I'm now wondering whether there's a fault with my board, and that it's not seeing the SIM cards.  A few commands that I thought would work aren't, for example:

AT+CPIN?

just returns ERROR
Similarly, when trying to read SMS data:

AT+CMGL="ALL"

returns ERROR.
Have I proved that the board isn't seeing the SIM, or is there something definitive I can try?
Thanks in advance!

Having exchanged the board for another one (that works!) I can now confirm that the calls above (e.g. AT+CMGL) should work if there is a working SIM connection.

Are the boards identical? Or are they of different versions/manufacturers?

They were identical.


text:
Connect 2 LSM9DS0 to Flora
So I'd like to connect two of these sensors to an Adafruit Flora (https://www.adafruit.com/products/2020). In the product page it says you can only connect one but in the forum an admin said that you could do it but it required a bit of hacking. I'm new to arduinos and circuits in general. Can someone tell me how I could do this, or at least point me in the right direction?
Edit
I decided to use this multiplexer to use LSM9DS0's with the Flora.
https://www.adafruit.com/products/2717

Adafruit's rectangular 9DOF device, unlike their round 9DOF, brings several more signals out to pads.  When using I²C with the rectangular 9DOF board, as I understand it signal pin SA0_G can be set low or high to modify the device address:

The SDO/SA0 pins (SDO_XM/SA0_XM or SDO_G/SA0_G) can be used to modify the least significant bit of the device address. If the SA0 pin is connected to the voltage supply, LSb is 1 (ex. address 0011101b) else if SA0 pad is connected to ground, the LSb value is 0 (ex. address 0011110b).

Controlling that signal should let you put multiple 9DOF's on one system.  (See my answer to  question 13830 for some additional comments on setting an I²C address.) Also see tables 15 and 16 on page 33 in the spec sheet (DM00087365.pdf) regarding addresses.
If you insist on using round 9DOFs for this application, you would need to find the trace from pin 22¤ of the LSM9DS0 to Vcc on one of your 9DOF boards; working under a microscope with miniature tools, cut the trace and rewire the pin end of the trace to Ground.  This will change that board from using addresses 0x1D and 0x6B to 0x1E and 0x6C, if I correctly understand the spec sheet.
It probably would be a good idea to get one of the rectangular 9DOF's so that you could experiment with changing its addresses, before modifying one of the round ones.
¤ Looking at the top of the chip, pin 24 is just clockwise from the depressed round dot marking pin 1; pin 22 is 1.75 mm from the corner.  See Figure 21, LGA 4x4x1 mm 24-lead outline, in the spec sheet.  That figure shows the underside of the chip.

Could I use this, or something similar, for multiple sensors? http://dsscircuits.com/sale/product/dssc0107

@Chris, I wasn't aware of that item; it should work.  From the data sheet, first you send (via I2C) a control word to the  PCA9544A, to select which attached device the I2C bus is passed through to.  After setup the  attached device can run full speed, but if you need to alternate between devices very much, the selection overhead will add up.


text:
cannot show free space of SD card with arduino nano
I'm using a nano v3, the SD module and a 64GB microSD card.
Writing to the card works fine.
But I can't print out the free space left on the card.
I'm using this code:
/*
  SD card read/write

 This example shows how to read and write data to and from an SD card file
 The circuit:
 * SD card attached to SPI bus as follows:
 ** MOSI - pin 11
 ** MISO - pin 12
 ** CLK - pin 13

 created   Nov 2010
 by David A. Mellis
 modified 9 Apr 2012
 by Tom Igoe

 This example code is in the public domain.

 */

#include <SPI.h>
//#include <SD.h>
#include "SdFat.h"
SdFat SD;

#define csPin 4
File myFile;
SdFat sd;

int startMillis;
int duration;

uint32_t freeKB;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.print("Initializing SD card...");

  if (!SD.begin(csPin)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");

  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
  myFile = SD.open("test.txt", FILE_WRITE);
  if (myFile) {
    myFile.close();
    Serial.println("done.");
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }
}

void loop() {
  myFile = SD.open("test.txt", FILE_WRITE);

  for (int j = 0; j < 1000; j++) {
    myFile.println(j);
  }
  myFile.close();
  startMillis = millis();
  ShowFreeSpace();
  duration = millis() - startMillis;
  Serial.print("Took ");
  Serial.print(duration);
  Serial.println("ms to calculate");
  delay(1000);
}

void ShowFreeSpace() {
  // Calculate free space (volume free clusters * blocks per clusters / 2)
  long lFreeKB = sd.vol()->freeClusterCount();
  lFreeKB *= sd.vol()->blocksPerCluster()/2;

  // Display free space
  Serial.print("Free space: ");
  Serial.print(lFreeKB);
  Serial.println(" KB");
}

What am I doing wrong?

this is a very poor description of what actually happens can't print out the free space ..... it provides no information that could be used to answer the question

aJazz, did you see my answer?

You have two instances of SdFat class. In setup() you begin the SD and for free space you try to use sd. Delete SdFat sd; line and in ShowFreeSpace use SD.vol().


text:
PC Fan Speed Control
I am working on a project to blow air gently through a number of pipes and variable speed. I would like to use a standard PC case fan and have control of whether the fans are on/off and also what speed they spin at. My hope is to attach temperature sensors later and eventually blow are depending on the temperature.
It appears that PC fans on 3-wire and 4-wire systems provide variable speed by changing input voltage ranging from 3-12V  (linear voltage regulator) or with PWM set to 3.3V or 5V. Furthermore, it looks like inexpensive products exist to split/copy a single signal to multiple fans (see here).
I am hoping to control 4-8 fan speeds, as independently as possible while using as simple/standard a case fan as possible. What is the best way to drive PC case fans using the Arduino?
Reference: https://en.wikipedia.org/wiki/Computer_fan_control

You can use a PWM breakout board, like the ones normally used for servos. Something like this from Adafruit

4 wire fans are best because you don't need any drivers, just a PWM output, and they can report RPMs. You might want to up the PWM frequency from uno speeds to avoid "kick noise", but that's it.

To put the comments into an answer:
You can drive most PC fans (which have at least 3 pins) with any PWM source and change their speed through the duty cycle. The Arduino Uno itself has 6 PWM channels. If you want to control more fans, you have to use an extra chip, that provides PWM. You can use the breakout board from Adafruit, but also any other external PWM chip (they are often marked as servo drivers, since servos use PWM signal too).
The speed of most fans can also be changed through providing a different input voltage, but this is not intended for direct variation. Instead this is normally used to set the speed interval, in which the fan should run. For example some PC fans have extra adapters, which lower the supply voltage to let them run more silent. For short term variation you should definitely use PWM. If your fans are too fast at their nominal voltage, you can provide them with a lower voltage permanently.
As dandavis pointed out, the 4th pin is usually connected to a feedback loop. They provide a defined number of pulses per full rotation, so that you can really measure the speed, instead of just estimating. When you don't need this functionality both kinds of fans (3 pin or 4 pin) are good for you.

Since the fan linear voltage regular usually goes up to 12V, and the breakout board from Adafruit says it will only support 6V vcc+, what do you think about going with this https://www.adafruit.com/product/1455 that says it can go up to 17V?

Yeah, thats good. It has enough outputs, is cheaper and fits to your voltage. I would use it

note that 3pin PC fans don't support PWM, they report RPM with the 3rd wire. the 4th wire is the PWM control. That's a bummer because 4pin fans cost more, but they are still cheaper/simpler than rolling your own PWM fan controller or even using a mosfet+dioide and all that. You can feed the 4th pin 3.3v for the PWM.


text:
'Serial1' was not declared in this scope for automatic plant watering
#include <LiquidCrystal.h>
#include <SoftwareSerial.h>
int in1 = 2;
int in2 = 3;
LiquidCrystal lcd(14,15,16,17,18,19);
int led = 13;
int flag = 0;
int motorpin = 11;
int sensorpin = 7;

void setup()
{
  lcd.begin(16,2);
  Serial1.begin(9600);
  pinMode(led, OUTPUT);
  pinMode(motor, OUTPUT);
  pinMode(sensor, INPUT_PULLUP);
  lcd.print("Plant Watering");
  lcd.setCursor(4,1);
  delay(2000);
  lcd.clear()
  lcd.print("RCC INSTITUTE");
  lcd.setCursor(0,1);
  lcd.print("Starting....");
  delay(2000);
  gsmInit();
  lcd.clear();
  lcd.print("System Ready");
}

void loop()
{
  lcd.setCursor(0,0);
  lcd.print("Automatic Mode");
  if (digitalRead(sensor) == 1 && flag == 0)
  {
    delay(1000);
    if (digitalRead(sensor) == 1)
    {
      digitalWrite(led, HIGH);
      sendSMS("Low Soil Moisture detected. Motor turned ON");
      lcd.begin(16, 2);
      lcd.setCursor(0, 1);
      lcd.print("Motor ON ");
      digitalWrite(motor, HIGH);
      delay(2000);
      flag=1;
    }
  } else if(digitalRead(sensor) == 0 && flag == 1)
  {
    delay(1000);
    if (digitalRead(sensor) == 0)
    {
      digitalWrite(led, LOW);
      sendSMS("Soil Moisture is Normal. Motor turned OFF");
      digitalWrite(motor, LOW);
      lcd.begin(16, 2);
      lcd.print("Motor OFF");
      lcd.setCursor(0, 1);
      lcd.print("Motor OFF");
      delay(2000);
      flag = 0;
    }
  }
}

void sendSMS(String msg)
{
  lcd.clear();
  lcd.print("Sending SMS");
  Serial1.println("AT+CMGF=1");
  delay(500);
  Serial1.print("AT+CMGS=");
  Serial1.print('"');
  Serial1.print("+918xxxxxxxxx"); // number
  Serial1.print('"');
  Serial1.println();
  delay(500);
  Serial1.println(msg);
  delay(500);
  Serial1.write(26);
  delay(1000);
  lcd.clear();
  lcd.print("SMS Sent");
  delay(1000);
  lcd.begin(16, 2);
}

void gsmInit()
{
  lcd.clear();
  lcd.print("Finding Module..");
  boolean at_flag = 1;
  while (at_flag)
  {
    Serial1.println("AT");
    while (Serial1.available() > 0)
    {
      if (Serial1.find("OK"))
      at_flag = 0;
    }
    delay(1000);
  }
  Serial1.println("ATE0"); //<=== it says 'Serial1' was not declared in this scope
  lcd.clear();
  lcd.print("Finding Network..");
  boolean net_flag = 1;
  while(net_flag)
  {
    Serial1.println("AT+CPIN?");
    while(Serial1.available() > 0)
    {
      if (Serial1.find("READY"))
        net_flag = 0;
      break;
    }
    delay(1000);
  }
  Serial1.println("AT+CNMI=2,2,0,0,0");
  delay(1000);
  Serial1.println("AT+CMGF=1");
  delay(1000);
  Serial1.println("AT+CSMP=17,167,0,0");
  lcd.clear();
  Serial1.flush();
}

UNO has no Serial1, so what did you expect?

The Uno has no Serial1. Just use Serial. 2. When asking about a compilation error on this site, you always have to include the complete error message, including information, where the error happened.

As an aside: in gsmInit(), the break isn't inside the if (Serial1.find("READY")) for lack of {}; possible bug.

FYI I flagged an admin to purge the phone number from your code.

The UNO only has one serial port, named Serial.  You can create another one using SoftwareSerial (which you have included but not used) and you can, if you choose, name this Serial1.

#include <SoftwareSerial.h>

SoftwareSerial Serial1(4, 5); // RX, TX


text:
Where is all of the Arduino Documentation?
Aside from the main website, I have noticed that it is hard to find documentation for specific Arduino add-ons, such as (This is just one example):
https://www.amazon.com/gp/product/B00OGYXN8C/ref=ppx_yo_dt_b_asin_title_o04_s01?ie=UTF8&psc=1#descriptionAndDetails
Is this fairly normal or are you just expected to "just know what to do" with every Arduino component after a while? I realize that the IDE does have samples, but they don't always help.

You search for tutorials, libraries and their documentation, etc. For example, for this, I searched for "HiLetgo 1602 LCD Keypad Shield 1602 LCD Expansion Shield arduino" (although "1602 LCD Keypad Shield Arduino" would be sufficient) and found multiple tutorials and examples. The "main website" has documentation for Arduino products, not random products from other companies. It's precisely the same for RPi, although with fewer standardized boards/peripheral chipsets.

It's pretty normal, since 90% are churned out by factories in China, and documentation is very much a luxury. Go to a reputable supplier (Adafruit, etc) for good quality and good support.

@Majenko Is this question really opinion based? I was at maybe 5/6th of writing an answer, that gives more context about the documentation topic (which is the OP is clearly lacking). I would say this is worth an answer. The OP asks how one is expected to navigate in the Arduino community. While surely having room for opinion, the question targets the broad consensus and how finding information works in the Arduino community. Voting to reopen.

@chrisl i'd say it's more of a rant than a question.

The OP is clearly frustrated, but that doesn't make it a rant. An answer might help here. I can understand the frustration from having lacking documentation. The reasons for such a lack are also important to know. And I think we are seeing (and answering) questions on this site, that are way worse that this. I'm totally willing to answer this question (though I might do so tomorrow and not now. It's time for bed here)

It turns rant-y on "I'm taking my RPi and going home" (even though the situation is roughly equivalent delta more Arduino clone HW). It turns opinion-y because there's no answer to "where is all the Arduino documentation", which is (again roughly) unanswerable. I'm not opposed to an expository response, but it's not "answerable" in the traditional sense--on main this would be closed for identical reasons; I don't know how the Arduino SE rolls yet.

@chrisl if enough people think it's worth reopening (by voting for it) then who am I to argue?

@DaveNewton I just edited out the main rant part. We'll see what the community makes of it...

Where is all of the Arduino Documentation?

Arduino
So far as I know, the Arduino name is owned by the Italian company Arduino AG.
Arduino AG provide documentation on the website arduino.cc for the products they manufacture.
Arduino AG have no responsibilities for documenting products designed and manufactured by other businesses.
Other businesses
There are many other businesses that design and, in some cases, manufacture products that are designed to be compatible with or to work with products manufactured by Arduino AG. They don't need permission from Arduino AG unless they are using the trademarks or other intellectual property of Arduino AG. In addition, Arduino AG make many designs available under a permissive licence that does not give Arduino AG any control over or responsibility for documentation of cloned or derivative products manufactured or marketed by other businesses.
Examples include Adafruit, Sparkfun and many others.
These businesses provide documentation for the products they manufacture.
Some other businesses might choose to manufacture products without providing documentation or without providing documentation in English. For example a small Chinese manufacturer might only provide documentation in Chinese or provide none at all, expecting users to make use of documentation provided by the community or by the designer whose open-source designs they are using or whose proprietary designs their product is functionally equivalent to.
Open Source Designers
Many hobbyists and small-scale makers provide documentation for use of their designs for products.

I'd like to add to what JRobert said of finding the information the "hard way"(i.e. looking into the datasheet of the chip it used, and understand how it works from schematic).
In the Arduino world, a lot of hardware/shields are so called Open Source Hardware, meaning that many companies can produce the same hardware with the schematic that is released under Open Source hardware license. China happened to be the country where it has the complete value-chain from components, to manufacturing and cheap labour. They are good in producing such products at large quantity and selling at low price, and they are not necessary good in developing original product, and certainly not in documentation (especially in English). These products are not necessary China "knock-off" as many people call it.
Since it is open hardware products, there are multiple vendors producing it and there are many information available on the internet, and take the example you provide, it is "1602 LCD Keypad Shield", and if your google it with this phase, you will soon find this pdf which is not exactly from the same company of your shield, but it is remarkably similar that you can try.
This applied to many hardware/shields that are available in the market. I hope this provide a general guidance and an "easy way" to find the information in your tinkering journey. Of course, if you want to learn more, go dig out the datasheet and schematic as JRobert mentioned.

To be fair, you're really talking about non-Arduino (capital-A) parts from a multitude of suppliers. And yes, the documentation varies in its depth, quality of translation if it wasn't originally written in English, and even availability at all. Taking the part you linked (from a retailer that storefronts for sellers (sometimes not in this country), who sell from component builders (often not in this country, who build with of parts from supplied factories definitely not in this country, ..., you get the idea. There may or may not exist any documentation specifically for this LCD/keypad combination shield.
But just by reading Amazon's seller's part description, I found that it consists of (at least) a 1602 LCD module and an HD44780 LCD controller chip, for both of which I can quickly find and download datasheets. The sixth image to the left of the description is a schematic of the board which shows that the left, right, up, down, and select buttons are 'multiplexed onto an output called AD0. I might have confirm that that is - or isn't - the Arduino's Analog-0 pin, but in any case, now I know what I have to write to decode which button was pressed from the board's analog output.
All this, and the part costs under US$7.00. For that price (and an assumption that these shields aren't being made in huge quantities), a maker couldn't possibly be able to create a custom datasheet for the shield as a whole, but they did supply a schematic, and their board's components are identified, and those components do, in fact have datasheets online.
Slightly awkward, perhaps, especially if one is thinking in terms of parts like MCUs such as the Atmega328 family, that are made in huge enough quantities that its datasheet runs to nearly 700 pages of engineering-ese. Still, the information is there and accessible, without requiring a way lot of digging.
That's part of being an experimenter.

With this particular board, you're quite fortunate in finding a supplier with an actual website and description: HiLetGo LCD1602 Input/Output expansion board LCD Keypad Shield for Arduino. The fact that the photos of the HiLetGo site show the DFRobot logo — the company that hcheung already referred to — shows just how radically open Open Hardware can get! In this case, DFRobot has pretty decent documentation: LCD KeyPad Shield For Arduino: SKU DFR0009 - DFRobot — but even they don't link to the official LiquidCrystal documentation, but a much older archived version.
The Arduino team admits that they “… never entirely got to grips with Arduino documentation”. Their own "Find in Reference" tool in the IDE will sometimes dead-end to error pages on the arduino.cc site. For example, "find in reference" for Serial will take you to a local copy of the documentation that has broken links for the Arduino Leonardo documentation.
It's not always the case, but typically if an Arduino shield costs less than $10 on Amazon then the cost of "just know[ing] what to do" is passed on to you, the user.


text:
Code to display binary value from 1 hall sensor A3144 connected with shift register 74HC165 when magnet is brought near to it or taken away?

I have checked my connections and when I bring a magnet close to the hall sensors the voltage on them which is apprx. 4.5V becomes 0V and when I remove the magnet the sensor turns back to 4.5V. This means that all the hall sensors are responding to the magnets which makes my connections alright. I want to get 0 when magnet is brought closer to the sensor and 1 when taken away.
The below code shows 11111111 continuously and does not get affected even if magnet is brought close or taken away. I expected the code to show 00000000 until magnet is brought closer to any sensor. If magnet is brought closer to 1st sensor, it should have shown 10000000 and so forth.
int load = 7;
int clockEnablePin = 4;
int dataIn = 5;
int clockIn = 6;

void setup() {
Serial.begin(9600);
pinMode(load, OUTPUT);
pinMode(clockEnablePin, OUTPUT);
pinMode(clockIn, OUTPUT);
pinMode(dataIn, INPUT);
digitalWrite(clockEnablePin, LOW);
digitalWrite(clockIn, LOW);
}

void loop() {

//Write pulse to load pin
digitalWrite(load, LOW);
digitalWrite(load, HIGH);

//Get data from 74HC165
byte incoming = shiftIn(dataIn, clockIn, LSBFIRST);

// Print to serial monitor
Serial.print("Pin States: \r\n");
Serial.println(incoming, BIN);
delay(200);
}

uint8_t shiftIn(uint8_t dataIn, uint8_t clockIn, uint8_t bitOrder) {
uint8_t value = 0;
uint8_t i;
for (i = 0; i < 8; ++i)
{
 digitalWrite(clockIn, HIGH);
 if (bitOrder == LSBFIRST)
 {
  value |= digitalRead(dataIn) << i;
 }
 else
 {
  value |= digitalRead(dataIn) << (7 - i);
 }
 digitalWrite(clockIn, LOW);
}
return value;
}

The code as well as the schematic is correct. The problem was with shift register. Thank you everyone for your suggestions.

The wiring seems good to me. The code seems to be from here, which I used before myself (though I have the clock inhibit pin hardwired). Does it work when you test the shift register without the sensors but with buttons or wires?

The connections are correct in the above diagram. I have had a terrible experience with non working shift register. Some 74HC165 don't work properly(might be duplicate). So, try buying from a verified store.
Use this code to get HIGH or LOW value as output. You can change them to 1 or 0 as per your requirement.
I used this code and it works perfect with 8 Hall switches connected to one shift register 74HC165. Don't forget to connect your pins with your Arduino Uno as depicted in the code or you can update your code as per your connections of shift register with Arduino Uno. You can increase the number of inputs by adding more shift register 74HC165 to the circuit & also you just need to update the value of number of shift chips in the below code.
/* How many shift register chips are daisy-chained.
*/
#define NUMBER_OF_SHIFT_CHIPS   1

/* Width of data (how many ext lines).
*/
#define DATA_WIDTH   NUMBER_OF_SHIFT_CHIPS * 8

/* Width of pulse to trigger the shift register to read and latch.
*/
#define PULSE_WIDTH_USEC   5

/* Optional delay between shift register reads.
*/
#define POLL_DELAY_MSEC   1

/* You will need to change the "int" to "long" If the
 * NUMBER_OF_SHIFT_CHIPS is higher than 2.
*/
#define BYTES_VAL_T unsigned int

int ploadPin        = 7;  // Connects to Parallel load pin the 165
int clockEnablePin  = 4;  // Connects to Clock Enable pin the 165
int dataPin         = 5; // Connects to the Q7 pin the 165
int clockPin        = 6; // Connects to the Clock pin the 165

BYTES_VAL_T pinValues;
BYTES_VAL_T oldPinValues;

/* This function is essentially a "shift-in" routine reading the
 * serial Data from the shift register chips and representing
 * the state of those pins in an unsigned integer (or long).
*/
BYTES_VAL_T read_shift_regs()
{
    long bitVal;
    BYTES_VAL_T bytesVal = 0;

    /* Trigger a parallel Load to latch the state of the data lines,
    */
    digitalWrite(clockEnablePin, HIGH);
    digitalWrite(ploadPin, LOW);
    delayMicroseconds(PULSE_WIDTH_USEC);
    digitalWrite(ploadPin, HIGH);
    digitalWrite(clockEnablePin, LOW);

    /* Loop to read each bit value from the serial out line
     * of the SN74HC165N.
    */
    for(int i = 0; i < DATA_WIDTH; i++)
    {
        bitVal = digitalRead(dataPin);

        /* Set the corresponding bit in bytesVal.
        */
        bytesVal |= (bitVal << ((DATA_WIDTH-1) - i));

        /* Pulse the Clock (rising edge shifts the next bit).
        */
        digitalWrite(clockPin, HIGH);
        delayMicroseconds(PULSE_WIDTH_USEC);
        digitalWrite(clockPin, LOW);
    }

    return(bytesVal);
}

/* Dump the list of zones along with their current status.
*/
void display_pin_values()
{
    Serial.print("Pin States:\r\n");

    for(int i = 0; i < DATA_WIDTH; i++)
    {
        Serial.print("  Pin-");
        Serial.print(i);
        Serial.print(": ");

        if((pinValues >> i) & 1)
            Serial.print("HIGH");
        else
            Serial.print("LOW");

        Serial.print("\r\n");
    }

    Serial.print("\r\n");
}

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

    /* Initialize our digital pins...
    */
    pinMode(ploadPin, OUTPUT);
    pinMode(clockEnablePin, OUTPUT);
    pinMode(clockPin, OUTPUT);
    pinMode(dataPin, INPUT);

    digitalWrite(clockPin, LOW);
    digitalWrite(ploadPin, HIGH);

    /* Read in and display the pin states at startup.
    */
    pinValues = read_shift_regs();
    display_pin_values();
    oldPinValues = pinValues;
}

void loop()
{
    /* Read the state of all zones.
    */
    pinValues = read_shift_regs();

    /* If there was a chage in state, display which ones changed.
    */
    if(pinValues != oldPinValues)
    {
        Serial.print("*Pin value change detected*\r\n");
        display_pin_values();
        oldPinValues = pinValues;
    }

    delay(POLL_DELAY_MSEC);
}


text:
Why can't I print this text to LCD?
I've been working on this for 4+ hours, and have gotten nowhere.
I have an array of weather conditions, and a number is sent over serial port to indicate which member of the array to print to the LCD.
I'm guessing the problem is in how I'm defining the array. These are my current 2 guesses for how to define it:
String weatherConditions[49] = { "tornado","hurricane","tropical storm","sev tstorms","tstorms","mix rain-snow","mix rain-sleet","mix snow-sleet","freez drizzle","drizzle","freez rain","showers","showers","snow flur","lt snow show","blowing snow","snow","hail","sleet","dust","foggy","haze","smoky","blustery","windy","cold","cloudy","mostly cloud","mostly cloud","part cloud","part cloud","clear","sunny","fair","fair","mix rain-hail","hot","isol tstorms","scat tstorms","scat tstorms","scat showers","heavy snow","scat snowshow","heavy snow","part cloudy","tshowers","snow showers","isol tshowers","not available" };

or:
char weatherConditions[49][16] = { "tornado","hurricane","tropical storm","sev tstorms","tstorms","mix rain-snow","mix rain-sleet","mix snow-sleet","freez drizzle","drizzle","freez rain","showers","showers","snow flur","lt snow show","blowing snow","snow","hail","sleet","dust","foggy","haze","smoky","blustery","windy","cold","cloudy","mostly cloud","mostly cloud","part cloud","part cloud","clear","sunny","fair","fair","mix rain-hail","hot","isol tstorms","scat tstorms","scat tstorms","scat showers","heavy snow","scat snowshow","heavy snow","part cloudy","tshowers","snow showers","isol tshowers","not available" };

I've tried many other ways of defining the array (including "char* weatherConditions"), but I'm sure most of them were just ignorant guesses.
Later in the code I have this to display a member of the array:
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(weatherTodayHigh);lcd.print("/");lcd.print(weatherTodayLow);lcd.print(" ");lcd.print(weatherConditions[weatherCurrentConditionsCode]);
lcd.setCursor(0, 1);
lcd.print(weatherTomorrowHigh);lcd.print("/");lcd.print(weatherTomorrowLow);lcd.print(" ");lcd.print(weatherConditions[weatherTomorrowConditionsCode);
break;

Everything I try ends up causing nothing to be printed on the 1602 LCD display (I have 15 other scrollable "screens" that are displaying just fine on the LCD). The earlier text on this screen (the highs and lows for today and tomorrow) is displaying fine, but after that, where the weather condition text is supposed to be shown, there is nothing.
I'm able to easily display the same weather condition text on the serial monitor (for that I was using "String weatherConditions[49] = {..." and then "Serial.println(weatherConditions[currentValue]);").
How can I get members of a text array to be printed on the LCD?

Sounds like you're out of SRAM.

That's very possible. I'm so glad you mentioned it. The IDE was giving me warnings about low RAM whenever I uploaded. I've never seen that before. I'll take a closer look at it tomorrow.

Ignacio hit the nail on the head. Once I moved the weatherConditions array to EEPROM, the sketch worked perfectly. Also the IDE stopped giving me errors about low RAM.

Try using const char weatherConditions[49][16] or PROGMEM. Those might be more convenient than using EEPROM.

Does const char not use SRAM? I thought I read that it does? I was deciding between PROGMEM and EEPROM (both of which I'm not fluent with), and I happened to find a nice short EEPROM code for storing and reading strings. It ended up to be way easier than I would've thought, so i stuck with that. Maybe I'll post the code in my answer because it might be helpful for others who stumble upon this question.

Adding const doesn't seem to do anything in this case (I think it doesn't optimize when used on arrays). The only downside with EEPROM is, you have to fill the EEPROM with your data before uploading your main program. But use whatever is easiest for you. Best of luck


text:
Arduino Leonardo doesn't print anything to Serial Monitor with my specific code
I did a project with an Arduino Leonardo and a fingerprint sensor (DY50).
When I uploaded the enroll example from the Adafruit Fingerprint Library and saved my fingerprint, everything worked. But when I upload my code, it doesn't print anything.
My Code
#include <Keyboard.h>
#include <Adafruit_Fingerprint.h>
#define mySerial Serial1

Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);
int fingerprintID = 0;
String inData;
bool isRight;
int pos;

//Number of services to log in
#define servNum 5

//Login URLs for Google, Amazon, Stackoverflow, Arduino and Github
String LogInURL[] = {"https://accounts.google.com/signin", "https://www.amazon.de/ap/signin", "https://stackoverflow.com/users/login", "https://login.arduino.cc/", "https://github.com/login"};
String LogInUser[] = {"user.name@gmail.com", "user.name@example.com", "user.name@example.com", "username", "username"};
String LogInPwd[] = {"password", "password", "password", "password", "password"};

void donothing() {};

void StepsBefore(int serviceNum){
  switch(serviceNum){
    case 0: donothing(); break;
    case 1: donothing(); break;
    case 2: for(int k=0; k<18; k++) Keyboard.press(KEY_TAB); Keyboard.release(KEY_TAB); break;
    case 3: for(int k=0; k<2; k++) Keyboard.press(KEY_TAB); Keyboard.release(KEY_TAB); break;
    case 4: donothing(); break;
    default: Serial.println("Error: Number not recognized."); break;
  }
}

void StepsAfter(int serviceNum){
  switch(serviceNum){
    case 0: Keyboard.println(); break;
    case 1: Keyboard.println(); break;
    case 2: Keyboard.press(KEY_TAB); Keyboard.release(KEY_TAB); break;
    case 3: Keyboard.press(KEY_TAB); Keyboard.release(KEY_TAB); break;
    case 4: for(int k=0; k<2; k++) Keyboard.press(KEY_TAB); Keyboard.release(KEY_TAB); break;
    default: Serial.println("Error: Number not recognized."); break;
  }
}

int getFingerprintIDez() {
  uint8_t p = finger.getImage();
  if (p != FINGERPRINT_OK)  return -1;
  p = finger.image2Tz();
  if (p != FINGERPRINT_OK)  return -1;
  p = finger.fingerFastSearch();
  if (p != FINGERPRINT_OK)  return -1;
  Serial.print("Found ID #");
  Serial.print(finger.fingerID);
  Serial.print(" with confidence of ");
  Serial.println(finger.confidence);
  return finger.fingerID;
}

void askForFingerprint() {
  fingerprintID = getFingerprintIDez();
    delay(50);
    if(fingerprintID == 1){
      isRight = true;
    }
}

void delAfterChar(String inString, String fromToKill){
  pos = inString.indexOf(fromToKill);
  inString.remove(pos, 1000);
  inData = inString;
}

void setup() {
    Serial.begin(115200);
    Serial.println("Debug 1");
    Keyboard.begin();
    Serial.println("Debug 2");
    finger.begin(57600);
    Serial.println("Debug 3");
    if(finger.verifyPassword()) {
        Serial.println("Found fingerprint sensor!");
    }
    else {
        Serial.println("Did not find fingerprint sensor :(");
        while (1) { delay(1); }
    }
}
void loop() {
  inData = Serial.read();
  delAfterChar(inData, "?openid"); //Amazon
  delAfterChar(inData, "/v2/"); //Google
  delAfterChar(inData, "?ssrc"); //Stackoverflow
  delAfterChar(inData, "login?state"); //Arduino
    for (int i=0; i<servNum; i++){
     if(inData == LogInURL[i]){
        askForFingerprint();
        if(isRight == true){
           StepsBefore(i);
           Keyboard.print(LogInUser[i]);
           StepsAfter(i);
           Keyboard.println(LogInPwd[i]);
        }
        else Serial.println("Finger not recognized");
     }
    }
}

What I've tried so far

I changed the baud rate from 9600 to 15200, didn't help
Added a few debug points in the setup to check for an error there, nothing changed
Uploaded a simple Hello World via Serial Monitor sketch, worked perfectly

Question
What could be the issue? It compiles with no error message. If you see any coding mistakes, feedback would be great.

EDIT
Using SoftwareSerial instead didn't help either.

@jsotola I did that, as explained in the third point of what I've already tried. Sorry if it's not understandable, I don't speak English natively.

add while (!Serial); after Serial.begin

Thanks, @Juraj, totally forgot about this. But why did printing Hello World work without that?

the Hello World print was in loop? it doesn't take long to connect, but the code runs fast

@Juraj Yes, it was.

As @Juraj pointed out, I just forgot to use while (!Serial) in the setup, probably because I use other boards that don't need this more often.


text:
Adafruit soundboard with esp32
Board: ESP32 Development Board
I am trying to get the adafruit soundboard code to work on my ESP32.  I have installed espSoftwareSerial but I keep getting errors with their sample code.
I receive
testcode:13:50: error: use of deleted function 'SoftwareSerial::SoftwareSerial(const SoftwareSerial&)'
SoftwareSerial ss = SoftwareSerial(SFX_TX, SFX_RX);

    /*
      Menu driven control of a sound board over UART.
      Commands for playing by # or by name (full 11-char name)
      Hard reset and List files (when not playing audio)
      Vol + and - (only when not playing audio)
      Pause, unpause, quit playing (when playing audio)
      Current play time, and bytes remaining & total bytes (when playing audio)

      Connect UG to ground to have the sound board boot into UART mode
    */

    #include <SoftwareSerial.h>
    #include "Adafruit_Soundboard.h"

    // Choose any two pins that can be used with SoftwareSerial to RX & TX
    #define SFX_TX 5
    #define SFX_RX 6

    // Connect to the RST pin on the Sound Board
    #define SFX_RST 4

    // You can also monitor the ACT pin for when audio is playing!

    // we'll be using software serial
    SoftwareSerial ss = SoftwareSerial(SFX_TX, SFX_RX);

     // pass the software serial to Adafruit_soundboard, the second
    // argument is the debug port (not used really) and the third
    // arg is the reset pin
    Adafruit_Soundboard sfx = Adafruit_Soundboard(&ss, NULL, SFX_RST);
    // can also try hardware serial with
    // Adafruit_Soundboard sfx = Adafruit_Soundboard(&Serial1, NULL, SFX_RST);

    void setup() {
      Serial.begin(115200);
      Serial.println("Adafruit Sound Board!");

      // softwareserial at 9600 baud
      ss.begin(9600);
      // can also do Serial1.begin(9600)

      if (!sfx.reset()) {
        Serial.println("Not found");
        while (1);
      }
      Serial.println("SFX board found");
    }

    void loop() {
      flushInput();

      Serial.println(F("What would you like to do?"));
      Serial.println(F("[r] - reset"));
      Serial.println(F("[+] - Vol +"));
      Serial.println(F("[-] - Vol -"));
      Serial.println(F("[L] - List files"));
      Serial.println(F("[P] - play by file name"));
      Serial.println(F("[#] - play by file number"));
      Serial.println(F("[=] - pause playing"));
      Serial.println(F("[>] - unpause playing"));
      Serial.println(F("[q] - stop playing"));
      Serial.println(F("[t] - playtime status"));
      Serial.println(F("> "));

      while (!Serial.available());
      char cmd = Serial.read();

      flushInput();

      switch (cmd) {
        case 'r': {
          if (!sfx.reset()) {
            Serial.println("Reset failed");
          }
          break;
        }

        case 'L': {
          uint8_t files = sfx.listFiles();

          Serial.println("File Listing");
          Serial.println("========================");
          Serial.println();
          Serial.print("Found "); Serial.print(files); Serial.println(" Files");
          for (uint8_t f=0; f<files; f++) {
            Serial.print(f);
            Serial.print("\tname: "); Serial.print(sfx.fileName(f));
            Serial.print("\tsize: "); Serial.println(sfx.fileSize(f));
          }
          Serial.println("========================");
          break;
        }

        case '#': {
          Serial.print("Enter track #");
          uint8_t n = readnumber();

          Serial.print("\nPlaying track #"); Serial.println(n);
          if (! sfx.playTrack((uint8_t)n) ) {
            Serial.println("Failed to play track?");
          }
          break;
        }

        case 'P': {
          Serial.print("Enter track name (full 12 character name!) >");
          char name[20];
          readline(name, 20);

          Serial.print("\nPlaying track \""); Serial.print(name); Serial.print("\"");
          if (! sfx.playTrack(name) ) {
            Serial.println("Failed to play track?");
          }
          break;
       }

       case '+': {
          Serial.println("Vol up...");
          uint16_t v;
          if (! (v = sfx.volUp()) ) {
            Serial.println("Failed to adjust");
          } else {
            Serial.print("Volume: "); Serial.println(v);
          }
          break;
       }

       case '-': {
          Serial.println("Vol down...");
          uint16_t v;
          if (! (v=sfx.volDown()) ) {
            Serial.println("Failed to adjust");
          } else {
            Serial.print("Volume: ");
            Serial.println(v);
          }
          break;
       }

       case '=': {
          Serial.println("Pausing...");
          if (! sfx.pause() ) Serial.println("Failed to pause");
          break;
       }

       case '>': {
          Serial.println("Unpausing...");
          if (! sfx.unpause() ) Serial.println("Failed to unpause");
          break;
       }

       case 'q': {
          Serial.println("Stopping...");
          if (! sfx.stop() ) Serial.println("Failed to stop");
          break;
       }

       case 't': {
          Serial.print("Track time: ");
          uint32_t current, total;
          if (! sfx.trackTime(&current, &total) ) Serial.println("Failed to query");
          Serial.print(current); Serial.println(" seconds");
          break;
       }

       case 's': {
          Serial.print("Track size (bytes remaining/total): ");
          uint32_t remain, total;
          if (! sfx.trackSize(&remain, &total) )
            Serial.println("Failed to query");
          Serial.print(remain); Serial.print("/"); Serial.println(total);
          break;
       }

      }
    }

    /************************ MENU HELPERS ***************************/

    void flushInput() {
      // Read all available serial input to flush pending data.
      uint16_t timeoutloop = 0;
      while (timeoutloop++ < 40) {
        while(ss.available()) {
          ss.read();
          timeoutloop = 0;  // If char was received reset the timer
        }
        delay(1);
      }
    }

    char readBlocking() {
      while (!Serial.available());
      return Serial.read();
    }

    uint16_t readnumber() {
      uint16_t x = 0;
      char c;
      while (! isdigit(c = readBlocking())) {
        //Serial.print(c);
      }
      Serial.print(c);
      x = c - '0';
      while (isdigit(c = readBlocking())) {
        Serial.print(c);
        x *= 10;
        x += c - '0';
      }
      return x;
    }

    uint8_t readline(char *buff, uint8_t maxbuff) {
      uint16_t buffidx = 0;

      while (true) {
        if (buffidx > maxbuff) {
          break;
        }

        if (Serial.available()) {
          char c =  Serial.read();
          //Serial.print(c, HEX); Serial.print("#"); Serial.println(c);

          if (c == '\r') continue;
          if (c == 0xA) {
            if (buffidx == 0) {  // the first 0x0A is ignored
              continue;
            }
            buff[buffidx] = 0;  // null term
            return buffidx;
          }
          buff[buffidx] = c;
          buffidx++;
        }
      }
      buff[buffidx] = 0;  // null term
      return buffidx;
    }
    /************************ MENU HELPERS ***************************

I bet the Adafruit Soundboard code is not for an ESP32. But you don’t have to use SoftwareSerial on an ESP32! It has plenty of “real” (hardware) serial ports. Use Serial1 or Serial2 instead. For some simple example code see here. You would also have to change the RST pin into a pin that is actually available on the ESP32 (GPIO4 isn’t).


text:
Error 1,603,0 when http post request using arduino and sim900a by Json format
I want to send HTTP post requests to a server in JSON Format using a SIM900 module. But the code is not posting the data and have an error.Can someone help me to solved the error 1,603,0 since I cannot solve , I already try to use http instead of https cause I read from other QnA channel that AT+HTTPPARA="URL can only be read in http .. But nothing happen the error still there. I know the error is about the DNS but I do not know how to solve it.. Sorry it was my first time to use the sim900a
Here is my code:
#include <SoftwareSerial.h>
#include <ArduinoJson.h>

SoftwareSerial SIM900(10, 11);
StaticJsonBuffer<200> jsonBuffer;

char t[32];
char deviceID[12] = "TESTING";
char Name[12] = "Irsyad";
char Place[12] = "JB";

void setup()
{
  SIM900.begin(9600);       // the GPRS baud rate
  Serial.begin(9600);
  Serial.println("Initializing..");

  DynamicJsonBuffer jsonBuffer;

}

void loop()
{
  Serial.println("");
  Serial.println("START");

  Serial.print("Device ID: ");
  Serial.println(deviceID);

  delay(1000);

  if (SIM900.available())
  Serial.write(SIM900.read());

  SIM900.println("AT");
  delay(3000);

  SIM900.println("AT+SAPBR=3,1,\"Contype\",\"GPRS\""); // untuk cek  GPRS
  delay(6000);
  ShowSerialData();

  SIM900.println("AT+SAPBR=3,1,\"APN\",\"\"");//APN mobile phone (cek dekat phone)
  delay(6000);
  ShowSerialData();

  SIM900.println("AT+SAPBR=1,1");
  delay(6000);
  ShowSerialData();

  SIM900.println("AT+SAPBR=2,1");
  delay(6000);
  ShowSerialData();

  SIM900.println("AT+HTTPINIT"); // jika keluar error means gagal
  delay(6000);
  ShowSerialData();

  SIM900.println("AT+HTTPPARA=\"CID\",1"); //parameters untuk HTTP session
  delay(6000);
  ShowSerialData();

  StaticJsonBuffer<200> jsonBuffer;
  JsonObject& object = jsonBuffer.createObject();

  object.set("deviceID",deviceID);
  object.set("Name",Name);
  object.set("Place",Place);

  object.printTo(Serial);
  Serial.println(" ");
  String sendtoserver;
  object.prettyPrintTo(sendtoserver);
  delay(4000);

  SIM900.println("AT+HTTPPARA=\"URL\",\"http://gas-api.smartcp.app/api/ttn/uplink\""); //Server address // tukar pakai lain https://
  delay(4000);
  ShowSerialData();

  SIM900.println("AT+HTTPPARA=\"CONTENT\",\"application/json\""); //json format
  delay(4000);
  ShowSerialData();

  SIM900.println("AT+HTTPDATA=" + String(sendtoserver.length()) + ",100000"); // size bytes untuk hantar data dalam masa 10 seconds
  Serial.println(sendtoserver);
  delay(6000);
  ShowSerialData();

  SIM900.println(sendtoserver);
  delay(6000);
  ShowSerialData;

  SIM900.println("AT+HTTPACTION=1"); // Post the data (1 means post)
  delay(6000);
  ShowSerialData();

  SIM900.println("AT+HTTPREAD");
  delay(6000);
  ShowSerialData();

  SIM900.println("AT+HTTPTERM");
  delay(10000);
  ShowSerialData;
}

void ShowSerialData()
{
  while (SIM900.available() != 0)
    Serial.write(SIM900.read());
  delay(1000);

}

please do not post a picture of text ... remove the picture and add the actual text

Just looking at the code, my guess is that all those 6 second delays cause a timeout error somewhere.
PS +SAPBR: 1,1,"10.143.42.168" I'm unfamiliar with AT-codes, but that 10.143.42.168 looks like an IP address, and that IP address is in the private range. Maybe it's just Carrier-grade NAT, and not related to your problem.

I hope you had found solution, otherwise, I tried this with SIM800l and it is working fine. Maybe you could try that module. I took help from your code in removing a syntax error in my code, so thank you for that.

it doesn't work for me. Getting the same error.


text:
Analog input draws current when Arduino is turned off
I am using a Arduino Pro Micro from SparkFun (similar to Arduino Leonardo, cpu: Atmega 32u4). It has a analog input: A0, which I use to keep track of the battery voltage in my battery powered project (via analogRead).
I found out that the red LED on the board lights up, even if there is no supply voltage on the usual inputs (micro-USB or Vcc). If I use a multimeter to measure the current between the battery and A0, I see that the analog input is drawing about 30mA if the Arduino is not powered.
Is this the normal behaviour? Can I fix this via hardware?

Also asked at: http://forum.arduino.cc/index.php?topic=509951 If you're going to do that then please be considerate enough to add links to the other places you cross posted. This will let us avoid wasting time due to duplicate effort and also help others who have the same questions and find your post to discover all the relevant information.

Hi, thanks for pointing this out. Will post links in future posts!

Yes, it is normal behaviour, and it's called back-powering.
The current is flowing into the input pin and then flowing up through the ESD protection diode inside the chip to VCC.  It's bad, because the ESD protection diode can't take much current and is easy to damage.

simulate this circuit – Schematic created using CircuitLab
You can prevent it from happening by adding some isolation into the input:

simulate this circuit
MOSFET M1 will be ON when VCC has power, but off when it doesn't. The 100kΩ resistor pulls the gate to ground when VCC is off so it doesn't float. The diode is the body diode of the MOSFET added for clarity. You don't need to add a diode there.

Won't the Arduino be powered through the MOSFET's body diode then?

Depends which way round you connect the MOSFET. As long as the diode is facing the power source it won't conduct.

https://electronics.stackexchange.com/questions/134157/jtag-circuit-to-prevent-back-powering

@EdgarBonet But yes, I needed to flip the symbol there - had it backwards. I have also added the diode for clarity.

I am totally new to mosfets. Can you recommend a type?

One with a suitable logic-level threshold voltage.

I often use the BSS138P.

Did i read your schematic correctly? According to wikipedia you use a N-channel, normally unconductive mosfet.

My schematic uses an n channel enhancement mode (normally unconductive) MOSFET.

To get the MOSFET around the right way you want the input on the Drain and the Source goes to the Arduino. The Gate is connected to Vcc. The MOSFET wants to be N-channel enhancement mode "logic level" (that is, it will turn fully on with 5V on the Gate).

This is normal, if you abuse the chip in this fashion.
But you must take into consideration that it is strictly prohibited to apply a voltage to any I/O pin when the chip itself is unpowered.
This is because the protection diodes are not rated to supply power to the chip, and relying on them to do so may cause damage.
The literal statement of this rule is in the data sheet as

Voltage on any Pin except RESET with respect to Ground . . . . . . . . . .-0.5V to VCC+0.5V

If VCC is 0v, then the maximum voltage you may apply to any I/O is half a volt which is approximately (or just below) the point where a protection diode would begin to meaningfully divert current from the I/O to trying to lift the Vcc net of the chip, and likely the entire board.

That's probably due to the clamping diodes. To protect the chip against ESD, there are diodes between the pins and Vcc and ground. This is to make sure that when charge builds up on a pin, it can flow to Vcc (when it's higher than the supply voltage) or to ground (when it's lower than ground level).
If you supply a voltage to a pin without a voltage on Vcc, current will flow through the pin to the supply line, powering the circuit.
You could probably solve this by adding a relatively large resistor in series with the pin.

How I calculate the required resistor?


text:
I keep gettint the error expected construcotr,destructor or type conversion before = token
#include <dht.h>
dht DHT;
#define DHT11_PIN 2     // what pin we're connected to  // DHT 11

String TextForSms ;
String humidity = " Humidity: %";
String temperature = "   Temperature";
String sign = " *C";
char fromc;

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

void loop() {
  int chk = DHT.read11(DHT11_PIN);
  float h = DHT.humidity;
  float t = DHT.temperature;
  delay(2000);
  }

  TextForSms = TextForSms + t + "," + h + ",";
Serial.println(TextForSms);
     TextForSms = "";
   delay(1000);

Please add a sentence to describe the question.  What are you actually asking?

This whole section:
  TextForSms = TextForSms + t + "," + h + ",";
Serial.println(TextForSms);
     TextForSms = "";
   delay(1000);

is outside a block. Code must be inside a block.
There are strict rules governing what can go where in a C or C++ program. I suggest you learn them.


text:
Code for Heart Rate Detection using PPG Sensor
I am using the "MIKROE Heart Rate 3 click" PPG sensor (https://www.mikroe.com/heart-rate-3-click) and an Arduino Nano (https://store.arduino.cc/usa/arduino-nano) to find heart rate estimation. Does someone know what code to use?
The library associated to the MIKROE is unavailable, therefore, I tried using the AFE4404 library through the code shown below and running a separate algorithm for finding heart rate, however, once I ran it, the monitor and plotter do not provide any peaks that must be used to run the algorithms.
PPG TEST CODE (used previously but do not know how to find heart rate)
/*
 * AFE4404 Basic Read library example.
 * https://github.com/rakshithbk/AFE4404-Library
 *
 * On Arduino Uno -  | AFE4404 | Uno Pin
 *                   | I2C_Dat | A4
 *                   | I2C_Clk | A5
 * get_led_val() will return uint32_t values.
 *
 * Advanced - you can modify the sample period and other
 * parameters in the library files (refer AFE4404 datasheet)
 */

#include <Wire.h>
#include <AFE_connect.h>

AFE A;

void setup() {
  Serial.begin(115200);
  Serial.println("AFE4404 basic readings -\n");
  A.init();
}

void loop() {
  Serial.print("LED 1 Val = ");
  Serial.print(A.get_led1_val());
  Serial.print("\t LED 2 Val = ");
  Serial.print(A.get_led2_val());
  Serial.print("\t LED 3 Val = ");
  Serial.print(A.get_led3_val());
  Serial.println();
}

GitHub
rakshithbk/AFE4404-Library
Basic Library of AFE4404 for Arduino Uno. Contribute to rakshithbk/AFE4404-Library development by creating an account on GitHub.


text:
Is there a way to go to the start of the void loop() function kind of like a "continue" keyword in c in loops?

I am new to Arduino programming and am trying to make an obstacle avoiding car with an ultrasonic sensor and a differential driver model. While learning how to code it, I learned that you can exit the void loop() function with an exit(0) to terminate the program analogous to break keyword in C language.
Is there anything similar that I can use to mimic the "continue" keyword, say if I don't want to run the code after a particular line in the void loop() function.

If you return from the loop() function, you immediately end the execution of the current iteration. The loop() function will then start again, as its always looping (therefor the naming). loop() is just a function like any other. It just gets called over and over in an infinite loop.

Using "return;" as if it were a normal function seemed to work. I thought at first that return would do the same thing as exit(0). Thank you so much @chrisl.

I think anexit(0) will just lead into an infinite loop,which is doing nothing. On a microcontroller there must run a code at anytime. It cannot give the control back to an OS.

yes, I have heard using exit(0) is a bad Arduino programming practice.

In the loop() function, return will perform that function. By exiting the function, the for() loop in main() (which we don't see) will iterate again, calling loop() again.
Another way to accomplish the same thing is to write everything in your setup() function, including whatever kind of loop construct you want, and use break; and continue; statements as you're used to:
void setup(){
   // pinMode() & digitalWrite() calls
   // Initialize the Serial port if you need to
   // Any other one-time setup
   //
   // Everything happens here:
   for( .... ){
      // loop contents here
      if( whatever ){
         continue;
      }
      else if( something_else ){
         break;
      }
   }
}

// This just stalls forever when setup() ends:
void loop(){
   ;
}


text:
How to make my sensor reads when i pressed the button
Hi I'm making a digital fare meter, I have a problem in how my sensor reads when I'd pressed the button(single tap). I need the sensor to read once I pressed the button because when I press the button the reading starts from the beginning of the program(when the device starts) not when I pressed it. and the display is not changing if I not pressed the button i need the display in lcd to change even if i only press the button once. ( Sorry for my grammar )
#define sw 5 //pin at push sw is connected
#include <LiquidCrystal_I2C.h>
int irPin=A0;
int count=0;
int counter=0;
boolean state = true;
float distance1; float distance2; float distance3; float distance4;
float wait1;float wait2;float wait3;float wait4;
float fare1;float fare2;float fare3;float fare4;
float hitObject = false;

LiquidCrystal_I2C lcd1(0x26,20,4);
LiquidCrystal_I2C lcd(0x27,20,4);
int lastButtonState = HIGH;   // the previous reading from the input pin
unsigned long lastDebounceTime = 0;  // the last time the output pin was toggled
unsigned long debounceDelay = 50;    // the debounce time; increase if the output flickers
bool buttonState = HIGH; //saving state of the switch
byte tapCounter; //for saving no. of times the switch is pressed
int timediff; //for saving the time in between each press and release of the switch
bool flag1, flag2; //just two variables
long double presstime, releasetime; //for saving millis at press and millis at release
void setup() {

lcd.init();
lcd.backlight();
lcd1.init();
lcd1.backlight();
pinMode(irPin, INPUT);
lcd.setCursor(0,0); lcd.print("Seater 1  D=");
  lcd.setCursor(0,1); lcd.print("Seater 2  D=0.00");
  lcd.setCursor(0,2); lcd.print("Seater 3  D=0.00");
  lcd.setCursor(0,3); lcd.print("Seater 4  D=0.00");
  lcd1.setCursor(0,0); lcd1.print("W=       F=Php0.00");
  lcd1.setCursor(0,1); lcd1.print("W=       F=Php0.00");
  lcd1.setCursor(0,2); lcd1.print("W=       F=Php0.00");
  lcd1.setCursor(0,3); lcd1.print("W=       F=Php0.00");

  Serial.begin(9600); //for serial monitor
  pinMode(sw, INPUT_PULLUP); //setting pin 5 as input with internal pull up resistor

}

void kount()
    {
  { if (!digitalRead(irPin) && state){
 count++;
 state = false;

 }
 if (digitalRead(irPin)){
 state = true;}}}
 void compute()

{
   distance1 = count*1.73;
   fare1 = count*1.73/100+wait1;
 }
 void printlcd()

 {
 lcd.setCursor(12,0); lcd.println(distance1);lcd.println("m");

 }

void loop() {
  kount();
  compute();
  int reading = digitalRead(sw);

  if (reading != lastButtonState) {
    // reset the debouncing timer
    lastDebounceTime = millis();
  }

  if ((millis() - lastDebounceTime) > debounceDelay) {
    // whatever the reading is at, it's been there for longer than the debounce
    // delay, so take it as the actual current state:

    // if the button state has changed:
    if (reading != buttonState) {
      buttonState = reading;
    }
  }
  //Serial.println(buttonState);

  //when switch is pressed
  if (buttonState == 0 && flag2 == 0)
  {
    presstime = millis(); //time from millis fn will save to presstime variable
    flag1 = 0;
    flag2 = 1;

    tapCounter++; //tap counter will increase by 1
    //delay(10); //for avoiding debouncing of the switch
  }
  //when sw is released
  if (buttonState == 1 && flag1 == 0)
  {
    releasetime = millis(); //time from millis fn will be saved to releasetime var
    flag1 = 1;
    flag2 = 0;

    timediff = releasetime - presstime; //here we find the time gap between press and release and stored  to timediff var
    //Serial.println(timediff);
    //delay(10);
  }

  if ((millis() - presstime) > 400 && buttonState == 1) //wait for some time and if sw is in release   position
  {
    if (tapCounter == 1) //if tap counter is 1
    {
      if (timediff >= 400) //if time diff is larger than 400 then its a hold
      {
        Serial.println("Hold");
        hold(); //fn to call when the button is hold
        ;
      }
      else //if timediff is less than 400 then its a single tap
      {

        Serial.print(count);
        Serial.println("single tap");
        singleTap();

        //fn to call when the button is single taped
      }
    }
    else if (tapCounter == 2 ) //if tapcounter is 2
    {
      if (timediff >= 400) // if timediff is greater than  400 then its single tap and hold
      {
        Serial.println("single tap and hold");
        tapAndHold(); //fn to call when the button is single tap and hold
      }
      else // if timediff is less than 400 then its just double tap
      {
        Serial.println("double tap");
        doubleTap(); //fn to call when doubletap
      }
    }
    else if (tapCounter == 3) //if tapcounter is 3 //then its triple tap
    {
      Serial.println("triple tap");
      tripleTap(); //fn to call when triple tap
    }
    else if (tapCounter == 4) //if tapcounter is 4 then its 4 tap
    {
      Serial.println("four tap");
      fourTap();//fn to call when four tap
    }
    tapCounter = 0;
  }
  lastButtonState = reading;
}

void singleTap()
{
compute();
printlcd();
}
void doubleTap()
{

}
void tripleTap()
{

}
void fourTap()
{

}
void hold()
{

}
void tapAndHold()
{

}


text:
Problem with interfacing Cirus OS1 oxygen sensor with Arduio Uno
I am trying to interface Arduino UNO with Cirus OS1 oxygen sensor but not able to get the expected output. The expected voltage output of OS1 sensor is 9-13mV and the oxygen % is expected to be in the range 19-21 %.
I am using the code :
void setup()

{

     Serial.begin(9600);
     analogReference(INTERNAL);
}

void loop()
{

     const float A_REF = 1.1e3;
     const float Sensor_Cal = 1 / 0.6;
     int sensorValue = analogRead(A0);
     float voltage = sensorValue *(A_REF / 1024);
     float oxygen = voltage * Sensor_Cal;
     Serial.print(" Voltage in mV : ");
     Serial.print(voltage);
     Serial.print("  ");
     Serial.print(" Oxygen level in % : ");
     Serial.println(oxygen);
     delay(1000);
}

However, I am getting an output :

I am using Cirus OS1 oxygen sensor - https://www.biometriccables.in/collections/oxygen-sensors/products/oxygen-sensor-os1
Expected voltage range - 9mV to 13mV
Expected oxygen % - 19 to 21 %
Have tried using LM324N opamp, but it's still not giving expected output. Kindly help or suggestions are welcome.


text:
Instead of 1 and 0, make display say On or Off
So for my project, I am making a button that turns on and off an LED, but also display the state of the led on an LCD and by Serial.  But my issue is, I don't want it to just show a 0 or a 1, I want it to say On or Off.
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

int inPin = 22;         // the number of the input pin
int outPin = 13;       // the number of the output pin

int state = HIGH;      // the current state of the output pin
int reading;           // the current reading from the input pin
int previous = LOW;    // the previous reading from the input pin

// the follow variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long time = 0;         // the last time the output pin was toggled
long debounce = 200;   // the debounce time, increase if the output flickers

void setup(){
    // set up the LCD's number of columns and rows:
    lcd.begin(16, 2);
    // Print a message to the LCD.
    lcd.print("System Activated");
    //
    lcd.setCursor(0, 1);
    lcd.print("Ready...");

    pinMode(inPin, INPUT);
    pinMode(outPin, OUTPUT);

    Serial.begin(9600);
    Serial.println("System Activated");
    Serial.println("Made by Mateo Holguin");
    Serial.println("0 = Light is Off | 1 = Light is On");
    Serial.println("=======================================");
}

void loop(){
    reading = digitalRead(inPin);

    if (reading == HIGH && previous == LOW && millis() - time > debounce) {
        Serial.println("Button Switch State Change:");
        if (state == HIGH)
            state = LOW;
        else
            state = HIGH;

        Serial.println(state);
        Serial.println("");
        lcd.clear();
        lcd.print("State: ");
        lcd.print(state);

        time = millis();
    }

    digitalWrite(outPin, state);

    previous = reading;
}

Both of these 2 answers works well, I just used the second one as I am a bit of a noob so I used one that I can understand more.

Another option: use the "inline" if construct:
lcd.print(state ? F("On") : F("Off"));

The format is:
<if comparison> ? <true result> : <false result>

Note the use of F(...) to force the strings to stay in flash memory.

I am going to try this option as well, as it makes a lot of sense to me.  Thank you very much!

When I use that line I get " '_F' was not declared in this scope"

@MateoHolguin Sorry, wasn't thinking straight that day - it's F() not _F()

I uploaded it to the Arduino, and it works perfectly the way I needed it to! Thanks again

Put the strings to display in an array, and output them instead.
char const * const stateDisplay[] = {"Off", "On"};

 ...

lcd.print(stateDisplay[state]);

Could you please explain why "const" is used twice there? I've never seen that before and don't know how to look it up.

@Jerry: One is for stateDisplay (i.e. the pointer is constant), and the other is for *stateDisplay (i.e. the contents are constant as well).

Thanks! I can actually use that in a sketch I'm working on now.

Thank you very much!  I can finally get that one issue fixed!