text:
Why does increasing resistance make a capacitive sensor more sensitive?
From the Capacitive Sensor Page on the Arduino website, it states the following:

The capacitiveSensor method toggles a microcontroller send pin to a new state and then waits for the receive pin to change to the same state as the send pin. A variable is incremented inside a while loop to time the receive pin's state change. The method then reports the variable's value, which is in arbitrary units.

AND

Use a 1 megohm resistor (or less maybe) for absolute touch to activate. With a 10 megohm resistor the sensor will start to respond 4-6 inches away. With a 40 megohm resistor the sensor will start to respond 12-24 inches away (dependent on the foil size)...

However, as mentioned above, what I'm measuring is the time taken to change state, and I understand that more resistance = more time taken = higher value, how exactly does increasing the resistance make the sensor more sensitive, allowing it to respond without even touching it (i.e., inches away)?
Am I not simply increasing the time taken to change state by increasing resistance? How would that make it more sensitive?!?

A capacitor is created from two conductors with a dielectric between them. The capacitance of the capacitor is determined by the surface area of the conductors and the distance between them. The larger the conductive surface, the higher the capacitance. The further apart the conductors, the smaller the capacitance. Using a higher resistance means that you can use a smaller capacitance, i.e. be further away from the sensor, to get the same results.

Thanks for taking the time to reply again Ignacio, i think i get what you mean about the bolded sentences. However, if i am acting as the conductor in a capacitive sensor, what would be the other conductor and dielectric in this case? I find it amazing that i am able to trigger the sensor without even touching it! How would i (acting as a capacitor) even store the voltage produced without even being in contact?

The other conductor is the wire. The dielectric is the air between. Capacitors are capacitors, regardless of what they're made of.

I had a feeling that was the case! Thank you for fast,concise and easily understood answers, i've upvoted your comment and answer in addition to accepting them !


text:
Do I need to use a resistor if I am using a potentiometer to control an LED's brightness?
I am currently tinkering with an arduino, and am using a potentiometer to change the brightness of an LED.
I understand that usually, a resistor is added to the circuit to limit the current flowing through the circuit in order to prevent the LED from burning out.
However, as I am currently using a potentiometer to adjust the LED's brightness, AND as a potentiometer is basically a variable resistor, would I still need a resistor to prevent the LED from burning out? Currently, I do not see a difference between using a 220 ohm resistor and not using it, as the LED seems unaffected.
My code:
const int pot=A0;
const int led=11;
int potValue;

void setup(){
  Serial.begin(9600);
  pinMode(pot,INPUT);
  pinMode(led,OUTPUT);
  analogWrite(led,100);
}

void loop(){
  potValue = analogRead(pot);
  potValue=map(potValue,0,1023,0,255);
  analogWrite(led,potValue);
  Serial.println(potValue);
}

PS: My LED is hooked up to the arduino's PWM pin, and connected to ground on a breadboard.

Without a good quality picture of your setup or some schematics, it's hard to tell what's going on, but from your description, what you're doing is potentially harmful for the LED and the output pin D11.
Yes, LEDs almost always need series resistors to limit their current. They don't limit currents and will burn if you don't do it for them.
If you had the pot in series with the LED, which seems to be what you think is going on, you'd still need a series resistance so that when the pot is all the way to one side, effectively behaving like a 0Ω resistor or a short, you'd still be limiting the current with the 2nd resistor. One would usually use Ohm's Law to calculate that 2nd resistance so that it lets the maximum current the LED can take when the pot is at 0Ω position, usually 20mA for common LEDs.
But that's not how your circuit seems to be wired. The pot is indirectly controlling the LED through an analog input and a PWM output via MCU. So it's not limiting the LED current, in the traditional sense. The pot seems to be wired between 5V and GND with the middle lead (the cursor) hooked up to the analog input A0. That's a variable voltage divider configuration that let's you select a continuous voltage between 0 and 5V that is in turn converted to a value between 0 and 1023 by the MCU ADC (Analog to Digital Converter) - that's the result of the analogRead() call.
That value is then fed to a PWM analog output, through the analogWrite() call, that will output a square wave to the LED. The relative position of the pot will determine the duty cycle of the PWM, i.e., how long the square wave is HIGH or LOW. The problem here is that this circuit where the LED is wired should have its own series current limiting resistance.
To me, if you didn't burn the LED or the D11 pin yet, is pure luck. If you were to turn the pot all the way to maximum brightness (don't do it), the PWM output would act like a digital output put in HIGH level (5V continuously), and without a current limiting resistor, the D11 pin would exceed it's 40mA absolute maximum source current and burn. Unless there's another factor limiting the current that I don't know of, that is.
There are some exceptional cases in which you can control the LED voltage closely so you don't need to limit the current (multiplexing, constant-current supply etc.), but these are really advanced configurations for us newbies. So, from know on, do it like I do it: ALWAYS put a series resistor, until you become familiar with these advanced configurations.
Finally, below are some links that you may find helpful about the topic:

SparkFun Tutorial on LED Current Limiting Resistors
WikiPedia Article about LED series resistors

Thank you for the prompt and detailed reply, you were right in assuming that the pot is controlling the LED through an analog input, and an output via a PWM.I've turned the pot to max brightness momentarily(never more than 1 sec), and am sure glad i've never left it there for extended periods of time!

source: Stack Exchange

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

sort: votes


text:
How to use a Bi-color matrix led 8x8 with 24 pins?
I've just buy this 8x8 LED matrix WLG M20088A/BEG and I'm trying to light all the LEDs in one single color (green) but I don't understand how the 24 pins work for this specific model.
I know that every manufacturer makes different models. Does anyone have any experience with this particular model?

Take a closer look at the device schematic diagram, which I copy below. It will tell you how each of the LEDs are wired. For example, the green LED on the upper-left corner (which I marked with a green circle) has its anode (positive terminal) wired to pin 5, while its cathode (negative terminal) is wired to pin 1. Can you see that?

To light up that LED (green LED on the upper-left corner), you must apply voltage (with limited current), to pins 1 (-) and 5 (+). If you wanted to light up the red LED at the same position instead, you should apply voltage to pins 1 (-) and 20 (+).
To light up all LEDs of a given color, you'll have to connect pins 1, 2, 3, 4, 21, 22, 23 and 24 to the negative terminal of your power supply. These are the LED common anodes. They are called common because they are shared among each pair of red and green LEDs. If you choose to use the red LEDs, you'll also have to wire pins 13 through 20 to your positive supply. On the other hand, if you pick green, you'll wire pins 5 through 12. These are the LED cathodes.
Don't forget to wire a current limiting resistor in series with each LED.

It seems to be:
Row 1 - 8 --> common cathode pins per row.
To light up a whole row, you must connect row X pin to Gnd and all green or red columns to High (Vcc). Do not forget to add a resistance in series!

authors: هاني البخاري

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


text:
433MHz transmitter and receiver pair doesnt work
I have a pair of 433 MHz transmitter and receiver:

Transmitter is connected to Arduino pro mini, receiver to Arduino Uno R3.
Output of receiver on serial looks like that (it doesn't change much):
Basicly I am getting either 75x or zero regardless of transmitter is on or off.
in > upper
756
in > upper
758
0
0
 0
in > upper
758
0
in > upper
757
in > upper

Transmitter code:
#define rfTransmitPin 4
#define ledPin 6

void setup()
{
    pinMode(rfTransmitPin, OUTPUT);
    pinMode(ledPin, OUTPUT);
}

void loop()
{
    for(;;)
    {
         digitalWrite(rfTransmitPin, HIGH);     //Transmit a HIGH signal
         analogWrite(ledPin, 255);              //Turn the LED on
         delay(500);                            //Wait for 1 second

         digitalWrite(rfTransmitPin,LOW);       //Transmit a LOW signal
         analogWrite(ledPin, 0);                //Turn the LED off
         delay(500);                            //Variable delay
    }
}

Receiver code:
const unsigned int upperThreshold = 70;  //upper threshold value
const unsigned int lowerThreshold = 0;  //lower threshold value
const int ledPin = 13;

#define ReceiverPin  A0

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

    pinMode(ledPin, OUTPUT);

    DiodeTest();
}

void loop()
{
   int data = analogRead(ReceiverPin);
   delay(50);

   if(data>upperThreshold)
   {
       digitalWrite(ledPin, LOW);   //If a LOW signal is received, turn LED OFF
       Serial.println("in > upper");
   }

   if(data<lowerThreshold)
   {
       digitalWrite(ledPin, HIGH);   //If a HIGH signal is received, turn LED ON
       Serial.println("in < lower" );
   }

   Serial.println(data);
}

The receiver simply sends random data to the output pin when it is not receiving a valid signal.  It is up to you to encode your transmit signal in a fashion that you can recognise.

Those receivers don't give an analog value. They give a HIGH if a signal is detected, and a LOW when no signal is detected. (Though the HIGH seems to only be 3.7v). So just use digitalRead instead of analogRead.

These types of receivers are AC coupled so you will not be able to do what you are doing as you need to have regular transitions in the signal and not stay in one state for too long.
They are also limited in the speed at which they will work, I expect 19200 bps is too fast.
You need to use a modulation technique such as Manchester Encoding or other technique that guarantees a suitable density of transitions, can synchronize the data and perform error checking.
One popular software library that does this is VirtualWire Arduino Library that is designed for Arduino and the type of transmitters and receivers you are using.

See this post about a radio-controlled car.
I found when using what looks like a similar receiver to yours, that the received data looked like this:

The cyan line was the receiver, the yellow line is what is being transmitted.
The trouble turned out to be the pull-up resistor on the Arduino Rx pin (from the USB chip).
Even with SoftwareSerial it wasn't too great:

I found that using an op-amp as a buffer helped a lot:

I also agree with the comments about adding an aerial wire, just a short length of hookup wire should do it.

You also need to attach a piece of insulated wire as a 1/4 wave length antenna to each of the receiver and transmitter boards. For the 433 MHz type antenna's this would be a piece of wire ~6.8" (17.3cm) long.
For reference if you were using the other popular type of low cost RF link pair at 315 MHz the antennas would be ~9.37" (23.8cm) long.


text:
appending string to char and vice versa
Some days ago i started a thread.
concatenation of non constant character array with a sting
I have a different question but on the same nature (string and chars)
what i want is one variable (string or char) that will hold a standard text and the value of gps coordinates latitude and longitude
The format is this: "latitude/longitude: 30.111111 20.111111"
What i have is a char that holds the standard text and the latitude: "Latitude/Longitude: 30.111111"
I also have another char that holds the second value (longitude)
The chars were generated with dtostrf():
char clat[10 + 20 + 1] = "Latitude/Longitude: ";
char clng[10 + 1];
dtostrf(gps.location.lat(), 10, 6, clat+20);
dtostrf(gps.location.lng(), 10, 6, clng);

I can also make the chars strings:
string1 = String(clat);

What have i tried:
1.Assigning clng to clat directly via dtostrf()
char clat[10 + 20 + 10 + 1] = "Latitude/Longitude: ";
dtostrf(gps.location.lng(), 10, 6, clng+31);

It didnt work and got unexpected output

making clat a string and assign clng via for loop
string1 = String(clat);
    for (int i=0; i<10; i++)
    string1[i+32]=clng[i];

This doesnt append it
I run out of ideas here.
Any help from more experienced guys?

Avoid using String at all costs! This is very bad for embedded programs. Take a lookk at my answer http://arduino.stackexchange.com/questions/1013/how-do-i-split-an-incoming-string/1033#1033 to see why

(See my updated answer to your other question.

solved it. was simple actually. dont know how to do it with chars, but with strings there is the addition operator.
So i converted both to string and used the + operator.
char clat[10 + 20 + 1] = "Latitude/Longitude: ";
char clng[10 + 1];
String string1, string2, finalstr;

and inside the loop:
dtostrf(gps.location.lat(), 10, 6, clat+20);
dtostrf(gps.location.lng(), 10, 6, clng);
string1 = String(clat);
string2 = String(clng);
finalstr = string1 + string2;

Maybe that was too much work?
If you have any smarter alternatives, please provide!

One thing I noticed is you do not need the + in:
char clat[10 + 20 + 1] = "Latitude/Longitude: ";

You can just do this:
char clat[31] = "Latitude/Longitude: ";

A much simpler way to do this is this:
Variables to initialize:
char subfinal[40] = "Latitude/Longitude: ";
String final = ""; //You don't need this, you could always use `String(subfinal)` instead

The code inside a function:
dtostrf(gps.location.lat(), 10, 6, subfinal+10);
subfinal[29] = " ";
dtostrf(gps.location.lng(), 10, 6, subfinal+30);
final = String(subfinal);

I haven't tested it, so let me know if it doesn't work.

In C/C++, char clat[31] allocates 31 characters, not 32. The resulting elements are indexed 0 to 30 inclusive (i.e. there is no element 31).

@Peter Fixed that mistake..

I think it was I who started expressing array lengths as sums in an earlier thread w/ this OP. It isn't necessary to do but it documents why I made the array that long. The final sum is all the compiler cares about but '30+1' reminds me that I've allowed for the NUL terminator in my count. Likewise, '10 + 10 + 1' says I'm counting two strings and the terminator. It just serves to remind me how I arrived at the size.


text:
Tone() generates a high pitched sound when button is released
I have a simple circuit that makes use of the tone() function to produce some sounds.
I also have a button, hooked with an interrupt function, that whenever is pressed, a variable changes.
Sometimes, when the button is pressed, a high pitched sound is produced. What is weird is that this does not happen every time.
You can take a look at this simulation:
https://wokwi.com/projects/291958456169005577
If you press the buttons continuously, you will hear the sound.
Why is this sound triggered? Is there a way to mitigate this?
Perhaps making changes to the tone() function? Or perhaps placing a low-pass filter - as this seems like a high frequency sound?

I do not hear anything out of ordinary in the simulation ... does the same thing happen with hardware?

what kind of actuator are you using and is it the actuator itself that produces the unwanted sound (and not a coil or something like that)? The tone() function generates a square wave and according to Fourier theory a square wave naturaly contains a lot of higher harmonics. If you have an unsuitable actuator which resonates at those harmonics, it could explain such a behaviour...

@jsotola If you press the buttons (say do it 20 times), you will for sure listen to some glitchy sounds when pressed, at some point. Yes, the same thing happens with hardware (which means the emulator is amazing, i guess).

@SimSon I am just using a pushbutton...

ok, now I hear it ... not audible with a laptop PC ... audible with an android phone

please add the code to your post ... the question must stand on its own without having to go to an external source to see the code

put delay(1); after the tone ... checking why that works

@jsotola I fixed the title!

Here is the result of my investigation.
The problem is caused by two factors.
First one is the contact bounce of the switch.
Second one is inadequate pullup strength at the switch, but this may be a simulator issue.
The attached picture shows the data that was captured by the Wokwi logic analyzer module.
The top trace pair shows the tone when the switch bounce is turned off in the simulator.
The rest of the traces are labeled.

Thank you so much for this investigation! I did manage to solve it by using the solution you provided in a comment. Specifically, i used delay(1); after tone().

proper switch debouncing is the real solution ... ignore switch transitions for 5 ms after the initial transition

My explanation for this issue is that the last pulse generated by the tone() function is interrupted while the output is on a high level. This results in the last pulse being shorter than it should be to correspond to the desired sound frequency.

While the pulse length doesn't matter for a continuous output (where the pulse frequency determines the sound frequency), a single short pulse can be interpreted as a pulse of a higher frequency.
According to Fourier theory at least its fundamental frequency will be higher than the one of the longer pulses.
Observations that might substantiate my theory:

the issue happens randomly in ~50% of the cases (for a 50% duty cycle signal).
the frequency of the erronous tone varies and is always higher than the desired frequency, depending on how short the trailing pulse is.

These seem to be the case for the simulation.
Possible fixes:
a) provide the tone() function with the optional duration argument and hope the library itself addresses this problem (which it actually might not as the issue is even in the simulation)
b) make sure to only use multiples of the square wave period for duration, so the wave always stops on a low level
According to my theory, a low-pass filter will not work as a fix because the fault frequency can be close to the desired frequency and is the "primary signal", not just some low amplitude harmonic which would be easier to filter from a (much stronger) fundamental.

Thank you so much for taking the time to investigate and create drawings! I solved this issue using jsotola's suggesting and placing delay(1); after the call to tone().

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


text:
Ubuntu - TinyISP is not recognized
I got a Pocket AVR Programmer.
https://learn.sparkfun.com/tutorials/pocket-avr-programmer-hookup-guide
I hooked it up on Ubuntu Linux, opened up a sketch in the Arduino IDE, selected Programmer: USBTinyISP and then Upload Using Programmer.
However, I am getting this error:
An error occured while uploading the sketch
avrdude: Warning: cannot open USB device: Permission denied
avrdude: Error: Could not find USBtiny device (0x1781/0xc9f)

I even followed this blog post:
https://www.krekr.nl/content/using-usbtinyisp-with-ubuntu/
and issued these commands:
In a terminal, type:
sudo nano /etc/udev/rules.d/99-USBtiny

Then paste
SUBSYSTEM=="usb", ATTR{idVendor}=="1781", ATTR{idProduct}=="0c9f", GROUP="adm", MODE="0666"

into the new file. Write it out by pressing Ctrl-O.
sudo usermod -a -G plugdev YOURUSERNAME
sudo service udev restart
sudo udevadm control --reload-rules

However, the problem still remains.

Use lsusb or dmesg to confirm that the device is listed.

please do not post picture of text ... copy and paste the text into your question instead ... format as code

Have you installed the libusb?

sudo apt-get install libusb-1.0-0-dev

I'm not sure this actually answers the question that was asked.

Why not? usbtiny needs the libusb driver installed to properly work, if it's now installed it won't work, at least in UBUNTU

Thanks but libusb was already installed....

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


text:
Most compact method of powering Arduino from wall socket
There are a lot of methods to power an Arduino from a large range of voltages:

USB cable from PC or from a phone charger or an USB hub
step down converters
step up converters
switching power supply
batteries (connected to the power jack or USB or to Vin)

What I can't seem to find is a small 220V-5V converter. I'd like to put an Arduino in the wall, under a light switch, so size matters.
The last resort option is to open a 5V phone charger and replace the metal prongs that go in a socket with two wires, and replace the USB socket with another pair of wires that go the Arduino board, but still, an Arduino Pro Mini or an Arduino Nano is smaller than the phone charger.

Check your insurance if you are covered in case of fire caused by your construction.

@Josef  Your comment looks like a question. If you have a new question please post it as such.

The last resort option is to open a 5v phone charger and replace the metal prongs that go in a socket with two wires, and replace the usb socket with another pair of wires that go the arduino board, but still, an Arduino Pro Mini or an Arduino Nano is smaller than the phone charger.

You will probably have to do something like that.

Because of the nature of conversion between AC and DC, there has to be some large parts.* I'm not going to go into the specifics here. There is usually a diode bridge (because AC waveforms reverse the current ~60 times a second) and a transformer (to lower the voltage for the diode bridge). They almost always include a regulator and a capacitor to make sure voltage is exact and it outputs a "clean" power supply.
*Switching power supplies, although considerably more expensive, are a lot smaller and more power efficient.
This adapter seems to be the most compact adapter I can find for 220V. You'll never get something near the size you are desiring, even with a switching power supply. I don't know the size of the Amazon adapter I gave a link for, but in the US (120V), iPhone chargers are very small and they should fit in a standard depth outlet box (with a little room left over for relays and such). If you really need to get everything smaller, I recommend using a ATtiny chip.
How I recommend connecting this:
I would avoid ripping this apart at all costs from a safety perspective. It would be really easy to send 220V to your Arduino if you're not careful. If you absolutely have to, you might want to coat it with some non-conductive epoxy or other coding. Note: this may act as a thermal insulator, therefore reducing the lifespan of the part. You should just coil some wire around the prongs, and then melt a little solder onto each of the terminals. Then, cover that with electrical tape and pigtail (with a wire nut) into a source power line. Note: you probably are doing wiring that could be illegal in your area. Check your local building codes before attempting this.
After that, attach a USB cord to the socket and to the Arduino or the ATtiny/ATmega328 chip 5V/GND input (of coarse, after cutting and stripping one end of the USB cord). I would also, after finalizing all the code and circuitry, seal that with some epoxy or somehow add it to an enclosure to make sure you don't fry your Arduino if a loose wire touches the Arduino circuitry.
If you don't feel safe doing any of the above, don't do it. You can live without a Arduino light switch.
That being said, happy hacking! :P

I don't think you can get much smaller than this for a mains -> 5V converter that is isolated from the mains. There are tricks to get non-isolated low voltages, but they are not generally safe.

Thank you, I will order a few of these adapters and post here with the results.

@Vladb If you haven't ordered them already I would suggest asking a question on Amazon for the dimensions. Editing my post to suggest how to connect those to the wiring and your Arduino.

@Vlad Updated post.

No. This is big because it is a linear power supply where the transformer operates at line frequency and so must by physically larger.  It's also unregulated and poorly filtered.  Switching power supplies as have largely taken over in the past few years are much smaller, because their transformers are operated at the higher switching frequency.

@Chris I forgot about switching power supplies... I'm updating my post now. In my opinion, switching power supplies are still somewhat bulky, but nowhere near as big as a linear supply.

I can suggest you to try this : AC DC Step Down Converter
It is as small as the Apple's tiny cube, and it can be placed inside of a wall easily. (I'm personally using this with an arduino micro)

Thank you for the information, i have ordered a few of these too.

Im not quite about things that go to the mains from aliexpress. Anyone used that thing?

Nowadays, most smartphones come with a charger that is linked to the USB plug of the phone.
The charger for my HTC says: 5V, 1A, I guess this voltage must be regulated (but I haven't checked it has the charger is sealed).

The charger itself has a female USB socket on which you can plug any USB cord to link to your Arduino.
IMPORTANT! I have never tried it myself! I would not bet my life on it! It would be wise to check the output voltage is well regulated.

It's regulated. I've cracked those units open to use the circuit inside in other projects. It's amazingly compact.

Simplest and cheapest solution...if it's good enough for Samsung et al then it's...

I use this one, 5V, 3W, very small, and only $3 on Aliexpress.
http://www.hlktech.net/product_detail.php?ProId=54

Using this, following safety tips at https://skippy.org.uk/quick-look-at-the-hlk-pm01/

It's 34mm x 20mm x 15mm, which is very small.

There are small board-mount AC/DC converters like this one http://www.digikey.com/product-detail/en/BP5063-5/BP5063-5-ND/658569

The website says it only works for 120VAC, but the OP says they want a 220V adapter. I guess the title is a little misleading... and there might be another model for 220V.

true. i don't know how much power OP needs but one of these similar ones might work. http://www.digikey.com/product-detail/en/BP5041A5/BP5041A5-ND/658559 , http://www.digikey.com/product-detail/en/PBK-3-5/102-3106-ND/4332643 , http://www.digikey.com/product-detail/en/PBK-1-5/102-3101-ND/4332638

Any good idea is worth investigating. It might be for 110V but now I can look for the 220 version, if there is such a thing. Thank You! DrewTM - you posted right before I did. Thank you again for the links!

An obvious answer has been omitted which is: transformerless power supply.
If your average power requirements are low (<10mA) then this is the most compact way to achieve the desired voltage.
For an in-depth study see: http://ww1.microchip.com/downloads/en/AppNotes/00954A.pdf
Another solution: jeelabs.org /2011/11/27/ultra-low-power-supply/
Some limitations:

safety - NONE - your circuit might now be floating at line voltage
heat dissipation - calculate here: www. daycounter.com/Circuits/Transformerless-Power-Supplies/Transformerless-Power-Supplies.phtml
low current - no servos or relays
voltage fluctuations on the line might affect the circuit

Best answer, much smaller than other options.

The smallest is probably a plug-in USB charger such as Apple's tiny cube. The cheapest is bound to be a ~9v (output) wall-wart scrounged from the lost and found in a tourist's/traveller's hotel.

wanted to do a similar thing and I found and just ordered these:
http://uk.farnell.com/recom-power/rac03-05scr-277/conv-ac-dc-3w-90-305v-in-5v-out/dp/2289701
A fully sealed power supply, disk-shaped, 5cm diameter and 11mm thick. THey are available in 3.3V, 5V, and 12V. They are designed to be put inside walls or behind switches.

That's pretty neat. The product is discontinued anyway. Is there a version around that can output 2A instead of 600ma?

Try an LED driver. Their typical output is 11.8V DC, which is in perfect specs for the Arduino. You can find them nowadays in all shapes and sizes, round or square, low profile or boxy. A 500ma version (6W) is more than enough for your needs.

Try something like this. It's 29x15mm and does 220V AC to 5V/3W DC.

This one is 51 x 30 x 17.5mm

Nov 2016
Here is a list of compact PCB mounted power supplies that are small (~50mmx25mmx20mm) from Mouser:
http://www.mouser.com/Power/Power-Supplies/AC-DC-Power-Modules/_/N-dv0g5?Ns=Output+Current-Channel+1%7c0&No=25&P=1yxt7eu
These all take in 120-240VAC and provide outputs in the range of 3 - 5 vdc with varying options for current.
The 5V 1A from Meanwell (IRM-05-5) looks like a good deal at $8.52 each.
http://www.mouser.com/ProductDetail/Mean-Well/IRM-05-5/?qs=sGAEpiMZZMuWiaalG5TUgH52QN1%252bIKAVmGC9ENLDVf688EuOMfqROg%3d%3d
Paul.

Wow, that's a nice one. Does it have output galvanically isolated from input (i.e. "can I touch the board powered by this thingie")? The datasheet mentions resistance between input and output and also has a couple of coils on schematics, but I'm still not sure.

The datasheet quotes "Isolation Class II".
See: https://en.wikipedia.org/wiki/Appliance_classes#Class_II

What if you replace the nearest outlet with some kind of USB Wall Socket and attach to that (either through a standard USB plug, or inside the wall) ?

This looks like the smallest and cheapest one from all of the above mentioned:
http://www.ebay.co.uk/itm/AC-DC-Power-Supply-Buck-Converter-Step-Down-Module-5V-700mA-for-Arduino-U-/121355318138

It would be helpful if you mentioned some of the details of that converter in your answer.

Ordered a few of these, will add comment with the results when I get them.

It's entirely dependent on whether or not you want to isolate the circuit from the mains. You could use a drop resistor a rectifier and a 5v zener diode but I do not recommend this if you are a hobbyist, in fact I don't recommend this at all, but it is done by some manufacturers with appropriate circuit protection.


text:
Issues in interfacing relay with Arduino
I want to control AC bulb with Arduino, 5v-relay.
My connections are

My code is
#define RELAY1  7

void setup()
{
  pinMode(RELAY1, OUTPUT);
  Serial.begin(9600);
}

void loop()
{
  digitalWrite(RELAY1,LOW); // Turns ON Relays 1
  Serial.println("Light OFF");
  delay(15000); // Wait 5 seconds
  digitalWrite(RELAY1,HIGH); // Turns Relay Off
  Serial.println("Light ON");
  delay(20000);
}

Red LED is on according to AC bulb.
Power LED (Green colored one) is also on as I have given 5v supply from Arduino.

The issues are

Bulb is not following the delay given in the code. The output for the above code is 20sec ON - 15sec OFF -20sec ON - 15sec OFF- 20sec ON -15sec OFF -  1sec ON - 20sec ON - 15sec OFF etc. means apart from 20,15 sec duration there is a duration of 1sec is coming in between as noise. What might be the reason?
On monitor also, only first 3 actions are getting printed after that no printing is observed.

==>The relay I am using is:

What relay board are you using? Do you hear the relay clicking?

yes I can here the relay clicking.!

As Gerben says, please state the relay part number, and give a link to it. Are you sure you connected Vcc on the relay to the +5 V pin on the Arduino?

@Nick, I dont have link to relay. But I have uploaded the relay picture in the question it self.  I am sure that 5v pin on Arduino connected to 5v pin on the relay.

There are two transistors there (the small black things with are sort-of a semicircle). Please read the part number and post that.

Part no on the transistor is "CTBC  5478  JS"

Are there any resistors (or parts of any kind) on the back of the board? Can you photograph that please?

Also please measure what voltage is on the 5V pin (with your multimeter) once the sketch is running. Is it 5V? Or something somewhat lower?

There is nothing on the back of the board except the metal connections.

You may want to add capacitor to help shore up your 5v.

what i would do is test the parts one by one.
so first look if you're signal is good by attaching a led to it.
then test you're relay with 5v.
now you should know what the problem is the arduino or the relay

Everything looks good, however Try a different relay, and double check your AC side and be sure the bulb voltage is correct for the AC and the bulb is OK.
You may have a power shortage from your USB or however you are powering it.  If you can monitor the 5VDC and be sure it is stable.
Good Luck


text:
LED cube and 200 mA limitation
I'm new to electronics and have been getting rather into my Arduino. But I don't just like following an instructable to do something. I like to know the math behind it and how it works inside. Now from my understanding the Arduino (Uno R3 for me), has a 200 mA max current. The LEDs I used have a 20 mA current. Now with 64 LEDs, wouldn't this fry my Arduino? This also applies to my LCD screen with a 160 mA current. Am I missing a key secret to going over amperage?

The current limit you quote is the maximum current that the main chip on the Arduino can tolerate through its 5V or GND pins.
As the chip itself consumes (round numbers demonstrate the theory) say 50mA that leaves 150mA in total that can be sourced or sunk through IO pins.
If you want to supply 20mA per LED (that is actually overkill - you can use considerably less and have very little difference in brightness) that means you can have, illuminated at any one time, (150 / 20 = ) 7.5 LEDs.
To increase the number of LEDs you can drive at once you can:

Reduce the current by increasing the resistor values.
Use multiplexing so that, although it looks like all LEDs are on at once, only a few are actually on at once.
Use external LED driving circuitry (transistors, LED driver shift registers, etc).

All this pertains purely to the current that passes through the main chip itself.  It does not pertain to any current you draw from the 5V or 3.3V pins.  The maximum current through those pins is limited by the voltage regulator they are attached to, and also by the voltage that you are supplying the board with (the higher the voltage, the more voltage has to be dropped, and so the more heat is generated per mA drawn).
The 5V regulator has around 800mA limit when supplied with 6.5V.  If supplied with 12V the limit is considerably less (since it will get too hot and go into thermal shutdown).  You subtract what you are drawing through the chip (maximum 200mA) and that is how much current you have available.
The 3.3V regulator is driven from the 5V regulator, so any current drawn from the 3.3V pin must also be subtracted from what is available on the 5V pin.

I'm assuming you're talking about an 8x8x8 cube.
The 200mA is for all IO. The regular 5v line can supply 500mA. Since you don't have 64 pins available, you are not supplying the leds via the Arduino directly. Probably using some shift register, or led driver chips for the 64 (cathode) columns. For the 8 levels you'd use some PNP transistors or P-channel mosfets.
So the Arduino won't drive any led directly, so it will only use a few tens of milli-amps. Since you'll draw around 1.3A when all leds are lid, you should power the external components directly from the power supply, instead of via the Arduino. Or you'll hit the 500mA limit.
So the Arduino is just pushing the levers, and not doing any of the hard work (crane analogy).


text:
Loop completion and resetting
Alright, so this code is for a game that is a power source connected to 6 buttons at ports 1, 2, 9, 11, 12, and 13. These are consequently supposed to light up 6 LEDs, each connected to 1. If you press the buttons in the right order, all the LEDs blink at once. Does it work?
int ledPin1 = 1;
int ledPin2 = 2;
int ledPin3 = 9;
int ledPin4 = 11;
int ledPin5 = 12;
int ledPin6 = 13;

void setup() {
//put your setup code here, to run once:
}
void loop() {
//put your main code here, to run repeatedly:
int QuestionNumberArray[] = {1, 2, 9, 11, 12, 13};//the array itself
const size_t n = sizeof(questionNumberArray) //the array used
sizeof(questionNumberArray[0]);//the base of the array

for (size_t i = 0; i < n - 1; i++) //the loop itself
{
size_t j = random(1, n-i);
int t = questionNumberArray[i]; //integer output for increase
questionNumberArray[i] = questionNumberArray[j];//the value definition
questionNumberArray[j] = t;
pinMode(questionNumberArray, INPUT);
if(digitalRead(questionNumberArray) == HIGH) {
then(digitalRead(1, 2, 9, 11, 12, 13) == HIGH)
break;
}
}

Also, how do I make it so that people have multiple tries to do it, or is it already like that?
Thank you

Hi err. I have reverted your last change that removed all contents of the question. Even when questions are put on hold, we leave its content as it was so it can be searched later.


text:
Break a big file into smaller files
I had a really big .ino file and I decided to break it down into sub-files.
So I had the .ino file, the globals.h file and the functions.h file.
I moved all the global vars and functions to their respective files.
This is what is going on inside:
//.ino
#include "globals.h"
#include "functions.h"

//globals.h
*Has header guard
*All variables here are extern
*Contains function prototypes - the definition is in functions.h
*Contains objects (like softWareSerial)

//functions.h
#include "globals.h"
*contains function definitions

However, my code will not work.
I get a huge list of errors, but the last of which is about SoftwareSerial (in globals.h)
'SoftwareSerial' does not name a type; did you mean 'SoftwareSerial_h'?

Isn'e the code structure that I posted previously valid?
EDIT: I ask here and not on StackOverflow for example, because the IDE has symo idiosyncracies, like it first loads the .ino and then all the other files in an alphabetical manner.
EDIT 2: I followed user's Edgar Bonet advice (thank you). I reached somewhere, but I get multiple definition errors now. This is the pseudocode to show to display my code structure:
    //string_handling_functions.h
    HEADER_GUARD
    #include <SoftwareSerial.h> //used later. If this call happened in main .ino (even before the call to this header file, code would not work)
    #include <model_definitions.h> //used in the function definition in the .cpp file
    byte clear_Buffer(bool, SoftwareSerial*);

    //string_handling_functions.cpp
    #include <Arduino.h>
    #include "string_handling_functions.h"
    FUNCTION DEFINITION GOES HERE

    //model_definitions.h
    HEADER_GUARD
    #defines
    SoftwareSerial object_definition
    Other Objects Definitions (libs called in main .ino file)
    const char example_var PROGMEM = {0};

    //main_ino.ino
    #include "string_handling_functions.h"

I get these type of errors now:
\sketch\string_handling_functions.cpp.o (symbol from plugin): In function `GSM_Module_SW_Serial':
(.text+0x0): multiple definition of `GSM_Module_SW_Serial'
\sketch\main_code.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here

All errors are multiple definitions. The items that fall victim to this error are objects and arrays.
Some extra questions:

All the vars in .h files have to be extern?
Can they have a value in the header file? (eg extern char value = {"0"};)

EDIT 3:
After compying to all the rules, I had to create many files (.h and .cpp) to group everything together.
These are the last errors that I get, and they have to do with SoftwareSerial:
In file included from \sketch_general_vars.cpp:2:0:
model_definitions.h:498:1: error: 'SoftwareSerial' does not name a type; did you mean 'HardwareSerial'?
 SoftwareSerial Ter_1_SS_RXOnly (TER_1_RX_PIN, TER_1_TX_PIN);
 ^~~~~~~~~~~~~~
 HardwareSerial
model_definitions.h:499:1: error: 'SoftwareSerial' does not name a type; did you mean 'HardwareSerial'?
 SoftwareSerial Ter_2_SS_RXOnly (TER_2_RX_PIN, TER_2_TX_PIN);
 ^~~~~~~~~~~~~~
 HardwareSerial
model_definitions.h:536:1: error: 'SoftwareSerial' does not name a type; did you mean 'HardwareSerial'?
 SoftwareSerial GSM_Module_SW_Serial(GSM_RX_PIN, GSM_TX_PIN);
 ^~~~~~~~~~~~~~
 HardwareSerial

exit status 1
'SoftwareSerial' does not name a type; did you mean 'HardwareSerial'?

When I #include <SoftwareSerial.h> in that file, then so many errors pop up. Its a cat and mouse game.
First of all, the previous Object calls now get multiple definitios errors, for example multiple definition of GSM_Module_SW_Serial'`.
Secondly, I get countless of these messages (not only for READ_GPS):
ino:1817: undefined reference to READ_GPS'`
READ_GPS is defined in globals_non_model.h, defined in globals_non_model.cpp, included in string_handling_functions.h. This is then included in the main ino (#include "string_handling_functions.h")

Thanks for shortening your posted code.  But in this case it may be too much trimming.  Maybe there's enough information here to determine what has gone wrong.  But I don't see it.  (Also, most of the time, I only look at and fix the 1st compiler error.  Often this fixes many of the other errors.)

@st2000 Thank you for the comment! I will try first to organize the errors into categories and will update the question.

maybe just rename functions.h to functions.ino and remove the #include "functions.h" line. https://arduino.github.io/arduino-cli/0.33/sketch-build-process/#pre-processing

At a guess, 'SoftwareSerial' does not name a type; suggests that the definition of an SoftwareSerial object was seen by the compiler before it had read SoftwareSerial.h. See @edgarbonet's answer, in particular, about partitioning a large project file into separately compiled files. It seems like all of your files are still compiled in one run which leaves compilation order out of your control. That can cause the first use of a symbol such as SoftwareSerial appearing before its declaration.

The include for SoftwareSerial needs to go  into the .ino file (the main project file). That way it is included appropriately. Please see my second answer.

Here is a clean model for splitting a large Arduino project down into individual .cpp and .h files : https://forum.arduino.cc/t/how-to-properly-include-functions-written-on-other-sketch-tabs/565672/4

This is not the right way to split a big .ino file. You should instead
think in terms of functional units, i.e. software “modules” that address
specific concerns. For example, if a subset of your code is intended to
manage an hyperdrive, then you could move that to a dedicated
“hyperdrive” module:
// hyperdrive.h -- module interface
* variable declarations (all extern, no initializers)
* function declarations (i.e. prototypes only)
* class definitions

// hyperdrive.cpp -- module implementation
#include <Arduino.h>     // needed if you use the Arduino API
#include "hyperdrive.h"  // to check consistency with the public interface
* variable definitions (without extern, with initializers when relevant)
* function definitions (with bodies)
* class method definitions

// main.ino
#include "hyperdrive.h"
* code of main program

Edit 1: Answering EDIT 2 of the question.

All errors are multiple definitions

This typically happens when you define a variable in a header (.h) file:
the variable gets defined as many times as that header is included
somewhere. You should not do that. The only things you should ever
define in a header are types, which includes classes. Everything
else (functions and variables) should only be declared in the header,
and defined in the accompanying .cpp file.

All the vars in .h files have to be extern?

Yes. Without the extern keyword, you would have a variable
definition, and variable definitions belong to the accompanying .cpp
file. The extern keyword is needed for writing a variable
declaration.

Can [variables] have a value in the header file?

No. An initial value belongs to the variable definition, not to its
declaration.
Edit 2: Answering EDIT 3 of the question.

model_definitions.h:498:1: error: 'SoftwareSerial' does not name a type

If the header file references types or objects that are defined
elsewhere, it needs to have the relevant #include lines. In this case
you need:
#include <SoftwareSerial.h>

multiple definition of `GSM_Module_SW_Serial'

This line:
SoftwareSerial GSM_Module_SW_Serial(GSM_RX_PIN, GSM_TX_PIN);

is a variable definition. At the risk of repeating myself: you should
not put variable definitions in header files. The header should contain
only the declaration:
extern SoftwareSerial GSM_Module_SW_Serial;

whereas the definition should be in the corresponding .cpp file.

Thanks! I followed your advice and definitely got somewhere. I only get multiple definition errors. I updated my question with my current strategy.

I started a bounty without seeing the edit on your part (perhaps I saw it but forgot it?). I will start implementing what you said. Thank you!

I created a part 3 in the edit history. It looks like a cat and mouse game.

Thank you. The blame is on my part, as I did not understand that you have to do the same for object definitions as well. The only thing left is the long list of undefined reference...

If you split the file into multiple .ino files, then the compiler will concatenate them all into one long .ino file before it compiles.  It will put the one that matches the name of the project first and the rest in alphabetical order.  This can cause problems if things end up being used in that long file before they are defined.
You can start the .ino file names with numbers or something and control the order that they get included in, or you can move that code into .h and .cpp files and include it that way.  Header files will be included in the order you include them in the code.

the Arduino builder adds forward declaration for functions and moves class and struct definitions at the beginning of the concatenated file

Yes, but it doesn't always get things right.  I can give dozens of examples that don't compile because the IDE put something in the wrong order.  It happens especially if you define a struct and a function that either returns that type or takes it as an argument.  I've seen many many cases where the forward declaration gets put in before the struct definition and you get does not name a type error.

that problem is not related to multiple ino files. it can happen with one ino too. and it is the only problem with creation of forward declarations. generating the C++ forward declarations is the most convenient thing the builder does for us

Thanks but as Juraj said, the problem is persistent regardless of the naming of the files.

Yes, but the problem is NOT present when using .h and .cpp instead of .ino files.  In that case the inclusion happens where you tell it to be included and things work the way one would expect having used other tools.

I AM using .h and .cpp files. However, the problems have not yet been solved.

I think @Juraj and I were talking about a different type of problem.

I had the same problem. This solution is wrong but I tried all types of solutions and eventually had the same problem. What I did was place the extracted code in another file and labeled it .ino in the same folder as the original file and it worked. Someday they might add the .insert"filename" command. It worked great in the assembler world.

"Someday they might add the .insert"filename" command." - How would that differ from #include < ... >?

.insert would insert the file where the statement is. It could be code, anything that was properly formatted. Even comments if properly delimited.  This was very useful in the old Assembler days.

#include is the same

#include is NOT the same thing. It will only include specific file types. A file with a simple print statement will not include at the insert point, it just says it cannot find it. "
W_Gil_Base:220:10: fatal error: Test.gil: No such file or directory
#include "Test.gil"
^~~~~~~~~~
compilation terminated.
exit status 1
Test.gil: No such file or directory
"  It is in the same directory as the .ino file.

Correct operation of #include is the same thing; You've found a compiler bug (reported) in the v2.1.0 IDE (maybe all IDE 2.x?). It works if you provide the full path to the include file (which should not be necessary). It works for 'recognized' file extensions (which should also not be necessary. In IDE 1.8.19, the #include directive does work correctly.

You need to treat the .ino file as a project file. Just put in that the includes for things like software serial. That triggers the IDE to include the appropriate libraries. Don't put any other code in it. Put declarations into .h files and definitions (ie. variable values and functions) into .cpp files.
If you do it that way make sure you do the usual C and C++ convention. Make forward declarations of functions, in case you attempt to use a function before its definition is found. These would normally go into .h files.

Some extra questions:
All the vars in .h files have to be extern?

If you don't want multiple declaration errors you should be declaring but not defining variables in your .h files. So yes, they should be extern.

Can they have a value in the header file? (eg extern char value = {"0"};)

No - because you will be including it multiple times, probably. In fact you can't have a value on an extern, it doesn't make sense. Using extern means it is defined elsewhere.

Put the declarations in the .h files with extern in front of them. Then they have to be defined somewhere (ie. given a value). You could make a .cpp file specifically for that purpose.
Did you read the link I gave? That goes into it in some detail.

//.ino
#include "globals.h"
#include "functions.h"

//globals.h
*Has header guard
*All variables here are extern
*Contains function prototypes - the definition is in functions.h
*Contains objects (like softWareSerial)

The includes for SoftwareSerial need to go into the .ino file because that is what the IDE scans for, to see what libraries to link into your project.
Just put the (includes for the) libraries into the .ino file, nothing else.

Header guards just stop multiple copies of the same .h file being included in the same compilation unit. They don't stop multiple .h files being included into different compilation units (multiple .cpp files). So they may not achieve much here.

Thank you! I am using the proper format however the errors remain. I have .h files and their equivalent cpp files with function and variable definitions. However, i get errors like  undefined reference to Battery_level'in the main.ino` file. This var (for example, one of many vars) is declared in a .h file and defined in the .cpp file. The header is included in another header, and this another header included in the main ino file. What is weird is that other vars in the header/cpp file are fine. Only some vars are affected. There are two headers whose vars give errors to the main ino.

And even if include these header files directly to the main ino file (like i said, they are included in another header, which is then included by the ino file), the problems still remain and are exactly the same.

Please make a Minimal, Reproducible Example of this problem. Just make two or three (small) files which reproduce the problem, nothing else, and post their complete contents here.

@user1584421 In the process of making this MRE you will probably hit a point where, before you do X it compiles, and after you do X you get error messages. Then you can see that X is the issue. If you can't see why X is the issue then we can help you.

I moved all the global vars and functions to their respective files. This is what is going on inside:

As Delta_G said, the concatenated file is the main file first (the one with the name of the project) followed by the other files in alphabetic order. This may move global vars to be declared after they are used in other files. I would have left the global vars in the main file.
However as Edgar_Bonet said in his answer, it would probably be better to make the whole thing modular.

See my answer How the IDE organizes things - it explains it in more detail.

'SoftwareSerial' does not name a type; did you mean 'SoftwareSerial_h'?

Things like includes of libraries therefore have to go in the main file - putting them in sub files breaks the inclusion of those libraries, hence that error message.


text:
Creating an AC pulse with arduino and perhaps components
I want to create an AC PWM pulse with arduino. The microcontoller, will be also responsible for specifying the frequency (which will be around 500 Hz).
External electronic components can also be used. Like an H-Bridge perhaps.
EDIT: This is the final waveform I want to produce:

I know the arduino is not capable of producing 36 V output. I plan to just create this waveform, with whatever the arduino can output  and then step up the voltage. But this is the final waveform that I want produced.

What exactly do you mean with "AC PWM pulse"?

@chrisl I edited the question.

Ah, ok. Using a H-bridge sounds good here. Have you tried it? What is your specific problem in doing so?

Yes a H-bridge is what you want. But be careful with controlling it as you may need to add a "dead zone" to prevent crowbaring (aka "overshoot").

@chrisl My problem is lack of experience.. So I do not know the best approach to this problem. Should I create a PWM pulse, double the frequency that I want with the arduino. Then half the frequency should be reversed with the H-Bridge? If yes, how exactly do I control the H-Bridge so that it reverses the pulse where I want? There is another option of a continuous output by the digital pin, then the H-Bridge will reverse half of the time .... So you get this AC square pulse.. But timing is critical so that you get the frequency you want...

Can you specify the load?

@TonyStewartEE75 The device that I am trying to emulate says OUTPUT: 31V, 193mA, 6W. I don't know if this fully describes the load. If it does not, please tell me so i can measure tomorrow with an Amp meter.

What is the supply? That does not load impedance or device or datasheet.  Do you mean +/-31V load from +/-36V supply drawing 6W max, non-inductive.  Do you need a power supply or want to make one from 12VDC or 5V?

@TonyStewartEE75 What i specified was from the supply output. Essentially, i want to recreate the power supply. Unfortunately, i do not know anything more. Can i measure the load with an current meter?

what can you say about the load?  what is it?  The arduino is not much help.

The load is a strip of LED lights.... If you want i can count them, if this will be of any help to figure out the load...

Yes, you want a H-bridge. That is the simplest way to make that "negative*" voltage.
But you can't just create a square wave and throw it blindly at a H-bridge, you have to be much more careful, otherwise you will cause short circuits and dissipate massive amounts of power.
You will need a "discrete" H-bridge where you have proper control over each transistor, and the best way of doing that is with discrete transistors (MOSFETs are best).
The important thing to remember though is than no transistor ever turns off or on instantaneously - so you have to add a "dead zone" into your waveform.  Turn one pair of MOSFETs off, then wait a moment, before turning the other pair on. Otherwise you get a brief overlap in the switching where massive currents can flow straight through everything as all the MOSFETs are turned on (or partially on) at the same time.
Some microcontrollers have programmable dead zones in their PWM outputs, but I am not sure if the AVR chips do - you'll have to check the datasheet - but it's not too hard to arrange a suitable waveform in software or using timers and interrupts (you could look at the tone() function and support code for some ideas for the latter).
The programming sequence, if you have 4 outputs H1/H2/L1/L2 for the HIGH and LOW sides of the H bridge pairs 1 and 2, would be:

Turn on H1 and L2
Pause
Turn off H1 and L2
Brief Pause
Turn on H2 and L1
Pause
Turn off H2 and L1
Brief Pause
Repeat

You haven't specified what your load is, but with an H-bridge it is important to remember that the output is not referenced directly to ground but ground alternates from side to side. If you want to properly isolate it from the Arduino ground a transformer can be used as the load to the H-bridge then use the output of the transformer to drive your real load. You can also use the transformer to change the output voltage (the ratio of windings is the same as the ratio of input to output voltage - so a 1:1 winding transformer will give the same voltage out as it gets in).

"Negative" only that the current flows the opposite way through the load, not an actual negative voltage WRT to Arduino GND.

Thank you so much for this comment! I have some quick questions and (i plan to really read about H-Bridges today). Unfortunately, at this moment the load is not clear to me... 1. Do you know if tone() supports dead zones in its PWM? 2. Should i stay away from ready solutions (like the L298) and rebuild the H-Bridge myself? If yes, i should make sure that the MOSFETS are within operating voltage right (36V)? 3. In the H-Bridge scenario, the initial pulse is PWM or constant voltage that the H-Bridge reverses polarity, and thus it creates an AC PWM? If it's PWM, should the frequency be double

of what i want? 4. How do i then step up the voltage to 36V (in both rails)? Does this come from the H-Bridge input? If yes, can i use a step down converter to use mains voltage to 36V that will feed the H-Bridge? Something like this perhaps? https://www.amazon.in/Electronicspices-LM2596-voltage-regulator-1-3-37V/dp/B08P7KT92B


text:
Methods of programming the Arduino
I took a look at a barebones Arduino schematic.
It had three different ways of programming the chip.

The first interface is for programming through SPI (For example with "Pocket AVR Programmer", or "USBTinyISP").
The second interface is for programming through an FTDI to USB module.
What is the third programming interface? It only has MOSI, MISO and SCK.
EDIT: This is a picture of the full schematic. Unfortunately, I could not find the link from which I downloaded it. I am sure it was from Github though.

Please include/link the full schematics. From what you posted, I can only say that the first two pin headers both connect to the same UART pins (RXD/TXD, making both the same UART programming interface, just with differently-shaped pin headers) and the third connects to the SPI pins of the chip -- but I would think that that pin header is there to connect SPI periphery/sensors, not for ICSP (in-circuit serial programming).

@orithena I updated the question with the full schematic.

Okay, that clears up the level of "barebone-ness" :)

JP2 and JP8 are both serial pin headers suitable for programming -- they connect to the same pins of the chip: RXD, TXD and RST. This is programming via UART: A bootloader software (which has to be "pre-burnt" in the chip's flash memory) is the first thing that is run after a reset (RST) signal. It waits a little moment for data to arrive on RXD. If data arrives, the bootloader goes into programming mode: the data is written to flash memory, making it the firmware to be executed after the next RST. (If no data arrives: well, then the firmware that already is there is executed.)
Programming the chip via JP4 would use "hardware-supported" programming interface via SPI, recognizeable by the pins MISO, MOSI and SCK. That is the only way to get the first bootloader into the flash memory. It also provides you with a way to flash and re-flash a firmware without a pre-burnt bootloader (making the bootloader space available to your firmware). That method is described in the ATmega328P datasheet, chapter 27.8 and is the primary method employed by "ISP programmer boards". You could use those from the Arduino IDE using the menu option "Upload using programmer".
If this "barebone Arduino" circuit is meant to use an ATmega328P with the Arduino bootloader, however, I would assume that JP4 is meant to provide a pin header for some SPI sensor module (even though you could program and even un-brick the chip using this interface).
NB: "FTDI" is a red herring here. One of the most-used ISP programmer boards employs an chip made by FTDI, so you could call this method "programming via FTDI" ... but a specific USB-to-Serial cable using an chip made by FTDI and an 1x5 pin header is also called an "FTDI cable". (For a while, FTDI made the best USB-to-Serial chips. Clones just did not work that reliable. Today, CH340G and CP2104 are reliable enough for hobby projects, but somehow, "FTDI" stuck as a name.)

Just adding https://docs.platformio.org/en/latest/platforms/atmelavr.html#upload-using-programmer for the platformio...

Thank you! I have one more question though. You said that JP4 is used for programming via an external programmer. However, I use the first pinout (JP2) with an external programmer (Sparkfun's Pocket AVR Programmer) that uses SPI communication protocol as an ISP (In System Programmer). So is there another protocol/interface being used with JP4?

@user1584421 That does not match the schematics you posted. JP2 and JP8 have the pins RXD und TXD, which points to an UART interface. JP4 has MISO, MOSI and SCK, which points to SPI interface. So either the schematics do not match the circuit you got in front of you, or you did use JP4 but remember using JP2, or the PocketAVR programmer has a method of detecting whether it should use UART or SPI that I don't know of (and is not described in its feature list).

The 2x2 pin JP2 is connected to the Atmel 16U2 or 32U2 processor (whichever the manufacturer used) which provides the USB I/O interface to/from the Atmel 328p, the one we usually consider to be the Uno's processor. When pins are actually installed on that pad, jumpers may be placed across either or both pairs to connect the xxU2's pin-4 to pin-6, and/or pin-5 to pin-7, which connect to that processor's interrupts (numbered the same as those pins).
My searches have not yielded any answer to the question of why it was provided, other than to suggest that they may have been intended for a feature that was never implemented. You can see JP2 and its connections to the xxU2 processor in the center of this schematic.
Update:
I was looking at the 3-pin connector(?) marked '???' in your question, and JP4 on the schematic in your update. Since your schematic does not show the xxU2 chip, and the connections of '???' are marked D11, D12, and D13, I'm going to guess instead that these are either auxilliary pins to access the 328's SPI interface, or is showing half of the ICSP hardware programming interface (the 3x2 pin block just above the '328 on the schematic I linked).

Thank you very much! I updated the question with the full schematic, if that is of any help to you.


text:
Detecting the stop of execution of a timer interrupt
This is my timer interrupt:
void setup() {
  attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), count_time_of_k_pulses, RISING);

  pinMode(OE_BAR_PIN, OUTPUT);
  pinMode(S0_PIN, OUTPUT);
  pinMode(S1_PIN, OUTPUT);
  pinMode(S2_PIN, OUTPUT);

  TIMER1_init();

  Serial.begin(BAUD_RATE);
  while (! Serial);
}

void count_time_of_k_pulses()
{
  if (interrupts_enabled)
  {
    pulse_counter++;

    if (pulse_counter == 1)
      TIMER1_start();

    if (pulse_counter == number_of_samples)
    {
      TIMER1_stop();

      measurement_finished = true;
      interrupts_enabled = false;
    }
  }
}

The logic behind this is that it will receive signals from a digital circuit on an arduino pin.
When it receives the first signal it will start a timer.
After it receives as many signals, as set by number_of_samples, it will stop.
This information will help my identify the resitance of a resistor.
There is a problem though.
Imagine that while the timer interrupt runs (signals are coming and the timer is running), i remove one pin from the resistor and the signal stops arriving at the arduino pin.
Then the program will lock, because it will be stuck inside the timer interrupt, constantly waiting for  if (pulse_counter == number_of_samples) to be satisfied.
So is there a way, while inside the timer interrupt, to detect when the timer interrupt is stuck, without using more timers?
EDIT: BELOW IS THE WHOLE CODE
/***** CONSTANTS *****/
const int BAUD_RATE = 9600;
const int INTERRUPT_PIN = 3;
const int S0_PIN = 4;
const int S1_PIN = 5;
const int S2_PIN = 6;
const int OE_BAR_PIN = 22;
const int NUM_OF_SENSORS = 8;

/***** ANALOG CIRCUIT CONSTANTS *****/
const double CAPACITOR_VALUE = 400; //pF
const double GAIN_VALUE = 3.5222672065;
const double R_BIAS_VALUE = 98.7; //kΩ

/***** GLOBAL VARIABLES *****/
int number_of_samples = 500;
int sensor_coord;
boolean full_mode = false;

unsigned long overflows = 0;
unsigned long ticks = 0;
double period = 0;

//variables for determining if a resistance cannot be measured
unsigned long timestamp = 0;
unsigned long measurement_timeout = 5000;  //5 seconds is the timeout time
boolean sensor_corruption[8]; //each element of the array is the sensor info. If false, resistance is working. If it's true, resistance is open.
boolean ISR_unavailable = false; //this flag is raised, when the ISR does not run, because no signal comes from the circuit, because resistance is open circuit

//variables that get changed inside the ISR
volatile int pulse_counter = 0;
volatile boolean interrupts_enabled = false;
volatile boolean measurement_finished = false;

void setup()
{
  attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), count_time_of_k_pulses, RISING);

  digitalWrite(OE_BAR_PIN, HIGH);
  pinMode(OE_BAR_PIN, OUTPUT);
  pinMode(S0_PIN, OUTPUT);
  pinMode(S1_PIN, OUTPUT);
  pinMode(S2_PIN, OUTPUT);

  TIMER1_init();

  Serial.begin(BAUD_RATE);
  while (! Serial);

  for (int i=0; i<=7; i++)
  {
    sensor_corruption[i] = false; // false means it's working ok. true means it's open-circuit (or cannot be read anyway)
  }
}

void loop()
{

  //CODE FOR SERIAL INTERFACE (RESISTANCE SELECTION)
  if (Serial.available())
  {
    /***** DEFINE MEASUREMENT MODE *****/
    String input = Serial.readString();
    if (input[0] == 'r' && interrupts_enabled == false)
    {
      if (input[1] == 'f')
      {
        full_mode = true;
        sensor_coord = 0;
      } else
        sensor_coord = input[2] - '0';  // r *SPACE* [0-7]

      select_sensor();

      pulse_counter = 0;
      TIMER1_clear();

      interrupts_enabled = true;
    }
  }

  //no_interrupts area-------
  // TIMEOUT CODE HERE. TO DETERMINE IF A RESISTANCE IS OPEN CIRCUITED
  if(interrupts_enabled && millis() - timestamp > measurement_timeout)
  {
    sensor_corruption[sensor_coord] = true; //label the resistance (indicated by sensor_coord) as true in the boolean array. this means it's open circuited (no signal from circuit)
    measurement_finished = true; ///we set this to true, so we can enter the next block of code
    ISR_unavailable = true; //small flag in order to not do calculations (some lines below) in case of an open circuit
  }
  //-------------------------

  if (measurement_finished)
  {

    if (!ISR_unavailable) //only make these calcs, if the ISR_unavailable is false. in other words if the ISR runs (so resistance is read)
    {
        ticks = (overflows * 65536) + TCNT1;
        period = (ticks * 0.0625) / (number_of_samples - 1);
    }

      TIMER1_print_results();
      ISR_unavailable = false;
      if (full_mode)
      {
        sensor_coord++;
        select_sensor();
        pulse_counter = 0;
        TIMER1_clear();
        interrupts_enabled = true;

        if (sensor_coord == NUM_OF_SENSORS)
        {
          full_mode = false;
          interrupts_enabled = false;

        }

        measurement_finished = false;
        timestamp = millis();

      }

       pulse_counter = 0;
       TIMER1_clear();
       interrupts_enabled = true; //NEW
       measurement_finished = false; // delete this bs
       timestamp = millis();

  }
 }

/***** INTERRUPT ROUTINES *****/

void count_time_of_k_pulses()
{
  if (interrupts_enabled)
  {
    pulse_counter++;

    if (pulse_counter == 1)
      TIMER1_start();

    if (pulse_counter == number_of_samples)
    {
      TIMER1_stop();

      measurement_finished = true;
      interrupts_enabled = false;
    }
  }
}

ISR (TIMER1_OVF_vect)
{
  overflows++;
}

/***** FUNCTION FOR SENSOR SELECTION *****/

void select_sensor()
{
  digitalWrite(OE_BAR_PIN, HIGH);
  digitalWrite(S2_PIN, ((sensor_coord & 4) == 4) ? HIGH : LOW );
  digitalWrite(S1_PIN, ((sensor_coord & 2) == 2) ? HIGH : LOW );
  digitalWrite(S0_PIN, ((sensor_coord & 1) == 1) ? HIGH : LOW );
  digitalWrite(OE_BAR_PIN, LOW);
}

/***** TIMER1 FUNCTIONS *****/

void TIMER1_init()
{
  TCCR1A  = 0;
  TCCR1B  = 0;
  TIMSK1 |= (1 << TOIE1);
}

void TIMER1_start()
{
   TCCR1B |= (0 << CS12) | (0 << CS11) | (1 << CS10);
}

void TIMER1_stop()
{
  TCCR1B  = 0;
}

void TIMER1_clear()
{
  TCNT1     = 0;
  overflows = 0;
}

void TIMER1_print_results()
{
  Serial.println("----------------------------------------");
  Serial.print("SENSOR COORDINATE         = ");
  Serial.println(sensor_coord);

  if (sensor_corruption[sensor_coord])
  {
    Serial.println("This resistance is open circuited!!!");
  }
  else
  {
    Serial.print("NUMBER OF PULSES MEASURED = ");
    Serial.println(pulse_counter);

    Serial.print("TIMER1 VALUE              = ");
    Serial.println(TCNT1);

    Serial.print("TIMER1 OVERFLOWS          = ");
    Serial.println(overflows);

    Serial.print("TICKS                     = ");
    Serial.println(ticks);

    Serial.print("MEASURED PERIOD           = ");
    Serial.print(period);
    Serial.println(" US");

    Serial.print("MEASURED RESISTANCE       = ");
    double resistanse = ((period * GAIN_VALUE * 1000) / (4 * CAPACITOR_VALUE)) - R_BIAS_VALUE; //kΩ
    Serial.print(resistanse);
    Serial.println(" kΩ");

    Serial.println("----------------------------------------");
  }
}

Is that your ISR? Then where should it get stuck? I don't see any while loops or similar. Also: What interrupts are you using here? I would assume that this ISR is used with an external interrupt pin. It starts a timer to measure the time of a pulse. Please provide a full working code. We need to see the whole code situation.

One moment, you already asked a question about that code some time ago: here. The problem seems quite similar, so I immediately thought about the same solution principle using millis(). Or do you need to use Timer0 somewhere else in your new code revision, so that you cannot use millis()?

Please, note that count_time_of_k_pulses() is not a timer interrupt. It's the handler of an external interrupt.

I updated the code. Yes, the code is the same from that thread. Although the problem is different. In that problem (which i solved thatnks to you guys) i wanted to detect when the timer interrupt does not run, because it does not get triggered. In this new problem, i am inside the interrupt, but for some reason the signal stops arriving, while inside (before i reach the number_of_samples). So the program is stuck inside the iterrupt, waiting for the signal to get equal the number_of_samples.

It won't be stuck inside any interrupt.  It will fire the interrupt and exit and then if the signal is gone it won't fire the interrupt again.  So the easiest method may be to just keep track in loop of how long it has been since the last interrupt.  If it has been a long time then the signal must be lost.  You just need one more unsigned long in the ISR to keep track of the millis time of the last interrupt.

I updated the post with the whole code. If you see in the comments labeled as "no interrupts area", is where i do calculations (as advised from my other post) in order to figure out when a timer interrupt does not run, thus there is no signal in the input pins, thus reistance is open circuited. But now when i do a continuous measurement of a working resistance and THEN i open circuit it, the program stops. This is why i assumed it stops inside the interrupt function. Could you modify the code with your one liner, to see your approach better please?

@Delta_G I don't think this is the case "if the signal is gone it won't fire the interrupt again", because if you see my whole code which i posted, i already do that (check the comments for 'no interrupts area'). If there is no signal then that resistance gets labeled and the appropriate print is shown. But when i measure continuously a resistance and then i open circuit it, nothing happens. The program stucks. If no signal arrived, then the 'no interrupts area' code should run again. But in my case, it doesn't happen.

Then you have a basic misunderstanding of how interrupts work.  The code can never ever become trapped in that interrupt.  Think about this, your timeout code in the no interrupts section, where does timestamp get a value?  That should tell you when the last interrupt fired, so it seems to me like it should get a value in the ISR.

So what seems to be the problem here?

I don't know.  Instead of giving us the symptoms of the problem you told us why you thought it was failing.  But your reasoning is not right.  The ISR will only be entered when there is a rising edge on the pin and then it runs very fast and exits.  It can never be hung up in the ISR.  Perhaps you should describe what the actual problem is.  To me it looks like you just need to take a time stamp from millis in the ISR and in your loop you can compare that to see how long it has been since the interrupt fired.  If it has been a long time then you have lost the signal and can act appropriately.

Mhh, I cannot see the code portion, where the code gets stuck. I agree with @Delta_G that it cannot get stuck in the ISR, since there are only if statements, which cannot block the code executing. You can test this by turning on an extra LED at the start of the ISR and turning it off at the end (with direct port manipulation to be fast enough). Please also add a simple blink code from the BlinkWithoutDelay example to the loop() function. That way we could prove, if the loop still runs

You can use the described LED principle to track down the problematic code part, if the code really gets stuck somewhere

I get the LED inside the ISR, but the BlinkWithoutDelay ses these lines:  if (currentMillis - previousMillis >= interval) {}. I have somethign similar in my code, so how do i combine those? Do i need new variables to store the currentMillis? If i use what i have, then the LED will only light up inside the 'No interrupts area' (as labeled in my comments inside the code).


text:
Sending serial data to arduino, while an operation triggered from serial data is underway
I have this snippet of code:
 if (Serial.available())
 {
    /***** DEFINE MEASUREMENT MODE *****/
    String input = Serial.readString();
    if (input[0] == 'r' && interrupts_enabled == false)
    {
      if (input[1] == 'f')
      {
        full_mode = true;
        sensor_coord = 0;
      } else
        sensor_coord = input[2] - '0';  // r *SPACE* [0-7]

      select_sensor();

      pulse_counter = 0;
      TIMER1_clear();

      interrupts_enabled = true;
    } //first if ends here
    else if (input[0] == 'C' || input[0] == 'c')
    {
      interrupts_enabled = false;  //If the user types 'C' OR 'c', stop the measurement
    }
 }

So when i send 'rf' to the arduino, a measurement to all my sensors starts hapening indefinetely.
(There is another mode as well, typing 'r 0' will start an infinite measurement on the first sensor.)
When all the eight sensors, are measured, it will start from the beggining.
I wanted to be able to stop this operation when i typed a command in the serial.
This is why i addded the  else if (input[0] == 'C' || input[0] == 'c') portion.
So that, when the infinite measurement occurs and i press 'C', it is supposed to stop.
But it didn't work.
Not only that, but if i am in full mode and i then press another serial command, such as previously mentioned 'r 0'. , nothing happens as well.
So what i am asking is:
Is there a way to stop an operation triggered frmo serial that is underway?
And by stopping it, i mean from serial as well.
Perhaps, when an operation is uderway taht is triggered from serial, it cannot be stopped until the operation is finished?
Maybe it has to do something with when i have already typed 'rf' and sometime later i type 'C', maybe that 'C' is no longer on position input[0] of the serial buffer?
EDIT: This is the full code:
/***** CONSTANTS *****/
const int BAUD_RATE = 9600;
const int INTERRUPT_PIN = 3;
const int S0_PIN = 4;
const int S1_PIN = 5;
const int S2_PIN = 6;
const int OE_BAR_PIN = 22;
const int NUM_OF_SENSORS = 8;

/***** ANALOG CIRCUIT CONSTANTS *****/
const double CAPACITOR_VALUE = 400; //pF
const double GAIN_VALUE = 3.5222672065;
const double R_BIAS_VALUE = 98.7; //kΩ

/***** GLOBAL VARIABLES *****/
int number_of_samples = 500;
int sensor_coord;
boolean full_mode = false;

unsigned long overflows = 0;
unsigned long ticks = 0;
double period = 0;

//variables for determining if a resistance cannot be measured !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
unsigned long timestamp = 0;
unsigned long measurement_timeout = 5000;  //5 seconds is the timeout time
boolean sensor_corruption[8]; //each element of the array is the sensor info. If false, resistance is working. If it's true, resistance is open.
boolean ISR_unavailable = false; //this flag is raised, when the ISR does not run, because no signal comes from the circuit, because resistance is open circuit

//variables that get changed inside the ISR - thus are declared volatile!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
volatile int pulse_counter = 0;
volatile boolean interrupts_enabled = false;
volatile boolean measurement_finished = false;

void setup()
{
  attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), count_time_of_k_pulses, RISING);

  digitalWrite(OE_BAR_PIN, HIGH);
  pinMode(OE_BAR_PIN, OUTPUT);
  pinMode(S0_PIN, OUTPUT);
  pinMode(S1_PIN, OUTPUT);
  pinMode(S2_PIN, OUTPUT);

  TIMER1_init();

  Serial.begin(BAUD_RATE);
  while (! Serial);

  //Initializing all array elements to false!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  for (int i=0; i<=7; i++)
  {
    sensor_corruption[i] = false; // false means it's working ok. true means it's open-circuit (or cannot be read anyway)
  }
}

void loop()
{

  //CODE FOR SERIAL INTERFACE (RESISTANCE SELECTION)
  if (Serial.available())
  {
    /***** DEFINE MEASUREMENT MODE *****/
    String input = Serial.readString();
    if (input[0] == 'r' && interrupts_enabled == false)
    {
      if (input[1] == 'f')
      {
        full_mode = true;
        sensor_coord = 0;
      } else
        sensor_coord = input[2] - '0';  // r *SPACE* [0-7]

      select_sensor();

      pulse_counter = 0;
      TIMER1_clear();

      interrupts_enabled = true;
    } //first if ends here
    else if (input[0] == 'C' || input[0] == 'c') //not sure if it's case sensitive, but just to make sure i added both capitals and lower-case
    {
      interrupts_enabled = false;  //If the user types 'C' OR 'c', stop the measurement
    }
  } //Serial.available portion ends here

  //no_interrupts area-------
  // TIMEOUT CODE HERE. TO DETERMINE IF A RESISTANCE IS OPEN CIRCUITED!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  if(interrupts_enabled && millis() - timestamp > measurement_timeout)
  {
    sensor_corruption[sensor_coord] = true; //label the resistance (indicated by sensor_coord) as true in the boolean array. this means it's open circuited (no signal from circuit)
    measurement_finished = true; ///we set this to true, so we can enter the next block of code
    ISR_unavailable = true; //small flag in order to not do calculations (some lines below) in case of an open circuit
  }
  //-------------------------

  if (measurement_finished)
  {

    if (!ISR_unavailable) //only make these calcs, if the ISR_unavailable is false. in other words if the ISR runs (so resistance is read)!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    {
        ticks = (overflows * 65536) + TCNT1;
        period = (ticks * 0.0625) / (number_of_samples - 1);

        //RESET THE SENSOR CORRUPTION TO FALSE HERE!!!!!!!!!!!!!!!!!!!!!!!!!!!
        sensor_corruption[sensor_coord] = false;
        // if the res goes from open-circuited to working, this will restore the array so it's not labelled as open-circuited anymore
        // THE PROBLEM IS: THE FIRST MEASUREMENT AFTER IT GOES FROM OPEN -> CLOSED IS CORRUPTED. IT'S ALWAYS TO HIGH
        // MAYBE IT'S CAUSED BY THE FRICTION OF WIRES????
    }

      TIMER1_print_results();
      ISR_unavailable = false; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! reset ISR_unavailable for the next measurement
      if (full_mode)
      {
        sensor_coord++;
        select_sensor();
        //pulse_counter = 0;
        //TIMER1_clear();
        //interrupts_enabled = true; //necessary in full mode. useless if res is open-circuit, as this value never changed. but it doesn't hurt

        if (sensor_coord == NUM_OF_SENSORS)
        {

          sensor_coord = 0; //back from the beginning !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
          // full_mode = false; //no i want to continue having full mode
          // interrupts_enabled = false; //no, i want to continue having interrupts

          //after i measure all 8 resistances, the interrupt_enabled will be false. so code will be stuck in my no_interrupts area
          //this means the no_interrupts() area should run only when interrupts_enabled is true

          //remove the full mode line and reset sensor coord
        }

        /* We only enter the block of code we are now, when a measurement has happened (or when the no_interrupts
        area fired).
        We know that a measurement happened because the 'measurement_finished' variable is set by the interrupt
        (or set by the no_interrupts area, in order to enter the block we are now).
        But we ONLY want to enter the block we are now, when a measurement is finished, in order to process it.
        So now, that we did process it, in the end of this block, we have to reset the value.
        So we set measurement_finished to false, in order to not enter the block we are now, unless a new
        measurement has occured (or the no_interrupts area fired).
         */
        //measurement_finished = false;
        //timestamp = millis();  //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        //if i measure 1 resistance. here, interrupts_enabled will be false. this means no interupts.
        //this means my no_interrupts code will run. so it will always print. so no_interrupts area should run only whe interrupts_enabled is true
      }

      //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
       pulse_counter = 0;
       TIMER1_clear();
       interrupts_enabled = true;
       measurement_finished = false;
       timestamp = millis();  // refresh timer !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

  }
 } //loop ends

/***** INTERRUPT ROUTINES *****/

void count_time_of_k_pulses()
{
  if (interrupts_enabled)
  {
    pulse_counter++;

    if (pulse_counter == 1)
      TIMER1_start();

    if (pulse_counter == number_of_samples)
    {
      TIMER1_stop();

      measurement_finished = true;
      interrupts_enabled = false;
    }
  }
}

ISR (TIMER1_OVF_vect)
{
  overflows++;
}

/***** FUNCTION FOR SENSOR SELECTION *****/

void select_sensor()
{
  digitalWrite(OE_BAR_PIN, HIGH);
  digitalWrite(S2_PIN, ((sensor_coord & 4) == 4) ? HIGH : LOW );
  digitalWrite(S1_PIN, ((sensor_coord & 2) == 2) ? HIGH : LOW );
  digitalWrite(S0_PIN, ((sensor_coord & 1) == 1) ? HIGH : LOW );
  digitalWrite(OE_BAR_PIN, LOW);
}

/***** TIMER1 FUNCTIONS (MODIFIED) *****/

void TIMER1_init()
{
  TCCR1A  = 0;
  TCCR1B  = 0;
  TIMSK1 |= (1 << TOIE1);
}

void TIMER1_start()
{
   TCCR1B |= (0 << CS12) | (0 << CS11) | (1 << CS10);
}

void TIMER1_stop()
{
  TCCR1B  = 0;
}

void TIMER1_clear()
{
  TCNT1     = 0;
  overflows = 0;
}

void TIMER1_print_results()
{
  Serial.println("----------------------------------------");
  Serial.print("SENSOR COORDINATE         = ");
  Serial.println(sensor_coord);

  //Added the if-else statement, to cover the possibility of open circuited resistance !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  if (sensor_corruption[sensor_coord])
  {
    Serial.println("This resistance is open circuited!!!");
  }
  else
  {
    Serial.print("NUMBER OF PULSES MEASURED = ");
    Serial.println(pulse_counter);

    Serial.print("TIMER1 VALUE              = ");
    Serial.println(TCNT1);

    Serial.print("TIMER1 OVERFLOWS          = ");
    Serial.println(overflows);

    Serial.print("TICKS                     = ");
    Serial.println(ticks);

    Serial.print("MEASURED PERIOD           = ");
    Serial.print(period);
    Serial.println(" US");

    Serial.print("MEASURED RESISTANCE       = ");
    double resistanse = ((period * GAIN_VALUE * 1000) / (4 * CAPACITOR_VALUE)) - R_BIAS_VALUE; //kΩ
    Serial.print(resistanse);
    Serial.println(" kΩ");

    Serial.println("----------------------------------------");
  }
}

You need to check serial inbetween of your infinite measurement loop. readString() is a bad choice for that, because it uses a 1s timeout. Please show us your full code or - if its too long - a minimal working example

I edited the question with the full code.

But the end of the loop, wont the execution always flow to the part where there is the Serial.available() check?

Maybe i should place the interrupts_enaled not at the end of the loop, but at the beginning? Because maybw now they are always enabled, so maybe my program doesnt have time to access the serial chekcing part.

why do you need to use interrupts?


text:
In Linux, how do I get this Arduino library to work
In Linux Fedora 20 Arduino I want to use the Timer library from here, from which  I have downloaded the folder Timer-master.zip, but, when I try to import it, I get the Arduino message that it cannot be imported because its name includes characters other than plain ACSII letters and numbers. I have tried copying the file to Timermaster.zip and importing that instead, but still got exactly the same failure message.
Please, how do I get out of this impasse?

What's causing the problem is that the folder name inside the zip has a hyphen in it, just extract the folder from this zip and rename it to timer instead of timer-master. I just imported it on Fedora 20.

#'itchyzombie, Thanks for that prompt and excellent answer. I have done that and, as you say, it works. A day wasted in frustrating floundering, but a nice end result


text:
One LED being constant and another blinking
I have just started my first project. I got through with 2 periodically blinking LEDs. Now I want one LED (blue) to be lit constantly and the other (red) to be blinking as before. Can anyone help me with this?
This is my code for blinking LEDs.
int red_led = 4;
int blue_led = 3;

void setup() {

  pinMode(red_led, OUTPUT);

  pinMode(blue_led, OUTPUT);

}

void loop() {

  digitalWrite(blue_led, LOW);

  digitalWrite(red_led, HIGH);

  delay(1000);

  digitalWrite(blue_led, HIGH);

  digitalWrite(red_led, LOW);

  delay(1000);

 }

So you do not want one of your LEDs to turn off?  The answer will depend on how your LEDs are wired.

What had you tried before posting the question? Did you at all understand the code you posted above?

The wonderful thing about the Arduino is that it hides a lot of the programming "noise" and lets you concentrate on the code that is actually doing the work. Part of the joy of programming is starting to "own" the code and being able to make it do what you want.
The answer here isn't too hard, and I'm sure that many could answer your question – but I think you might enjoy the experience more (and you would earn more respect) if you make a stab at it yourself first. Or if you already have, tell us what you've tried and what happened when you tried it. That will help us help you to see not only the steps necessary, but the concepts that will enable you to branch off on your own.
Do you know what is causing the LEDs to blink in your current code?

The LEDs get forward-biased with positive supply at anode and ground at cathode: that makes them getting lit. In the code, the infinite loop forces the consecutive LEDs to glow for 1000ms and then going to "off" state for 1000ms.

So, if you move the blue_led control out of the infinite loop() and into setup() you get what you want.

Remember that the setup() function runs once, and then the loop() function runs forever.  So to keep the blue LED light, simply turn it on, but never off.  The code for the red LED remains unchanged.
const int red_led  = 4;
const int blue_led = 3;

void setup()
{
    pinMode(red_led, OUTPUT);
    pinMode(blue_led, OUTPUT);

    digitalWrite(blue_led, HIGH);  // LED On
}

void loop()
{
    digitalWrite(red_led, HIGH);  // LED On
    delay(1000);
    digitalWrite(red_led, LOW);   // LED Off
    delay(1000);
}


text:
invalid conversion from 'const char*' to 'char*' [-fpermissive]
With WebSocket various messages arrive.
Task:

Find message "setBrightness: 15"
Extract the value "15" from the message (the value can be any)
Convert this value to uint8_t

My code:
#include <string.h>

String payload_str = "setBrightness: 15"; // WebSocket message
const char* payload = payload_str.c_str(); // Convert string to char

const char* value; // Message value
uint8_t brightness;

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

  if(strncmp(payload, "setBri", 6) == 0) { // Search message
   value = strtok(payload, " ");
   value = strtok(NULL," "); // Get value (15)
   brightness = (uint8_t)atoi(value); // Convert to uint8_t
  }
}

void loop() {}

Compilling error:

error: invalid conversion from 'const char*' to 'char*' [-fpermissive]
error:   initializing argument 1 of 'char* strtok(char*, const char*)' [-fpermissive]

Maybe I'm doing it completely wrong and not safe. How can this be fixed?

strtok modifies the char buffer entered as first parameter. It replaces the delimiters with terminating zeros. To parse a constant string with strtok, you must first copy it into a working char buffer.
For your test you can initialize a char array as in following example.
char payload[] = "setBrightness: 15";

uint8_t brightness;

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

  if(strncmp(payload, "setBri", 6) == 0) { // Search message
   strtok(payload, " ");
   const char* tok = strtok(NULL," "); // Get value (15)
   brightness = (uint8_t) atoi(tok); // Convert to uint8_t
  }
}

void loop() {}

if you know the 'name' part of the name:value string, you can skip it for atoi this way:
brightness = (uint8_t) atoi(payload + strlen("setBrightness: "));
(strlen("setBrightness: " will be evaluated at compile time to a constant number)
const char payload[] = "setBrightness: 15";

uint8_t brightness;

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

  if(strncmp(payload, "setBri", 6) == 0) { // Search message
     brightness = (uint8_t) atoi(payload + strlen("setBrightness: ")); // Convert to uint8_t
  }
}

void loop() {}

Thanks for the help! I will try today and say the result.


text:
Will Arduino Mega support stepper motor NEMA 24, NEMA 34
Will two stepper motor NEMA 24, 10 kg cm, 2. 8 amp, 24 vdc work at same time on Arduino Mega and when they stop stepper motor NEMA 34, 34 kg cm, 4amp, 24 VDC will work or not? This is my first project please help me to choose the controller.

Properly running multiple stepper motors is a bit challenging if they need to move at the same time, but any Arduino-based 3d printer firmware manages to do so.  If only one needs to move at time then it is far simpler.  Selecting the power drivers for a given motor is not an Arduino question and therefore not on topic here.

I'm using 4x Nema 24s for a CNC project of mine.  They only need a couple of signals/pins each from the Arduino to work, the rest is up to the stepper controller board.
For my steppers, I'm using TB6600s, since I need ~3.5 amps per motor/channel.  There are others out there that'll work, but it's what I saw other people at my maker space using.
Nema34s would probably need higher rated amps, so that would determine what controller you need to use.
In fact, every motor is rated for different amps and voltages, so that will always determine what motor controller you use.  Since you need a higher voltage to run the motor controllers than the Arduino, using a separate stepping power supply is a requirement.
The Arduino gets hooked to the step/pulse and direction pins of the motor controller and the other pins on the motor controller go elsewhere.  The CNC motor controller shields you normally see are for lower amp controllers and do most of the pin connections for you.  With the higher amperage motors, you'll have to do this yourself.
When you determine what motor controller you are going to use, find a wiring diagram for it (and maybe a friend) to figure out how it should be wired.


text:
Use of array in case statement
I want to know how I can use case statement for each array.
Below is my code:
int incomingByte = 0;

void setup()
{
  Serial.begin(115200);
  for (int thisPin = 2; thisPin < 6; thisPin++)
  {
    pinMode(thisPin, OUTPUT);
  }
}

void loop()
{
  int button1[] = {0xFF, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05};
  int button2[] = {0xFF, 0x04, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06};
  int button3[] = {0xFF, 0x04, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08};
  int button4[] = {0xFF, 0x04, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C};

  if (Serial.available() > 0)
  {
    incomingByte = Serial.read();
  }

  switch (incomingByte)
  {
    case button1:
      digitalWrite(2, HIGH);
      break;
    case button2:
      digitalWrite(3, HIGH);
      break;
    case button3:
      digitalWrite(4, HIGH);
      break;
    case button4:
      digitalWrite(5, HIGH);
      break;
    default:
      for (int thisPin = 2; thisPin < 6; thisPin++)
      {
        digitalWrite(thisPin, LOW);
      }
  }
}

Not checked/compiled, just to give an idea.
/* One button message is 12 bytes, it is assumed that all received messages are 12 bytes. If note, you have to check later differently. */
#define MSG_SIZE 11
byte incomingBytes[MSG_SIZE]; /* Storage for 11 bytes */
byte index = 0; /* Current byte to set within incomingBytes */

void setup()
{
  Serial.begin(115200);
  for (int thisPin = 2; thisPin < 6; thisPin++)
  {
    pinMode(thisPin, OUTPUT);
  }
}

void loop()
{
  if (Serial.available() > 0)
  {
    /* Store the next incoming byte. Assume 0xFF is the start of a message. */
    byte incoming_byte = Serial.read();
    if (incoming_byte == 0xFF)
    {
      index = 0;
    }

    incomingBytes[index] = incoming_byte;
    index++;
    if (index >= MSG_SIZE)
    {
       check_message();
       index = 0;
    }
  }
}

/* Checks which button is pressed and performs an action based on the
pressed button. */
void check_message()
{
  case check_button_pressed())
  {
    case 1:
      digitalWrite(2, HIGH);
      break;
    case 2:
      digitalWrite(3, HIGH);
      break;
    case 3:
      digitalWrite(4, HIGH);
      break;
    case 4:
      digitalWrite(5, HIGH);
      break;
    default:
      for (int thisPin = 2; thisPin < 6; thisPin++)
      {
        digitalWrite(thisPin, LOW);
      }
  }
}

/* Checks which button is pressed by comparing 11 incoming bytes to the
four buttons to be checked. Returns -1 for an illegal message/unsupported
button and 1, 2, 3 or 4 for the pressed button. */
int check_button_pressed()
{
  int button_pressed = -1;
  if ((incomingBytes[0] == 0xFF) &&
      (incomingBytes[1] == 0x04) &&
      (incomingBytes[3] == 0x00) &&
      (incomingBytes[4] == 0x00) &&
      (incomingBytes[5] == 0x00) &&
      (incomingBytes[6] == 0x00) &&
      (incomingBytes[7] == 0x00) &&
      (incomingBytes[8] == 0x00) &&
      (incomingBytes[9] == 0x00))
  {
    if ((incomingBytes[2] == 0x01) && (incomingBytes[10] == 0x05))
    {
      button_pressed = 1;
    }
    else if ((incomingBytes[2] == 0x02) && (incomingBytes[10] == 0x06))
    {
      button_pressed = 2;
    }
    else if ((incomingBytes[2] == 0x04) && (incomingBytes[10] == 0x08))
    {
      button_pressed = 3;
    }
    else if ((incomingBytes[2] == 0x08) && (incomingBytes[10] == 0x0C))
    {
      button_pressed = 4;
    }
  }
  return button_pressed;
}

I'd add something to explicitly re-sync the stream when 0xFF is received, to handle variable length messages and cases where the serial connection is established in mid-message, but otherwise this is a good approach.

True, this is in case all messages are same length. But I don't know what the start of a message is, probably 0xFF. If so, if character is encounter, set Index to 0

@RussellBorogove I adapted the code for it.

yw ... if it is helpful, you can upvote the helpful answers, and select one which you consider best to answer your question (and press accept).

case doesn't work like that; it can only switch on a single integer. Are you trying to pattern-match those sequences of bytes? You'll have to use some sort of state machine instead, keeping track of what bytes you've received and where in the expected pattern you are.

Can you give me some hints? I am a newbie and i don't know much about Arduino. Thanks