text:
"stray '/302' in program error" when compiling
For some weird reason, the following code doesn't compile. I get a "stray '\302' in program" error around volatile unsigned int encoderPos = 0;, and I have no idea what the issue is. I've been trying to figure this out for over 40min, and nothing works. It doesn't make any sense
#include <U8g2lib.h>
#include <SPI.h>

//Pin definitions:

const int control_PWM = A3; //PWM output for the delay

const int btn_1 = 1; //Button for mode 1
const int btn_2 = 4; //Button for mode 2
const int btn_3 = 5; //Button for mode 3

const int r_A = 2; //Rotary encoder A's data
const int r_B = 3; //Rotary encoder A's data
const int r_SW = 0; //Rotary encoder's button data

const int oled_CLK = 9; //SPI cloack
const int oled_MOSI = 8; //MOSI pin
const int oled_CS = 7; //Chip Select pin
const int oled_DC = 6; //OLED's D/C pin
U8G2_SH1106_128X64_NONAME_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8);

int mode = 1; //1: RGB, 2: HSL, 3: Distance control
int value_selection = 1; //Actual value selectrion
int value1 = 0; //red in mode 1; tint in mode 2
int value2 = 0; ////green in mode 1; saturation in mode 2
int value3 = 0; //blue in mode 1; luminosity in mode 2

volatile unsigned int encoderPos = 0;  // rotary encoder's current position
unsigned int lastReportedPos = 1;   // rotary encoder's previous position
static boolean rotating=false;      // is the encoder activity status

// interrupter variables
boolean A_set = false;
boolean B_set = false;
boolean A_change = false;
boolean B_change= false;
void setup() {

}

void loop() {
}

What IDE version?

Could you please edit your question to include the exact error message.

@canadiancyborg: Your edit obscured the problem.

@IgnacioVazquez-Abrams I just translated the french comments to english, how did it change anything?

@canadiancyborg: You removed the non-ASCII characters in the source, which were the cause of the error.

@IgnacioVazquez-Abrams wait, so non-ASCII characters in comments also affect the program?

0302 is 0xc2. Somewhere in your source you have one or more non-breaking spaces (0xa0) encoded in UTF-8 (0xc2 0xa0). Use od or a similar tool to find them, and then replace them with normal spaces. Since you have non-ASCII Latin-1 characters in your source, those characters are encoded as two bytes with the first being 0xc2 or 0xc3. Remove all non-ASCII characters before proceeding.

You can probably just copy the code from your post and past it over the original code in the IDE. As I can't detect any weird characters in the text above (I think browser replace NBSPs with regular spaces). Invisible characters can be quite a pain for some compilers.

One cause of the /(302) error is copy and paste code from a word processor. You have ASCII codes copied that add spaces, etc to your code. Go through each identified line and remove any extra spaces at the beginning and end of any identified line. Then, (Arduino IDE) go to TOOLS, Auto Format. At least, this cleared up the problem for me.


text:
How to animate a LED Strip via wifi?
I'm remotely connecting my phone to an arduino MKR1000 via wifi, and sending data via HTTP GET (so to switch on the debug LED, I just need to navigate to http://192.168.1.1/debug/H, for example). Now, I want to be able to remotely send animations to an RGBW led strip.
Ideally, I would have a simple keyframe based protocol such as:
    http://192.168.1.1/anim/(keytime in ms):R,G,B,W+(keytimeinms) etc...
So for example, to animate from white to red in 500ms, I would navigate to:
    http://192.168.1.1/anim/0:255,255,255,255+500:255,0,0,0
Is this the best way to remotely send animations to my arduino? How should I implement this on the arduino side in the most ressource-efficient way possible? I don't even know where to start :/
For the moment, on the arduino side, I've got a keyframe class and an array of those keyframes representing the animation.

Start with something. Worry about making it efficient after you've figured out how to make it at all.

I'm actually working on such a thing (https://github.com/Paul-Ver/OpenLedstrip). Though it's far from finished and may focus on other points of such a LED driver, but you can check out the HTTP message handling.

I'm also using "HUE" instead of "RGB", which makes it easier for a user to select a color (with a slider, going through all hue's). I believe that will make animating a fade much easier. You simply increase/decrease the hue with set steps over time, until you reach the set hue. And same can be done for the brightness.

Ignacio's comment, “Start with something. Worry about making it efficient after you've figured out how to make it at all”, is good advice.
Note, to make the transition from one keyframe to another more efficient, use a variant of the Bresenham algorithm.  This allows use of fast integer arithmetic and is intrinsically accurate.  Instead of error accumulating and getting steadily worse (as will happen if you add constant increments), the Bresenham algorithm tracks error and minimizes it.  See, for example, “Simplified Bresenham's line algorithm: What does it exactly do?”.

This edit addresses Paul's question about accumulating error:

I've added a note to my answer, in which I try to battle the accumulation of error, could you check if my assumption (that the last implementation doesn't accumulate the error) is right?

There can be several sources of error, including accumulation of round-off error; arithmetic overflow errors; time-base errors; and silly errors [it's always easier to poke holes in other people's code!].
To illustrate those error sources and a possible solution, consider the following code snippet:
 0   unsigned long int startTime = millis();
 1.  unsigned int totalTime = 3000, nSteps = 100;
 2.  int msPerStep = round(totalTime/nSteps);
 3.  byte startRed = 100, startGreen = 28, startBlue= 50;
 4.  int deltaRed   = endRed   - startRed;
 5.  int deltaGreen = endGreen - startGreen;
 6.  int deltaBlue  = endBlue  - startBlue;
 7.  byte nowRed=startRed, nowGreen=startGreen, nowBlue=startBlue;
 8.  for(int step= 0; step < nSteps; step++){
 9.     analogWrite(RPin, nowRed   += deltaRed/step);
10.     analogWrite(GPin, nowGreen += deltaGreen/nSteps);
11.     nowBlue = startBlue + (deltaBlue/amountOfSteps)*step;
12.     analogWrite(BPin, nowBlue);
13.     long int elapsed = millis()-startTime;
14.     analogWrite(RPin, startRed + (deltaRed*elapsed)/totalTime);
15.     delay(msPerStep);
16.  }

First, consider currentRed += deltaRed/step expression in line 9.  In the first loop pass it adds an undefined quantity, deltaRed/0, to nowRed; in the next, it adds deltaRed/1 to nowRed; then deltaRed/2; and so forth.
Line 10 corrects the silly error of dividing by step instead of nSteps.  But there can be significant accumulation of round-off error.  For example, if deltaGreen is 199 and nSteps is 100, it repeatedly adds 1 instead of 1.99, and ends up with the Green level 99 counts short of being correct.
Line 11 attempts to compensate for that problem by adding a step-proportional amount of deltaBlue to startBlue at each step.  However, due to the parenthesized order of arithmetic it has exactly the same round-off error problem as line 10 – it adds exactly one unit per step for my example numbers.  To try to avoid this problem, one might write (deltaBlue*step)/amountOfSteps in place of (deltaBlue/amountOfSteps)*step.  This will do accurate arithmetic except can easily overflow an int so should perhaps be written instead as (deltaBlue*(long int)step)/amountOfSteps.
Even if line 11 is rewritten to avoid truncation, round-off, and overflow errors, it still is subject to time-base errors.  Like the color numbers, the delay() parameter msPerStep is subject to accumulation of round-off errors.  During the for loop, several hundred milliseconds of error could accumulate, leading to mismatched or jittery color levels.  To avoid that error, instead measure elapsed time (as in line 13) and make color levels proportional to elapsed time (as in line 14).  In addition, one probably should change the for loop to a do { ... } while (elapsed < totalTime) loop, ie, let the loop run until the right time has passed, rather than some arbitrary number of passes.

Nice note on the "Bresenham algorithm", I also encountered thought of that when writing my answer. But I think that for LED lighting, it wouldn't really be that visible. (Unless it just rolls over 255 and becomes 0.1, then it's about off instead of fully on ;D)

I've added a note to my answer, in which I try to battle the accumulation of error, could you check if my assumption (that the last implementation doesn't accumulate the error) is right? EDIT: I'm not even sure if it battles the problem (and is probably inefficient) but it seems logical.

@Paul, as I couldn't fit a reply into a comment, I've edited my answer with comments on that question.  Let me know if you see any errors in the comments.  Thanks!

Very good explanation, indeed, if I do the multiplication after the dividing, it will still accumulate the error, missed that one. But nice fix you have there ;) but it indeed is rather easy to overflow, should be tested and specced well, or add some checks.

And I indeed missed the thing on delay, of it's 49ms instead of 50ms and you only have 100 frames, it has an error of 100 on 5000, which may seem not too much of a deal, but I agree that code should be robuust/portable. If you get 1ms on 2ms, with a 1000 steps, you're at 50% error (a whole second).

@Paul, for this particular color animation, an error of 100 in 5000 might not matter.  But more generally, for sound or picture sequences, a tenth of a second is glaringly obvious.  Even a hundredth of a second gap is pretty obvious and makes a click in a sound sequence.

I'm not sure what you have working or what you haven't.
I'm also not sure what you've tried and which problems occured.
However, I'd like to give you atleast a basic answer before I vote for: "Too broad".
It's actually quite simple (but you can make it difficult).
Step 1
Imagine the effect, what are you actually trying to achieve? Fade out the current color and fade in a new one? Or are you trying to shift the color from one to another?
Step 2
Find resources online.
You're likely not the first person to have tried this ;D
https://www.arduino.cc/en/Tutorial/ColorCrossfader
Step 3
Iteratively and rationally develop your project.
Know what you have and what you need.
You've got these parameters:

Current R/G/B values.
R/G/B values you wish to shift/fade to.
Duration of the fading effect (total time of the animation, total amount of frames for the animation)

Your goal:
Is making an "animation". Changing the colors over time, as an fading effect.
We will simplyfy it by starting with only the R (red) channel, we can add the rest later.
Let's say we want to fade from 100 to 255 in 3 seconds.
We're going to have 155 different levels of brightness over 3 seconds.
Which is roughly 20ms per step.
for(currentRed; currentRed < setRed; currentRed++){
   analogWrite(redPin,currentRed);
   delay(msPerStep);
}

But that won't really work for multiple channels...
Just add another channel and find your way out that challenge.
(I added blue, but you could add up to x amount with this code I believe)
unsigned char currentRed = 100;
unsigned char currentBlue = 50;
unsigned char setRed  = 255;
unsigned char setBlue = 255;
int differenceRed  = setRed  - currentRed;
int differenceBlue = setBlue - currentBlue;
unsigned int totalTime = 3000; //3sec (in ms)
unsigned int amountOfSteps = 100;
int msPerStep = round(totalTime/amountOfSteps);

for(unsigned int step= 0; step < amountOfSteps; step++){
   analogWrite(redPin, currentRed  += differenceRed/step);//We could optionally calculate the difference per step beforehand, to avoid having doing dividing in a loop (may be a tad inefficient this way).
   analogWrite(bluePin,currentBlue += differenceBlue/step);//But well, in the delay you're also just wasting CPU, so who cares? :)
   delay(msPerStep);
}
currentRed = setRed;//Compensate for rounding step values
currentBlue=setBlue;//You may want update the analog pins, though I presume it would be barely visible to a person.

You could get rid of the blocking delay, but well, that's beyond the scope of this answer.
I haven't tested the code, nor the algorithm extensively.
You may check what happens if the setpoint is lower as the current value.
So now you can test the algorithm, finetune/adapt it to your liking and make a function out of it :)

As noted by jwpat7, combining floating point math and integers on Arduino will have quite an error in it. And if you keep applying the same error each step, it will accumulate.
I'm not sure how significant it will be for LED applications, you usually can't see the difference between a few "levels" of brightness.
I've made my own implementation of which I think may battle this problem:
unsigned char previousRed = 100;
unsigned char previousBlue= 50;
unsigned char currentRed = previousRed;
unsigned char currentBlue = previousBlue;
unsigned char setRed  = 255;
unsigned char setBlue = 255;
unsigned int totalTime = 3000; //3sec (in ms)
unsigned int amountOfSteps = 100;
int msPerStep = round(totalTime/amountOfSteps);

for(unsigned int step= 0; step < amountOfSteps; step++){
    currentRed = previousRed + ((setRed-previousRed)/amountOfSteps)*step;
    currentBlue = previousBlue + ((setBlue-previousBlue)/amountOfSteps)*step;
    analogWrite(redPin, currentRed);
    analogWrite(bluePin,currentBlue);
    delay(msPerStep);//If the algorithm is inefficient, you COULD compensate for it by lowering the msPerStep.
}
currentRed=setRed;
currentBlue=setBlue;

I believe that, by completely recalculating it every step, the error won't accumulate.
This, however, may be a lot more inefficient than what jwpat7 describes. But atleast it's easy to understand.
Since you're throwing most of the cycles away by waiting for the next frame and can barely see the difference between "100 and 102" intensity from PWM, I think it's a viabale option.

source: Stack Exchange

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

sort: votes


text:
Most compact way to power 5V Arduino boards?
So I have quite a few ideas for wearable devices using Arduino boards (mainly the Nano and the Micro clones). With that in mind, I want to determine what the best way to power an Arduino is, with compactness in mind (and cost too, of course). One single button cell battery does not supply enough power to the Arduino to power it properly. I can use these 2x button cell battery holders (6v) but they mainly ship only from China and, for some reason, are relatively expensive ($15 for 6 of them).
Does anyone know of a better and cheaper way of powering these Arduino boards, with wear-ability in mind?
Thanks! :)

The best solutions are probably not to run at 5v.  In the ATmega you have a processor which at appropriate clock can match the range of several battery chemistries, choosing one or two cells appropriately.

I made a torch locator which looks like this:

That was powered by a single button cell. The actual processor is an ATtiny85. As you can see it isn't much bigger or heavier than the coin cell.
You can run the Atmega328P (and the ATtiny) at 3V (as from that battery) provided you slow them down to 8 MHz. That is quite easy to achieve, and then you don't need an external crystal as the Atmega328P has an inbuilt oscillator which can drive it at that frequency (as does the ATtiny).
I have a page about power saving which might help you with your design.
A possible alternative is a single LiPo cell (nominally 3.7V) which, if you get a small one, should be quite light.

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


text:
How to automate an electric kettle?
I have this tea kettle, which requires pressing two buttons one after the other ("on" and "prog") to start.
I'd like to automate that action (tying it to Tasker on my phone), and am wondering what's my simplest/cheapest option. My communication options are either WiFi or Z-Wave/ZigBee.
I'm assuming Arduino Uno Wifi is an option, but that seems like a huge overkill given how simple what I want to do is. Are there any other simpler/cheaper tools that I could use to do this?

... ESP8266... ?

WiFi is IMHO better, since you probably already have a WiFi network. And your phone supports WiFi. Otherwise you'll need some IP-to-ZigBee gateway. The ESP8266 is very nice, there are pretty neat little "dev boards" with USB, which make programming an easy job.

You may wire the buttons and transistor (bjt or fet) parallel. This way the device will still work with the normal buttons.

If you want to connect to your phone, you'd be better of using Bluetooth.

@Gerben the kettle is too far from my bedroom for that to work

You could use lots of options to control it from Mbed boards to the Uno with a wifi shield, to a raspberry pi to .... the list goes on.  But if it were me I would use the something like the ESP8266 which cost less than $10 usd and can be programmed with the arduino IDE (I'm assuming that is useful given the community this was posted in).  There are also lots of tutorials available online for this kind of thing.
To trigger the button you have two options: a non-destructive one and a destructive one.  For the non destructive one, use something like a solenoid in a custom mount or a servo and small lever arm to push the button.  The benefit to this is that if you change your mind you just have to move the device and you still have a perfect unharmed kettle.  Plus, you can still use it if your device breaks or malfunctions.
For the destructive option, open up the kettle to get at the buttons or button pads and solder a wire to each side.  If you're lucky you can do this so that it can still be put back together and the original button still work.  One option is to use a relay to connect them.  You can use a small solid state relay or a larger coil relay; both would be under a couple of dollars and not large enough to be too obtrusive.  Using a relay is nice since you don't have to worry about which voltages are being used on which side of the button and it isolates the microcontroller from the kettle better.  (Actually some relays are polarized so if it doesn't work, switch the wires and try again).  Another option is to use an  optoisolator like this one.  It is polarized so if it doesn't work switch the wires.  Another option is to use a mosfet.  I believe it will work if you get an N channel mosfet with a Vgs (gate to source voltage) less than 3.3V.  Hook up the Source pin to the more negative of the two button leads and the Drain to the other.  Hook up the gate to a pin on the micorcontroller.  Also, you should put a resister between the gate and the source pins.

Thanks! What resistor should I add if I use this transistor: IRLZ24N?

It's just a pull down resistor so a wide range would work.  I'd use a 10k just because I've got a lot laying around.  Anything 1k-25k should be fine.

Here's another article that may be of use: http://little-scale.blogspot.com/2016/05/circuit-bending-basics-two-easy-was-of.html

Replace your button with a relay and use a microcontroller to switch it.
It will be cheaper to use an ESP6266, which could be programmed with the Arduino IDE and the same Arduino code works on it. It will be perfect as it has got just 2 GPIO ports and it will just be the size of your thumb.

Calm down, you don't need a full relay to emulate a small switch, a MOSFET would be good enough.

Also, the ESP8266 has more then 2 GPIOs, I mean WAY more. You just have the ESP8266 ESP-01 breakout, the first on which has only 2 GPIOs. The ESP-12 has many more and with a custom PCB, you can have access to all of them.

This is simply a suggestion. It is not in your list of communication protocol that you listed but this could work great.
A good and reliable way is to use an GSM shield with and Arduino. The GSM shield could receive a text such as "on" or "off" and could interpret those messages to control your kettle.
To emulate the switches, you can use 2 MOSFET. They act like an electronic in the sense that when you apply 5V (PNP transistor), it lets current pass and will cut the current flow when there is no voltage applied to it.
NOTE: GSM modules are quite cheap if you know where to get them. I recommended getting a chinese version because they usualy work fine for me and there price is way lower.

Hmm, I het have to find a decent+cheap GSM module. But WiFi will do in this case, since I suppose the device will always be within range of the WiFi. So you can eaily get away with a ~4$ ESP8266-12 dev board.

Pay and extra 4$ and you get something that works everywhere. https://www.amazon.com/SIM800L-Quad-band-Network-Breakout-Module/dp/B017I6QC8C/ref=sr_1_7?ie=UTF8&qid=1478086767&sr=8-7&keywords=gsm+arduino

Nice, considering I've worked with the SIM900, I should be able to figure out how to get this one working.

Probably a dumb question, but I know basically nothing about GSM aside from my phone having it. Wouldn't said module need a sim card/service connection to work?

Yes it does need a SIM card

@canadiancyborg so I'd need to pay monthly fees to a cellular provider to use this? Those would greatly exceed whatever the costs of the GSM shield are, so I don't really understand this suggestion..?

Well I have a cell with unlimited data and I remove its SIM card when I need to use it in my projects.


text:
why of 2 identical micro-controllers, only one can connect to a given device?
I am working with 2 identical (Arduino) Adafruit Feather M0 Bluefruit LEs. Only one of them can connect to a Universal Windows Platform app running on a  Windows 10 machine. The other connection fails with Unreachable status.
I am only trying to connect with one MCU at one time. Both MCUs are loaded with the same program which resets the Bluetooth Unit. Both MCUs can connect to an Android app. Neither board appear damaged.
Why could a UWP app be able to connect to one board but not another?

Other than a software issue, there is no reason it shouldn't work. Only thing may be identical Bluetooth names or ids. Clear the device from windows and try again.
I have some cheap Bluetooth obd 2 readers that all use the same Bluetooth mac address and name. I have to delete one from my android phone before adding the new one to connect to it.

They have different addresses but the same name. The one that couldn't connect was paired (through the os) to the computer. It could connect after unpairing. I experimented by pairing the other. It could no longer connect if the other had been connected.

Yep, and that's because sometimes the app or system looks for the name and sometimes the Mac address and sometimes both. Unique everything solves that. Same thing with a pair of cheap bluetooth speakers. Change the name and it starts working.

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


text:
Problem sending string with Python to Arduino through serial port
I want to send string 50 to Arduino through serial port, the Arduino UNO seems it communicates with port COM25 but it doesnt receive the string properly:
import serial # if you have not already done so

ser = serial.Serial('COM25')
ser.baudrate = 9600
ser.write(b'50')
ser.close()

Btw Arduino code is correct I checked it with other serial com programs. How can I fix the above code?

serial.Serial() resets Uno and it spends some time in bootloader after then. add a delay/sleep after serial.Serial

I dont understand ;so how can I send string in Python as done in hyperTerminal? My Ard code works with hyperTerminal but I have been looking for a day and couldn't find a code which work for Python.

you need to wait 2 seconds until sending something over that Serial from python. Serial Monitor resets the Arduino too when opening a connection. At opening of window, not before every sent data

The AVR Arduinos (Uno, Nano, Mega) have auto-reset function. At opening of USB connection the circuit around USB resets the MCU. After reset the bootloader waits a second for a new upload. If the upload doesn't happen the bootloader starts the current sketch.
The serial.Serial() command in python opens the USB connection. With that the Arduino is reset and waits in bootloader while you send the data. The data doesn't arrive in your sketch. Add a two seconds wait time after Python's serial.Serial().

Thanks for this answer. This was driving me nuts. Alternatively, I added a line in Arduino setup() to send a byte and waited for that in python to get things started.

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


text:
What are exactly XTAL1 and XTAL2 pins in Arduino Uno/Nano?
I know that the blow red encircled component is the 16MHz Crystal Oscillator (XTAL):

But PB6 and PB7 pins are called XTAL1 and XTAL2 pins which are not accessible by the Arduino board.
Are these pins where the 16MHz crystal oscillator is connected. But if so why are they two of them? I searched net but couldn't find explicit information about these.
How many clocks in total this board have?

Yes they connect to the crystal. There's two of them because a crystal has two pins.

But what is the difference between them? One is not ground. So they have difference in implementation or use. Is that something to do with CMOS or TTL interfacing? Im looking for a more detailed answer.

Look up some typical crystal oscillator circuits. All but the crystal is inside the chip.

Im asking what is the difference between XTAL1 and XTAL2 explicitly not how to connect a crystal osc to them.

One is the drive output and the others the sense input. To understand what they do you first have to understand how a crystal oscillator circuit works.

https://www.electronics-tutorials.ws/oscillator/crystal.html scroll down to the CMOS oscillator. The gates are inside the mcu. Where the crystal fits in that circuit are the xtal1 (gate input) and xtal2 (junction between two gates).

I marked in red to be sure is it something like that: https://i.sstatic.net/gvcMB.png ??

Yep, that's right.

The Crystal in Red is for the Atmega16U2 that manages the USB interface with its high speed connection to the PC (12 MHz for USB2 I think).
The Resonator in Yellow is for the Atmega328P.  It is less precise than the crystal oscillator.
PB6 and PB7 are dedicated to the external crystal or resonator by the fuse settings used for Arduino.
You can read more about the XTAL1, XTAL2 pins and the fuses from the device datasheet
https://www.microchip.com/wwwproducts/en/ATMEGA328P
You can connect a crystal to the pins, but you will also need 22pF caps to connect from the pins to Gnd. And remove the resonator.  Current Uno layout does not really support making those connections.

XTAL1 is the input and XTAL2 is the output of the oscillator.
Using 8MHz internal RC oscillator instead of the crystal, you can use PB6 and PB7 as I/O, like other I/Os.


text:
Confusion with storage of declared variables and volatile
I read that volatile is used when we want to store variables in SRAM.
But aren't all the variables in a code are stored in SRAM anyway?
And what makes it an advantage sometimes for variables(like volatile) to be stored in SRAM?

That's just plain incorrect.
The volatile keyword tells the compiler that the value of that variable may change at any time, and that therefore it must re-read the value every time you use it in your code.
If you don't use volatile, the compiler may choose to make an optimisation.
Consider this code:
int b = 7;
a = b + b;

The compiler can see that 'b' is always 7 -- it is assigned the value 7 and nobody ever changes it.  The compiler may choose to optimise this to the equivalent of
a = 14;

But if you do this:
volatile int b = 7;
a = b + b;

then the compiler MUST read b twice from memory.
Why would you want to do that?  Perhaps you have an interrupt which might change the value of b.  Perhaps your interrupt changes the value of 'b' every time you press a button.  You need the code to really check the value of b every time it calculates a, and not rely on it always being 7.
Here is a fuller explanation.

Can you a bit expound on why volatile is better to use with interrupts?

I've tried and added a bit more information, but I'm not quite sure what more you'd like to know. Is there a particular thing you don't understand? (I'm aware that it's often hard to state clearly what one doesn't understand.)

Technically, variables can be stored anywhere, in SRAM, eeprom or enev flash.
However, without doing anything special, variables are stored in SRAM.
Thee votike attribute is just that, it tells the compiler that the variable could change its value and the compiler shouldn't assume that values obtained from prior access is valid now. This forces the compiler to re-read the variable on demand.

"Thee votike" ?

Local variables are most often stored in CPU registers, although in some cases they can end up in RAM.


text:
Problem to convert rotary encoder output to angle
I'm using this incremental rotary encoder with a rotating disc.
Here is my system:

I will explain the system briefly and above is the illustration for that:
The rotary encoder(blue) is attached/fixed to a larger disc(yellow) concentrically at its origin, so both the encoder and the disc rotate together the same angle.
The disc is rotating on a fixed plane(gray). The plane has a fixed point mark(red X) on its surface.
There is also a fixed red arrow on the disc.
Each time before the system is powered, I will manually rotate the disc such that its red arrow will be aligned to the red X mark on the surface.
This adjustment each time at the beginning will provide the reference point.
After this adjustment I want to output the actual angles via Arduino.
I tried the following example code from Arduino website:
#define encoder0PinA  2
#define encoder0PinB  4

volatile unsigned int encoder0Pos = 0;

void setup() {

  pinMode(encoder0PinA, INPUT);
  digitalWrite(encoder0PinA, HIGH);       // turn on pull-up resistor
  pinMode(encoder0PinB, INPUT);
  digitalWrite(encoder0PinB, HIGH);       // turn on pull-up resistor

  attachInterrupt(0, doEncoder, CHANGE);  // encoder pin on interrupt 0 - pin 2
  Serial.begin (9600);
  Serial.println("start");                // a personal quirk

}

void loop(){
// do some stuff here - the joy of interrupts is that they take care of themselves
}

void doEncoder() {
  /* If pinA and pinB are both high or both low, it is spinning
   * forward. If they're different, it's going backward.
   *
   * For more information on speeding up this process, see
   * [Reference/PortManipulation], specifically the PIND register.
   */
  if (digitalRead(encoder0PinA) == digitalRead(encoder0PinB)) {
    encoder0Pos++;
  } else {
    encoder0Pos--;
  }

  Serial.println (encoder0Pos, DEC);
}

/* See this expanded function to get a better understanding of the
 * meanings of the four possible (pinA, pinB) value pairs:
 */
void doEncoder_Expanded(){
  if (digitalRead(encoder0PinA) == HIGH) {   // found a low-to-high on channel A
    if (digitalRead(encoder0PinB) == LOW) {  // check channel B to see which way
                                             // encoder is turning
      encoder0Pos = encoder0Pos - 1;         // CCW
    }
    else {
      encoder0Pos = encoder0Pos + 1;         // CW
    }
  }
  else                                        // found a high-to-low on channel A
  {
    if (digitalRead(encoder0PinB) == LOW) {   // check channel B to see which way
                                              // encoder is turning
      encoder0Pos = encoder0Pos + 1;          // CW
    }
    else {
      encoder0Pos = encoder0Pos - 1;          // CCW
    }

  }
  Serial.println (encoder0Pos, DEC);          // debug - remember to comment out
                                              // before final program run
  // you don't want serial slowing down your program if not needed
}

But this code increases one count for each encoder tick at CW direction, and decreases one count for each tick at CCW direction.
It keeps increasing from zero to 65535 in CW and decrease from 65535 to 0 in CCW.
I want to translate this code such that I can output the angle in degrees.
My encoder says its ppr is 15 and 30 ticks. This code increase/decrease one count for each tick.
Any idea how to extract the angle from this setup? (It doesn't have to use the specific code I provided.)

if it's 30ppr then every count is 12 degrees. So multiply the number by 12. The do a modulo 360 ( x = x % 360), so you only get values from 0 to 360. But not that you can only know the angle difference from when the sketch first started. So you have to set the disk to the zero position before turning on the Arduino.

Serial.println() can cause problems when used within an ISR.  Set a flag instead, and print from loop()

@jwpat7 How can I implement that setting flag and outputting from void? I also experience two outputs at some single encoder ticks. Can that be because of bouncing?

Declare a flag, eg volatile byte cchange;, and set it true in the ISR.  In loop(), say if (cchange) { cchange=false; printstuff(); }   ¶ Re double counts, the ISR shown is slow, which can mess up counting.  If your ISR were to catch all the edges and treat them correctly, eg via a state machine like in my answer to question 32572,  bouncing would cancel out.

How could this code be modified to use an indexed encoder to reset the counter to 0 every time it hit the index. I would like to use this to track a rotating mast for direction finding.

As noted in a comment, treating the numbers modulo 360° will put results into the range you want.
Note, however, that you can (and should) avoid use of long arithmetic by taking the pulse count modulo 30 before multiplying by 12°.
To compensate for the reference point adjustment, have the program set your tick count to correspond to 0° when the arrows align.  If you set the base count to some value that's a multiple of 30, say 120, and store it in an unsigned byte, the code would look like so:
angle = 12*(count%30);

Since the base count 120 is a multiple of 30, it falls out automatically when the modulus is taken.  To make this work in the long run, you would set the encoder count to 120 whenever the arrows align (or to (current%30)+120 if required to adjust it at other times).
If your base count were 0 instead of 120 and the count an unsigned integer instead of a byte, when the rotor goes CCW the modulus counts would have 15 extra counts.  For example, a count of 0 correctly converts to 0°, but a count of 65535 is 15 modulo 30, so converts to 180° instead of 348°.
Note, there is no need to debounce rotary encoder inputs if a proper state machine is used; and debouncing slows processing to the point that ticks will be lost.  See my answer to question 32572 which includes code for reading several encoders active at once.

Gerben's comment is mostly right. The shortest way to adapt the behavior of that sketch to your setup is by multiplying the result by 24 (not 12, since it is 15 pulses - 30 dents, but each channel varies 15 times) and then making the modulo:
if (digitalRead(encoder0PinA) == digitalRead(encoder0PinB)) {
    encoder0Pos += 24;
} else {
    encoder0Pos -= 24;
}
encoder0Pos = encoder0Pos % 360;

BUT... the code you posted has some problems.

"The joy of interrupts is that they take care of themselves" is true, but relying on interrupts always has some drawbacks you MUST take into account. Mainly you are blocking the rest of the program (screwing up the timings for instance). I prefer to use the interrupts only when strictly needed (and this is not the case)
You are performing a potentially long function (serial interaction) into an interrupt. Totally wrong
You are using HALF the steps you can potentially use (since you are checking only one input, you are ignoring half the transitions).

To fix these, I propose you to rewrite the program to check in the loop the buttons status. Then, since they are mechanical switches, I'm going to use the Bounce2 library to debounce the inputs.
This, alongside with solving the previous 3 points, will also allow you to use any arbitrary pin on the board.
#include <Bounce2.h>

#define encoder0PinA  2
#define encoder0PinB  4
#define STEP_SIZE 12

byte encoder0Pos = 0;

Bounce debouncerA = Bounce();
Bounce debouncerB = Bounce();

void setup()
{
    debouncerA.attach(encoder0PinA, INPUT_PULLUP);
    debouncerA.interval(5); // interval in ms
    debouncerB.attach(encoder0PinB, INPUT_PULLUP);
    debouncerB.interval(5); // interval in ms

    Serial.begin (9600);
    Serial.println("start");                // a personal quirk

}

void loop()
{
    // Read the status of the inputs
    debouncerA.update();
    debouncerB.update();

    int8_t EncVariation = 0;

    if (debouncerA.rose())
    { // if input A changed from low to high, it was CW if B is high too
        EncVariation = (debouncerB.read()) ? 1 : -1;
    }
    else if (debouncerA.fell())
    { // if input A changed from high to low, it was CW if B is low too
        EncVariation = (debouncerB.read()) ? -1 : 1;
    }
    else if (debouncerB.rose())
    { // if input B changed from low to high, it was CCW if A is high too
        EncVariation = (debouncerA.read()) ? -1 : 1;
    }
    else if (debouncerB.fell())
    { // if input B changed from high to low, it was CCW if B is low too
        EncVariation = (debouncerA.read()) ? 1 : -1;
    }

    if (EncVariation != 0)
    {
        encoder0Pos = (encoder0Pos + EncVariation * STEP_SIZE) % 360;

        Serial.println (encoder0Pos, DEC);
    }
}

Disclaimer: I haven't tested this, but I'm pretty confident this will work.
I highly suggest you to use the Bounce2 library, since it also has many helper functions which shorten the code a lot. See here for instructions on how to get and use it. I'm just a happy user of this library, and I'm not linked in any way to the author ;)

This code works better I dont see erratic outputs. Is it also possible to output the direction CCW or CW. I mean this code will work but I also want an LED to turn on when  the encoder rotates CCW. How can it be done? Thanks in advance

oh i actually noticed EncVariation indicates the direction:)

@doncarlos yes, just check it and it tells you whether it is turning (!= 0) and the direction. By the way, if the answer fully answers your question please mark it as accepted; otherwise just ask ;)


text:
Confusion in the use of byte variable
A byte stores an 8-bit unsigned number, from 0 to 255.
I can understand the following line:
byte b = B10010;  // "B" is the binary formatter (B10010 = 18 decimal)

But I also saw a use such as:
volatile byte state = LOW;

What does the last line mean here? Is that special for Arduino?
I mean LOW is not a 8 bit unsigned number. LOW is not a number here.

It is common practise in C/C++ to define certain much-used constants at the beginning of the code.
#define true 1

this means that every time you write true in your code, the compiler will see it as 1.
The arduino IDE comes with a few constants predefined:

true = 1
false = 0
HIGH = 1
LOW = 0
...

in C++ true and false are already keywords, why would one try to  #define them?

@jfpoilpret Perhaps if one is not using C++ ...

In the same way that you can do
int blarb = 12;
#define wibble 73

you can do
int FOO = 73;
#define BINKY 99

or even
int LOW = 0;
#define HIGH 1

So in the line
volatile byte state = LOW;

someone has created some sort of numerical constant with the name LOW.
You can read all about various constants provided for you here.


text:
What kind of data type can be use store a binary bit-stream which is more than 64-bits?
I'm wondering if one needs to assign a bit-stream of 78 bits to a variable(later on to be processed), what datatype can be used? What is the max bit can be stored into a variable in C?

How about an array ob bytes? also 78 is not divisible by 8. no matter what type you take, you will have fractional parts.

But I can still store 78 into anything multiple of 8. Its not a problem rest of the bits can be zero.

Would in 64 can store 64 bits? How about if more than 64 and less than 128 bits are to assigned? Is it impossible?

FWIW, sizeof(intmax_t) == 8, at least on the AVR-based boards.

Here is a template class that handles this, https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/BitSet.hh.

There is no builtin data type that can store 78 bits. However, it depends a bit what you want to store. Like the following cases:

If the 78 bits are one 'entity' (e.g. one really big value), you can store it as an array of bytes (10 bytes of 8 bits = 80 bits, leaving 2 bits unused)
If the 78 bits can be split up in smaller parts, you can:

Create a structure or class to contain the sub elements into fields (instance variables), using for each sub type a normal type (e.g. signed/unsigned 8, 16 or 32 bits).
Create bit fields to save some memory if there are small items and memory space is an issue.
Or a combination of the above

If you have many of these items and you want to save space (thus the 2 unused bits of each 80 bits), you can create a big array that contains many items, and use bit operations to get each item. E.g. the first element will be in the first 10 bytes, where the last 2 bits are not part of the element. The second item will use the remaining 2 bits and the following 78 - 2 = 76 bits, etc. This saves only 2/80 * 100% = 2.5% so only use this when really needed.


text:
Arduino Nano memory issue. SD card and LCD screen together
When i am uploading my code to arduino nano, i am getting message about high dynamic memory usage (87%):
Sketch uses 17,628 bytes (57%) of program storage space. Maximum is 30,720 bytes.
Global variables use 1,751 bytes (85%) of dynamic memory, leaving 297 bytes for local variables. Maximum is 2,048 bytes.
Low memory available, stability problems may occur.

But despite this, its uploading to my arduino nano and everything works fine without action method's code. How to use code (code to work with LCD) wich is located in action() method. If i use hidden code, im getting message error opening test.txt (not enough memory). But if code which is controls LCD screen is annotated then SD card works fine.
If i use this code, i'm getting problem with SD card. But i can still use LCD and SD on same arduino board separately without any problems, but if i try to combine it, im getting some problems with SD card reading.
void action() {
//  display.display();
//  display.clearDisplay();
//  display.setCursor(0, 0);
//  display.setTextSize(2);
//  display.setTextColor(WHITE);
//  display.println(sensorValue);
// if uncomment this code, i am getting error with sd card reading (possible memory issue)
}

All code:
#include <Wire.h>
#include <Adafruit_SSD1306.h>

#include <SPI.h>
#include <SD.h>

#define OLED_RESET 4
Adafruit_SSD1306 display(OLED_RESET);

const int analogInPin = A0;  // Analog input pin that the potentiometer is attached to
const int analogOutPin = 9; // Analog output pin that the LED is attached to

int sensorValue = 0;        // value read from the pot
int outputValue = 0;        // value output to the PWM (analog out)

int count_iterations = 0;

#if (SSD1306_LCDHEIGHT != 32)
#error("Height incorrect, please fix Adafruit_SSD1306.h!");
#endif

File myFile;

void setup() {

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

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

  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");
  myFile = SD.open("test.txt", FILE_WRITE);

  // if the file opened okay, write to it:
  if (myFile) {
    Serial.print("Writing to test.txt...");
    myFile.println("testing 1, 2, 3.");
    // close the file:
    myFile.close();
    Serial.println("done.");
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }
  myFile = SD.open("test.txt");
  if (myFile) {
    Serial.println("test.txt:");
    while (myFile.available()) {
      Serial.write(myFile.read());
    }
    myFile.close();
  } else {
    Serial.println("error opening test.txt");
  }
  //// SD END
}

void loop() {
  sensorValue = analogRead(analogInPin);
  if (sensorValue < 1000) {
    action();
  }
}

void action() {
//  display.display();
//  display.clearDisplay();
//  display.setCursor(0, 0);
//  display.setTextSize(2);
//  display.setTextColor(WHITE);
//  display.println(sensorValue);
// if uncomment this code, i am getting error with sd card reading (possible memory issue)
}

Your code is using in the neighborhood of 150 bytes for text-strings in RAM, much of which can be moved to PROGMEM quite easily.  For example, replace
Serial.print("Initializing SD card...");

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

Changes like that to Serial.print() arguments should free up about 140 bytes of RAM.  To free up another 8 bytes, instead of SD.open("test.txt" ...), write SD.open(FileName ...) with FileName previously declared via char *FileName = "test.txt"; so that the text test.txt appears in RAM once instead of twice.
In short, if 150 bytes will make the difference, that much memory reduction is easy.

I briefly examined the source code behind the Adafruit_SSD1306.h and SD.h headers, to see if they use some large arrays in RAM, such as 512 bytes of sector data, or some hundreds of bytes for frame buffers.
Ordinarily, such arrays are difficult to get rid of without a rewrite from scratch or without major loss of functionality.  For most one-off projects, the effort involved isn't worthwhile:  one can instead use an Arduino Mega2560 system, which has 8 KB of RAM, vs the Arduino Nano's 2KB RAM; or can use an Arduino Due with 96KB RAM; or a Teensy, with 8, 16, or 64KB RAM.
However, if you plan a production run and are trying to hold down costs by using Nanos, consider the following approach:   Carefully arrange the processing so that you are done with SD buffers before needing a display frame buffer; and revise the libraries so the SD buffer and frame buffer overlap.  That is, place the smaller buffer within the same region of memory holding the larger buffer.  If processing can't be neatly separated, blank the display while using the shared buffer area for accessing SD data.
[Note, I edited this answer and expanded discussion of buffers in the libraries.]


text:
Arduino Leonardo - disabling the debugger port
My Sketch program is working perfectly as a specialized keyboard application on the Leonardo. I want to disable the development tools drivers from the USB, (COM PORT) leaving only the HID Keyboard drivers.  I understand I will need to use the Arduino ISP or other method to load my code.
Is there any way to disable the drivers for the development tools from the on board USB, leaving just the HID drivers?

Other than modifying the core? (Which, BTW, doesn't affect the bootloader)

@IgnacioVazquez-Abrams It would affect your ability to (easily) get into the bootloader since that relies on opening the (now non-existent) serial port at 1200 baud to trigger a reboot.

Never could get that to work. I just use Sparkfun's bootloader, which uses a double-press of the reset button to put it in programming mode.

There is no easy way, no. You have to reprogram the core to break the connection between the USB interface and the CDC/ACM driver. That means working out a new set of descriptors, deleting chunks of code, patching around the newly created holes, etc.

I was afraid of that...

Is this driver code publicly available somewhere?

It is on your computer.


text:
wire.h multiple slave addresses
Is it possible to use wire.h on an Arduino Uno to act as a slave for more than one address?  For example I'd like it to emulate two different devices, one at I2C address 23 and the other at address 57.
I'm either looking for a way to do this directly, or to run multiple instances (each would need a different onReceive handler).

Why do you want to? That's like saying "I have a house in New York, and another in London. When someone sends a letter to the London house I want it to arrive in the New York house." That's not how addresses work.

Now you described, how my e-mails works :) Anyway I would like to do the same with i2C, as I am planning to have one master and a lot of slave devices (implemented by Ard's) and want to start with one dummy to emulate commanding all of them, then later, as I would implement the bodies and start suffering from space, pins and speed, I would transfer some devices to another HW. Then, if  I improve and shorten my code I would like to move back.So having more I2C addresses on the same Arduino (and access to different would run different code/codepath) make perfect sense for me. Bad luck, I cannot.

Is it possible to use wire.h on an Arduino Uno to act as a slave for more than one address?

The quick answer is: No!
The ATmega328 2-Wire Serial Interface has a special register for the address match in slave mode. This only allows a single address to be matched.

22.5.4   Address Match Unit
The Address Match unit checks if received address bytes match the seven-bit address in the TWI Address
  Register (TWAR). If the TWI General  Call Recognition Enable (TWGCE)
  bit in  the TWAR is written to one, all  incoming address bits will
  also be compared against the General Call address. Upon  an address
  match, the  Control Unit is informed, allowing correct action to be
  taken. The TWI may or may not acknowledge its address,  depending on
  settings in the TWCR. The Address Match  unit is able to compare
  addresses even when the AVR  MCU is in sleep mode, enabling the MCU to
  wake up if addressed by a Master. Reference, pp. 213

On an ATtiny with USI it is actually possible to implement multiple address matching as this is controlled by software.
Last, a pure software approach could be used, i.e. implement the I2C protocol with external interrupt pin and fast pin access. See Amtel Application Note AVR154. The code for this app-note can be found on github. This could be modified to allow multiple slave addresses.
Cheers!


text:
wire.h onReceive only triggering once
I am writing a program to emulate a LCD driver chip (PCF8576) in a piece of equipment where I need to replace an unobtainable LCD display.
I have wire.h set up and the code in place to decode chip commands and load the segment data to an array.  That all works, and I can take that data and drive a new LCD just fine.
My problem is that the onReceive handler only triggers once.  To get it to be armed and trigger again I need to press the reset button on the Uno board.  I put code in to pulse an output pin and can verify with a scope that the onReceive only runs once.
When I just began the coding last week the handler would trigger each time the equipment would write to this particular I2C address, and I can tell the equipment is operating correctly since an Arduino reset will then result in the onReceive event triggering again.
Does anyone have any clue what's happening here?  I tried commenting out most of my code but it still won't trigger on each receive.  Obviously there's something subtle I changed that I'm missing, but what?

Please edit question and put the reduced code into the question.  Accompany the code with a diagram or brief outline of circuit.

Try this; https://www.arduino.cc/en/Tutorial/MasterWriter

You are correct and that was the second part of the problem. The first part was that my code wasn't always retrieving every byte and this was hanging up the OnReceive function. Once I fixed that bug I found something very close to what you mentioned. On rapid device writes my handler routine didn't finish fast enough and thus could miss updates. What I did was to streamline the routine to take minimum time and that worked as the sending processor needed time between updates itself. In testing this works fine, what I did was to toggle a port pin and look at the I2C bus and that pin and could verify I was cleared out of the routine before the next update could come in. If it was close I would have gone to assembly for that routine but it turned out ok in this case. Thank you for your analysis!

If you have solved your own problem, please accept your own answer.

I looked at what docs I can find (not much) for 'onReceive' handler, but have not looked at the code itself.  I would ask, does the system keep running in spite of the fact that your handler isn't being invoked?  I'm asking if the bus is actually working after the first invocation of the handler? My guess is no. I also guess this ("onReceive" handler) has never worked as designed (hoped for?)
Also it sounds like you have a DSO scope, neat. Decades in electronics and I still get fooled by them (or the software:) now and then.  So make sure it's setup properly. Sounds like you do... but...
Does the i2c bus have only this one device?
I've found that 99.99% of my problems turn out to be chip configuration.  Improper interrupt or mask bits, etc. If it's driven by an interrupt, then it almost has to be the chip's interrupt configuration.  Of course if your code goes awry then it could change some of these bits that control the micro's operation and most can also write over the interrupt vector table.
Since it works after a reset, once, it may be wise to track down what happens in your particular micro's configuration after the reset, compared to what you change to get it to work.  Some of the parts of the micro I use (328p, maybe you also) have to be reset after an interrupt.
A last but not least option, since I'm not familiar with the function is to look at the assembler and see if it's resetting the required interrupt enable flags or masks. Most of these handlers end with some type of return from interrupt instruction that enables the interrupts and returns.  Generally alleviating the programmer of that task.
Best of luck :)

An Arduino as a I2C Slave to replace something in a device often fails. The Arduino uses hardware and software, while I2C chips use only hardware. The Arduino as Slave is often recognized on the I2C bus because it acknowledges to its I2C address. However, as soon as data needs to be transferred, the Arduino stretches the clock signal to create some time to call the onReceive function. Do you know if the I2C Master controller is able to handle the clock pulse stretching ? Sometimes it is a software I2C, and almost no software implementation takes care of clock stretching.


text:
Bootloader on Atmega328p overwrites whenever it gets programmed
I built my first custom circuit board with an Atmel ATMega328p-AU the tqfp-32 form factor. I connected xtal1 and xtal2 to an external 16mhz crystal to 22pf caps tied to ground. It seems to work great, I load the Arduino Bootloader using AVRDude and an arduino as an isp. As soon as I load a sketch on using the ftdi it blows out the bootloader and I can't upload a new sketch until reloading the bootloader. The sketch works as expected, my board has an on board relay and an onboard mosfet I've programmed various blink patterns on both the mosfet and relay.I just don't want to have to reload the bootloader everytime I want to make a change, my sketch is an evolving piece of work and it's frustratinf to take these steps. So far I've tried changing the lock bits to 0x0F 0xEF 0xFF and 0X2F. I've tried various fuse bits, I've changed the signature 0x1e 0x95 0x14 to 0x1e 0x95 0x0F. Nothing seems to change the results, the only thing I've managed to do is one upload caused the chip to run at 8mhz instead of 16mhz, oops. That was easily fixed though. Please if someone can help that would be great, unfortunately the fuse bit calculators I have found don't have the 16mhz crystal as an option even though it's clearly functional.
In Summary
Sketches overwrite my bootloader and I want my bootloader locked but I can't find a solution after nearly a full day of googling and experimenting

... probably should also have pin 6 of the ATmega328p connected to Vcc as well, but probably doesn't explain your problem.

... you also want a fly-back diode across your solenoid header, and across your relay coil, probably, or those NPN transistors may not be long for this world, but again not related to this question

...7805 regulator probably needs bulk capacitors 10uF on its input and output too, but again probably not related...

I suspect the BOOTSZ bits in the hfuse might be set to an incorrect value. Have you tried setting hfuse to 0xD9 ?

Why would you change the signature? That identifies the chip. How did you change the signature?

Almost certainly your fuses are wrong. The fuses tells it whether or not to run the bootloader. With an empty PROGMEM (ie. no sketch) the processor probably skips over all the 0xFF bytes until it hits the bootloader. Once you have a sketch there it will run the sketch.
On my Uno (which is an Atmega328P) running at 16 MHz from a crystal, my fuses are:
Low = FF High = DE Ext = FD Lock = EF

I suggest you visit http://www.engbedded.com/fusecalc to work out fuse settings.
You want the BOOTRST fuse set (that is, the high fuse should be 0xDE or something with the low-order bit clear). On the AVR chips, having a bit clear (0) means the fuse is set.
I have a bootloader programmer sketch which not only puts the bootloader there, it sets the correct fuse bit.
I also have a chip detector sketch which will tell you the current fuse settings.

I suspect you aren't writing the fuses on the AVR correctly in some way (or at all?). Try using the "Tools > Burn Bootloader" functionality of the IDE itself (which will set the fuses as well as loading the flash). You have to make sure you pick your ISP programmer under tools as well for this to work (e.g. Arduino as ISP). See if that works any better for you.
As an aside, there are a variety of AVR online fuse calculators if you're not into reading the datasheet. For example, http://www.engbedded.com/fusecalc. I seem to remember some rumblings in recent history that full swing external crystal configurations wouldn't be supported in new silicon for the ATmega328p, but that's what I always used to pick, and I think it probably still works as a setting.
Honestly, though, the easiest thing to do is to run Arduino in verbose (check the boxes in Preferences) and borrow their avrdude commands that get displayed when you run Burn Bootloader.
Continuations...
If that (Burn Bootloader) doesn't work for you, we're going to need to see some schematics, and I'd be staring pretty hard at your reset sub-circuit and FTDI sub-circuit.
Arduino Uno bootloader wants you to talk to it at 115200 baud... see the boards file.
What do you mean "My IDE doesn't hae a 328p UNO"? Download the latest Arduino from https://www.arduino.cc/en/Main/Software and choose Genuino Uno.

@Cfoote7 they do have 16MHz, it's just listed as "8.0 - Mhz" meaning 8MHz and up. I would just pick the last one in the dropdown (maximum frequency, slowest startup), also you can probably safely choose the Uno as your board in the IDE, give that a try?

@Cfoote7 You are just clicking upload when you want to load over USB right? Make sure you aren't choosing Upload using Programmer. Because that will blow away the bootloader... on purpose.

@Cfoote7 see updated answer, try Arduino Uno @ 115200 baud, p.s. don't have both your 12v and the ftdi cable plugged in at the same time with your circuit

My IDE doesn't have a 328p UNO as an option - what IDE?


text:
How many bits can an Arduino uno read?
What is the maximum of bits that an Arduino can read on the digital input, which model in the Arduino range can read the most bits?

A single digital pin can only ever be either on or off.

Sounds like an X-Y problem - what are you really trying to solve?

Ah, GrassHopper.... when you can answer my question, you will know the answer to your own...    How big is a bit?

What is the maximum of bits that an Arduino can read on the digital input, which model in the Arduino range can read the most bits?

A digital input is by nature binary (i.e. a single bit). The answer to your question is therefore one bit per digital input.
The total number of digital inputs depends on the board. It ranges from Arduino Micro (which has fewest less with than 10) to Arduino Mega which has the most with more than 60).
Another possible interpretation of your question is the resolution of an analog pin (ADC). The AVR has max 10 bit resolution.
Cheers!

Do you mean simultaneous read or write? The AVR processors are 8-bit processors and their I/Os are grouped into 8-bit registers. If you configure all of the bits in a register to the same direction - all inputs or all outputs - then the entire 8 bits could be read/written at once. in C/C++ you would use the `PORTWhich I/Os are assigned to which register is designed into the chip - but the data sheet describes which physical pins are connected to which I/O register. You can take advantage of that to make use of a single register's-worth of pins for up to 8 signals that need to be set or read simultaneously.


text:
Connection between Matlab and Arduino
I'm trying to connect Maltab and Arduino by this code:
arduino=serial('COM7','BaudRate',9600);
fopen(arduino);

But I get this message:

Open failed: Port: COM7 is not available. No ports are available. Use
  INSTRFIND to determine if other instrument objects are connected to
  the requested device.

What might be a proper reason?
I have another question which is; How can I save a text file (.txt) from Matlab to Arduino SD card .. ? Wether opening a .txt file in arduino or saving it from Matlab directly to Arduino SD card.

when you open it and after forget to close it (lets say your script crashes) and retry to reopen it will cause these errors. Try force a fclose on serial object.

I've done this and it still gives the same message.
Isn't there any other possible option maybe to add a text file to Arduino SD card or anything else?

If you use arduino IDE, does it open the port normally?

Hmmm I currently have no time to order one since I have to finish my project in only 3 days .. You see, I got the results of my algorithm from Matlab in a .txt file, and what's left is to add this .txt file in Arduino SD card in a way or another... my first option was to add it directly from Matlab but the connection seems not quite supportive.. so is there any way to put this text file from my pc to Arduino SD card? Thanks in advance! You'd save my life :)

Sorry but now you got me confused. You don't actually have an arduino (hardware)? When before I asked if the port opens correctly I was talking about arduino IDE (the software). I suppose a basic SD card reader connected to computer is out of question right?

Ahh apologies, Yes I have the Arduino hardware and the port works normally from what I see in IDE, however, in Matlab there seems to be a problem, I don't think it is the port neither the Arduino plug-ins in Matlab, this was actually the second option, my first option was to take the text file from my pc and save it in Arduino SD card but I don't think it is possible!

There is no 'Arduino SD card'. There are only SD cards and Arduino libraries that help you talk with the cards. Now, the text file you wish to write to an SD card, where exactly is it? Is it already on your PC? If so, then transferring it to the SD card using a standard card reader or adapter, like has been suggested already, is all you need to do. Unless there's some other reason why you need the Arduino...

@JackSparrow aparrently the problem is related to the fact the uno usesatmega16u2 as serial emulator. I managed to make it work in linux by following this link: (http://www.mathworks.com/matlabcentral/newsreader/view_thread/194071). However I do not have any windows pc to test similar approach as refered like here: http://www.mathworks.com/matlabcentral/answers/93708-is-it-possible-to-support-1024-serial-ports-in-win32-systems-in-matlab . Try to test it with your port

The first step in debugging this is to use the Device Manager (available in Computer Management) to see what ports the PC thinks are there.  It will confirm whether or not there is a COM7 at all.  Your error message seems to indicate the port does not exist.


text:
How do you get 2 PWM pins to inversely bitbang at 25 KHz on a Nano?
I need 2 PWM pins to oscillate at 25 KHz but they need to oscillate inverse to each other.  When one is high, the other must be low and vise-versa.
I want to do this with a Nano.

use one pin and invert it using hardware

Use two timers with the same settings, started simulaneously.

@towe: How do you start them simultaneously?

@EdgarBonet Set their Clock Select right after each other, that should only be a couple clock cycles of difference.

There are various solutions. I suggest using two PWM channels driven by
a single timer. This way you do not have to worry about synchronizing
two timers. You can configure the channels identically, except that one
of them would be in “non-inverting” PWM mode, while the other one would
be in “inverting” mode.
Here is how I would do it: use Timer 1 to drive pins 9 (PB1, OC1A) and
10 (PB2, OC1B) in fast PWM.
void setup() {
    // Configure Timer 1 for complementary PWM @ 25 kHz.
    DDRB  |= _BV(PB1);    // set pin 9 = PB1 = OC1A as output
    DDRB  |= _BV(PB2);    // set pin 10 = PB2 = OC1B as output
    TCCR1A = 0;           // undo the Arduino timer initialization
    TCCR1B = 0;           // ditto
    ICR1   = 640 - 1;     // period = 640 CPU cycles = 40 us
    OCR1A  = 320 - 1;     // OC1A HIGH for 320 CPU cycles = 20 us
    OCR1B  = 320 - 1;     // OC1B LOW for 320 CPU cycles = 20 us
    TCCR1A = _BV(COM1A1)  // non-inverting PWM on OC1A
           | _BV(COM1B0)  // inverting PWM on OC1B
           | _BV(COM1B1)  // ditto
           | _BV(WGM11);  // fast PWM, TOP = ICR1
    TCCR1B = _BV(WGM12)   // ditto
           | _BV(WGM13)   // ditto
           | _BV(CS10);   // clock at F_CPU
}

Ah, that's what I had in mind first, but I was irritated by the second Compare Output Mode behaving different for OC1A and OC1B and thought they were fixed to each other. +1

This works perfectly.  I could not have asked for a more simple and precise solution !!!


text:
Why isn't my Arduino Nano Every recognized as a Nano Every and why won't it upload sketch?
I have a genuine Arduino Nano Every board that isn't showing up quite right.  I actually have 2 hooked up to the computer on different ports and one of them, when I click on 'Port' shows as:
COM12 (Arduino Nano Every)

But the other one just shows up as:
COM18

The COM18 device used to have (Arduino Nano Every), but doesn't anymore.  The other problem I have is that when I try to upload a sketch to the device, it compiles and gets to uploading and then has a bunch of errors:
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
An error occurred while uploading the sketch

I've tried changing the selection on "Registers emulation:" between ATMEGO328 and None (ATMEGA4809) but I get the same errors whenever I try to upload a sketch.  Is my Every bricked?  Or is there some way to revive it?
I'm not sure why this happened.  I was able to upload sketches before, and have barely even used this device.
Does somebody have any ideas on how to get this working again, or should I just throw it away and get another one?

the USB chip on Nano Every is a SAMD11 with Arduino firmware. you could try to flash the firmware. https://www.arduino.cc/en/Guide/NANOEvery#firmware-for-samd11d14a

Your programmer chip is bricked. Lol

I'm not the one who voted down, but you might show some effort, like trying to restore the bootloader. Both symptoms are clear: The Arduino does not work as the expected USB device any more. You might need to use another programmer (another Arduino for example) to access it.

Don't worry about the down-vote. If you got 20 you might worry. :)

Encountered this on linux, solved by selecting the tty/ACM0 port


text:
delete or free on object causes Arduino to hand or reboot
I've read a lot about dynamic allocation for strings or buffers, but that's not my case.
I plan to implement much blinkers types as classes, all inheriting from a base Action class.
I declare an array of 10 pointers because I want to limit to 10 blinkers simultaneously at most :
Action** actions = new Action*[10];

In the code, I will do something like :
int i = GetFreeActionID();
actions[i] = new ActionLightBlinkerMono(myPin, onDuration, offDuration);

Then the loop will call a method of the object and it works fine.
When it comes to stop the blinking, I would just destroy the object and set the pointer to zero, so the loop will not try to call the method of the object anymore :
if (actions[i]->Do() != 0)
{
  delete(actions[i]);
  actions[i] == 0;
}

Howerver, I see in the serial console that when it comes to the delete instruction, the Arduino just reboots itself ...
Tryed also free instead of delete with same result.
How could I safely free the object when it's not used anymore ?
It's an evidence I don't know what will be used at compile time, the blinkers will be started by the user (via I2C instructions) at runtime, hence instanciating different classes.

Please post a Minimal, Complete, and Verifiable example. Action** actions = new Action*[10]; - you aren't declaring an array of 10 pointers, you are declaring an array of 10 pointers to pointers. Is this really what you want?

It's an evidence I don't know what will be used at compile time, the blinkers will be started by the user (via I2C instructions) at runtime, hence instanciating different classes. - I don't understand that at all.

i'd really like to understand, I felt I was declaring a pointer to an array of pointers, not an array of pointers to pointers, I thought an array of pointers to pointers would have been something like Action** actions[10];

Ah yes, you are probably right there. :)

  actions[i] == 0;

That statement has no useful effect. Perhaps you mean:
actions[i] = 0;

oh god, man, you saved my life! Sometimes I feel my eyes need glasses ... Such a mistake, it works perfectly now!


text:
Do Arduino Nano Every devices short out?
I have an Arduino Nano Every device that seems to have shorted out.
I use a lighted USB hub with buttons that turn connections on and off.  Each button has its own LED that indicates power state for its associated port.
Anyway, when I plug my Arduino Nano Every into that USB hub, the lighted buttons turn off for half of the hub, like the Arduino is shorting out the hub.
I use a different Arduino and have no problems, so it's definitely the Arduino.
Any idea what could have caused this?  I was using the Arduino with a TMUX1511 switch chip and using pins  D9-D12 to turn on and off the 4 internal switches in the chip.  It's using very low voltage (5v) and amperage is (25 mA).  I used the 5v and gnd pins on the Arduino to power the TMUX1511 chip, but with such low amperage, I can't see how that could have caused the Arduino to fry.
Any ideas?

Probably you at some time created a short somewhere. Though that is impossible to say for us. We don't see the board and we don't know your exact circuit, that you used. Have you tested the Arduino with a different power source? If yes, was it working there?

I have 5 identical devices that use these Arduino Nano Everys.  Only one has had this problem and it is after it was connected for several weeks.  One day, it just stopped working and when I checked it out, it appeared that the Arduino Nano Every was malfunctioning.  I replaced the Every, and now the defective device works fine.

Still the same answer. You are right that the TMUX chip shouldnt have fried the Arduino. So I can only guess, that something else happened, for example a short, maybe only for a short time. But how should someone find out, what exactly happened? Imagine I would ask you "My car doesn't turn on anymore. I just drove the normal way home. As I drove the way with another car, it worked, so its definitely the car, which has problems. What could have happened?" There are many possible answers to that question. Without information on what exactly happened when the error occurred, nobody can say.

Is there anything connected to the MUX, which you didn't mention?

Just using the Arduino to switch the MUX back and forth between sources.  The MUX is connecting and disconnecting network wires.  Just turning on and off network connectivity, so no major voltage or amperage that would cause the Every to fry...  Maybe I just got a defective one.  I've never had problems with them before.  I guess we'll see on the other 5 devices that I'm using, but they've been fine for the past month with no issues.

this might because of powering issue...try using different source having a good number of current capability. likely up


text:
Arduino Leonardo Pro Mini will not begin sketch when connected to BIOS not an OS
I have an Arduino Leonardo that I am using to emulate a Keyboard using the keyboard.press function with the Keyboard.h libraries. I have gotten the Keyboard.press function to work on my windows and mac- the keystroke I used was CTRL N to test- this worked well. So my ultimate goal was to emulate a keystroke ,F1, on a PC that is not running an OS- meaning I want the sketch to run in BIOS. for context, This keystroke (F1) tells the computer to use the a bootable USB to run a certain MathWorks OS.
The problem, when it is plugged in the Arduino shows that power is receieved by lighting the POWER LED but it does not begin the sketch. The RED LED that usually flashes ( TX or RX im not sure) when it is running a sketch is not happening (not illuminating).
How can I troubleshoot this and what could be happening? I have read that maybe too much serial info is going to the board so it confuses the board and does not begin the sketch.
I appreciate all the following help!!

When you have booted into Windows or OSX, how long does it take from the moment you plug the Leonardo into the computer to the keystroke happening? Are you sure that the computer isn't leaving BIOS or POST before the Arduino has had a chance to boot itself?

Because the computer doesn't have a full OS at POST time any USB keyboards attached to the system have to operate in a special "Boot Keyboard" mode.

Keyboards that implement the USB Boot Keyboard profile specified in the USB Device Class Definition for Human Interface Devices (HID) v1.11 and are explicitly configured to use the boot protocol will interrupt the CPU every time the keyboard is polled even if there is no change in state unless the USB controller overrides this behavior, and are limited to 6-key rollover (6KRO). This profile is intended to allow the BIOS to handle a USB keyboard in the absence of a USB-aware operating system. The recommended profile for keyboards that are not in boot mode in this specification limits keyboards to 6KRO and causes them to respond to an interrupt with a status report at least every half second even if there is no state change in the keyboard unless the USB controller overrides this behavior in order to implement typematic (the function that causes keys to repeat when they are held long enough). However, keyboards in non-boot mode are free to implement an alternative HID profile.
-- Wikipedia

Since it was not expected that anyone would be using the Leonardo to operate in the BIOS that functionality has never been implemented. The choice was to implement the entire system, which would have left less room for your sketch, or to just implement the parts that the majority of people would find useful (that is keyboard, mouse, joystick, etc) and leave out the extra stuff, leaving as much room for sketches as possible.
They chose the latter, since as I am sure you are well aware: "The needs of the many outweigh the needs of the one".
For your rather specific case it may be easiest to butcher an old USB keyboard and work out which pair of inputs to the matrix, when connected together, perform the function you require and design some small interface circuit to allow the Arduino to trigger that function.

Thanks for the Input, you were quite right Majenko. The keyboard.press does not work in BIOS. The problem has been solved by a patch ( I'm not sure if that's the correct terminology) I found on github. By a Nicohood, here is the project if anyone find this having the same issues as me.https://github.com/NicoHood/HID?files=1


text:
Esp8266-01 AT commands returns random chars and/or "ERROR"
I'm trying to make my esp8266 work with my arduino.
But when I send AT commands I get some weird symbols and some functions return "ERROR"
Here's the code I'm using.
#include "SoftwareSerial.h"

SoftwareSerial esp8266(6, 7); // RX, TX

void setup()
{
  Serial.begin(9600); // serial port used for debugging
  esp8266.begin(115200);  // your ESP's baud rate might be different
}

void loop()
{
  if(esp8266.available())  // check if the ESP is sending a message
  {
    while(esp8266.available())
    {
      char c = esp8266.read();  // read the next character.

      Serial.write(c);  // writes data to the serial monitor
    }
  }

  if(Serial.available())
  {
    delay(10);  // wait to let all the input command in the serial buffer

    // read the input command in a string
    String cmd = "";
    while(Serial.available())
    {
      cmd += (char)Serial.read();
    }
    // send to the esp8266
    esp8266.println(cmd);
  }
}

Here's the Serial Monitor:
AT

OK
AT+RST

OK

 ets Jan  8 2013,rst catse:2, boot lode:(3,7)

loab 0x40100000& len 1396, qoom 16
tail 4C�,kk�������e
load 0x3fge8000, len 776, room 4 tak0  t0�v�
�!jH+��
����(j5�!
,�2%1�

j
�sl��o�
Ai,Thinker Technology Co. Ltd.

invalid
AT+CWMODE?

+CWMODE:1

OK

AT+GMR

AT version;0.25.0.0(Juo  5 2015 17:27:16)
SDK version:1.0
ryJ 0

AT+CWLAP

+CWLAP:(4,"�P��R�*bj��b���*��2��*����Ҋ�b�Jj
��*A�B�br������Յź�aj��b����2j
":6�*AՉ����J
"�́������

The commands where, AT, AT+RST, AT+CWMODE?, AT+GMR, AT+CWLAP
Why am I getting this weird symbols and etc? I haven't upgraded the firmware, should I?  There other commands I tried return "ERROR" or even "ERROQ"
I don't have a USB to TTL or any other board. I connected my board in the arduino with this schematic:

Cap = 10uF
VolReg = LM1117 3.3v

ESP8266 is a 3.3V device that means it's logic HIGH is not 5V. That means you need to convert ESP's serial output from 3.3V to 5V logic and serial input must be converted from 5V to 3.3V to avoid damaging the ESP. It is not meant to be fed 5V signals!

I'm not feeding 5v to my ESP. But do I have to step up the output signal from 3.3v to 5v? How can I do this?

Yes you are. Look at digital pin 7 and 6 they operate at 5V, ESP8266 is not a 5V device. So signals going from Arduino to ESP must be converted (5V->3.3V) and signals coming from ESP to Arduino can be converted, but Arduino should handle 3.3V HIGH just fine (to minimize possible issues you might want to do this). TisteAndii has mentioned it in his answer too.

SoftwareSerial is reliable only up to 9600 baud or so. You can either swap ports and use Software serial as your debug output (but requires disconnecting/reconnecting the ESP8266 chip each time you upload to the UNO); or write a short sketch to set the device's baud rate to 9600 baud (and convince yourself that at least that much ran OK!) and set your SoftwareSerial to that rate.

The problem is mainly in using Serial and SoftwareSerial together. Or it can be due the esp getting less current than it requires from the Arduino(you are also damaging your Arduino!), use an external 5V source (I use my computer USB)
Why dont you directly use Serial for communication with pins 0 and 1. Just upload a blank sketch, connect Arduino Tx, Rx to esp's Tx, Rx(reverse Tx, Rx if not working). What you type into Serial will then be sent to the esp. Later if you wish to communicate to esp in sketches, use only SoftwareSerial.
Also, the esp is not 5V tolerant so you need to use a level shifter(like the cd4050 ic) or a voltage divider(less efficient) for signals from the Arduino to the esp. 3.3V is considered as a logical HIGH so you dont need to do any changes for signals from esp to the Arduino.
I highly recommend getting a USB TTL converter, this will save you a lot of headaches and debugging will be easy. I did things without it for 1-2months and now I can totally feel the difference.

I had the same issue before and it is a little bug in your code - while reading all the data from the serial port, you also read the CR & NL and then you send that as a line (with probably another NL). I solved it as such:
  if(Serial.available())
  {
    String command="";
    uint8_t c=0;
    while(c!=10) // read the command character by character
    {
      if (Serial.available()) {
        c=Serial.read();
        command+=(char)c;
      }
    }
    //Serial.print("Sending: ");
    //Serial.println(command);
    esp8266.print(command); // send the read character to the esp8266
  }

As you can tell, I was suspicious of the code and echoed back to make sure the reading from the Serial function. Also I went back to straight USB->Uno->ESP mode to confirm all was working, even the firmware with the 9600 Baud uploaded and then it clicked.

When I tried one simple scetch which just communicates between Serial monitor and ESP I got "ERROR" when typed AT in the monitor. Then I switched from "Newline" to "Both NL & CR" in Serial monitor and after that I got OK when typed AT.

These values mostly come when you are unable to communicate with any UART device on proper baud rate. Best is to change the baud rate of ESP8266 from dafault 115200 to 9600 using
AT+UART_DEF=9600,8,1,0,3

And then use the regular program. And you will get what you want.
#include <SoftwareSerial.h>
#include<stdio.h>
SoftwareSerial mySerial(2,3);
void get_wifi_list();
uint8_t flag = 0;

void setup() {

    Serial.begin(9600);
    Serial.println("Starting the code, initial set-up");
    mySerial.begin(9600);
    delay(1000);
    Serial.println("Inside the main loop, going to start communicating with ESP8266");
    delay(1000);

}

void loop(){

  char data[1024];
  uint8_t ch = -1;
  uint8_t index = 0;
  memset(&data,0,sizeof(data));
  char data1[200];
  uint8_t index1 = 0;
  memset(&data1,0,sizeof(data1));

  if(mySerial.available())  // check if the ESP is sending a message
    {
    while(mySerial.available())
        {
            char c = mySerial.read();  // read the next character.
            data[index] = c;
            index++;
            if(index >= 2000){
                Serial.print("Data received exceed allowed length \n");
                return;
                }
                if (c == '+' ){
                    Serial.print("got start char");
                    //data1[index1] = c;
                    //index1++;
                    //if ( c== '\n');{
                    //    Serial.print("First data1 is :  ");
                    //    Serial.println(data1);
                    //    return;
                    //    }

      if( strstr(data,"OK")!=NULL || strstr(data,"CWLAP") !=NULL){
      Serial.print ("Get reply as OK \n");
      Serial.print (data);

        }
      }
    }
  }
  if (flag == 0){
      get_wifi_list();
      Serial.println("Getting the wifi list");
      flag = 1;
      return;
  }

  if(Serial.available()){
    delay(10);
    String cmd = "";
    while(Serial.available()){
        cmd += (char)Serial.read();
        }
    mySerial.println(cmd);
      }

}

void get_wifi_list(){
  String cmd = "AT+CWLAP";
  mySerial.println(cmd);
}

The Arduino pin 7 (TX) signal must be level-shifted from 5V to 3.3V using a voltage divider, because the ESP cant handle 5V signals.
The Serial baud is a lot lower than that of SoftwareSerial plus you are spending a lot of time waiting for the whole command to come in. SoftwareSerial is also unreliable at 115200 baud. Use 57600 baud for both serial ports.

Use this code:
SoftwareSerial esp8266(6, 7); // RX, TX

void setup()
{
  Serial.begin(57600);
  esp8266.begin(57600);
}

void loop()
{
  while (Serial.available())
    esp8266.write(Serial.read());
  while (esp8266.available())
    Serial.write(esp8266.read());
}

It will do the exact same thing you want to do. Good luck.


text:
DS18B20 - Temperature a bit off?
I'm trying to measure the temperature using a DS18B20 sensor. I'm using the DallasTemperature and OneWire Libraries. The sensor is connect in Pin 10 with a 4k7 resistor between VDD and DQ (actually I'm using 4x 1k and 2x 330 ohms) as so:

Here's the code I'm using:
#include <OneWire.h>
#include <DallasTemperature.h>

#define ONE_WIRE_BUS 10

OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

float celsius;

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

  sensors.setResolution(12);

  sensors.begin();
}

void loop(void) {
  sensors.requestTemperatures();
  celsius = sensors.getTempCByIndex(0);

  Serial.println(celsius);
}

The sensor is outputing values close to the actual temperature (measure with a mercury thermometer), but a bit off.
Example:
Sensor Temperaute: 34.44°C
Thermometer Temperature: ~32°C

Why is that? And how can I fix it?

if the error is consistent (stable) you can just correct it in software, but it should be within 1/2 deg C; is your thermometer calibrated?

When the wires to the DS18B20 are short, you can use a 10k resistor as well.
The DS18B20 is accurate. If you have connected it wrong and it became very hot, then it might be damaged. But normally it is always accurate.
Many report that the DS18B20 returns a high temperature, and the cause is often something nearby that makes the DS18B20 warmer. For example an Arduino board (with a hot voltage regulator) or a computer screen or a certain air flow of warm air or even very dim sunlight. A normal thermometer does not do that, but the DS18B20 is highly influenced by warm things nearby.
Some temperature sensors have a problem with self-heating. You could add a delay of 5 seconds in the loop function, to see if that makes a difference.
To be sure you can put it in distilled water at sea level at 0°C (water and ice cubes) and 100°C (boiling water).
The picture uses pin 2 and the sketch uses pin 10. I assume that is a mistake.

Oh I see, maybe that's why, The sensor is in a protoboard in my desk, it has a bit of sunlight shining on it, should I cover the sensor? Doesn't it create the problem of airflow trapping hot air inside? I'll try the delay maybe that's why, I'm using no delay whatsoever.

Get it away from the sunlight, and, as mentioned, anything else that might be warm.

As long as the thermometer is measuring the same exact conditions as the sensor, you should be OK.  Put the bulb right against the sensor and wrap it in a rag or something.  Both would be measuring the temperature in the center of the rag.


text:
Controlling Relay Using Serial Monitor
I tried to make a program that can control a 4 channel relay (with LEDs as indicators) with a serial monitor. First time I tried to program it using a char command to make it turn on only, it worked. Then I tried to make it off only, it also worked, but when I tried to combine them, to control it to On or Off in the same program, it didn't work.
this is my code
#define CH1 2
 #define CH2 3
 #define CH3 4
 #define CH4 5
  void setup(){
 Serial.begin(9600);

pinMode(CH1, OUTPUT);
pinMode(CH2, OUTPUT);
pinMode(CH3, OUTPUT);
pinMode(CH4, OUTPUT);
digitalWrite(CH1,HIGH);
digitalWrite(CH2,HIGH);
digitalWrite(CH3,HIGH);
digitalWrite(CH4,HIGH);
 }

 void loop (){
  if (Serial.available()) {

char ser = Serial.read();

 switch(ser){
 case 'on1':

 onPin1();

 break;

 case 'on2':

 onPin2();

 break;

 case'on3':

 onPin3();

 break;

 case 'on4':

 onPin4();

 break;

 case 'off1':

 offPin1();

 break;

 case 'off2':

 offPin2();

 break;

  case'off3':

 offPin3();

 break;

  case 'off4':

 offPin4();

 break;

   }

 }
 }

 void onPin1(){
    digitalWrite(CH1, LOW);
 }
  void onPin2(){
   digitalWrite(CH2, LOW);
 }
   void onPin3(){
   digitalWrite(CH3, LOW);
 }
  void onPin4(){
   digitalWrite(CH4, LOW);
 }

  void offPin1(){
   digitalWrite(CH1, HIGH);
 }
   void offPin2(){
   digitalWrite(CH2, HIGH);
 }
   void offPin3(){
   digitalWrite(CH3, HIGH);
 }
   void offPin4(){
   digitalWrite(CH4, HIGH);
 }

with that code, I got "duplicate value", maybe because the pin is double-called. But when I tried to make it in separate swicth case condition, no error but couldn't respond to the command char

This is C++, so the single quotes are used for character literals. If you want string literal, you have to use double quotes. However, string literals can't be used in switch.
And you can't definitely use it like that if you are reading only one character.
However you can use single characters for this:
#define CH1 2
#define CH2 3
#define CH3 4
#define CH4 5

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

  pinMode(CH1, OUTPUT);
  pinMode(CH2, OUTPUT);
  pinMode(CH3, OUTPUT);
  pinMode(CH4, OUTPUT);
  digitalWrite(CH1,HIGH);
  digitalWrite(CH2,HIGH);
  digitalWrite(CH3,HIGH);
  digitalWrite(CH4,HIGH);
}

void loop (){
  if (Serial.available()) {
    char ser = Serial.read();
    switch(ser){
      case '1':  onPin(CH1); break;
      case '2':  onPin(CH2); break;
      case '3':  onPin(CH3); break;
      case '4':  onPin(CH4); break;
      case '5': offPin(CH1); break;
      case '6': offPin(CH2); break;
      case '7': offPin(CH3); break;
      case '8': offPin(CH4); break;
    }
  }
}

void onPin(int8_t pin) {
  digitalWrite(pin, LOW);
}

void offPin(int8_t pin) {
  digitalWrite(pin, HIGH);
}

Or you can toggle the relay states.
Test strings as commands are little bit harder to use as you have to read whole command (or use state machine). Following example is little bit unnecessary hard but it's working...
constexpr uint8_t     channels = 4;
constexpr uint8_t ch[channels] = { 2, 3, 4, 5};

template <uint8_t pin, uint8_t val> void setChan() {
  digitalWrite(pin,val);

  Serial.print("setChan: "); Serial.print(pin);  Serial.print(' ');  Serial.println(val);
}

using action_t = void(*)(void);

action_t  on_actions[channels] = {
  &setChan<ch[0],LOW>,
  &setChan<ch[1],LOW>,
  &setChan<ch[2],LOW>,
  &setChan<ch[3],LOW>
};

action_t off_actions[channels] = {
  &setChan<ch[0],HIGH>,
  &setChan<ch[1],HIGH>,
  &setChan<ch[2],HIGH>,
  &setChan<ch[3],HIGH>
};

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

  for (auto pin : ch) {
    pinMode(pin, OUTPUT);
  }
}

String command = "";
action_t action = nullptr;

void loop() {
  if (action != nullptr) {
    action();
    action = nullptr;
  }
}

void serialEvent() {
  if (Serial.available() > 0) {
    char inChar = (char)Serial.read();
    if ((inChar == '\r' || inChar == '\n')) {
      if (command.length() > 0) {
        Serial.print(command);
        if (command.startsWith("on")) {
          uint8_t channel = command.substring(2).toInt()-1;
          if (channel < channels) {
            action = on_actions[channel];
          }
          Serial.print(" On="); Serial.print(channel+1);
        } else if (command.startsWith("off")) {
          uint8_t channel = command.substring(3).toInt()-1;
          if (channel < channels) {
            action = off_actions[channel];
          }
          Serial.print(" Off="); Serial.print(channel+1);
        }
        Serial.println();
        command = "";
      }
    } else {
      command += inChar;
    }
  }
}

I have learned about switch case purposes, I i do like that, but I need to use specific "text" instead of single text 't'. How to do that? @kiiv


text:
RF24 Network and Payload
i struggle to figure out the max payload for the RF24 Network library without payload fragmentation.
It uses a NetworkHeader with the Attributes from_node, to_node, id, type and reserved.
This must be send to and lowers the amount of Bytes of the payload.
Can any one tell me how many Bytes I can write without sending two packages?

According to the source code:
const static unsigned int max_frame_payload_size = MAX_FRAME_SIZE-sizeof(RF24NetworkHeader);

that would be 24 bytes. Maximum lenght of payload for NRF24L01+ is 32 bytes and the RF24NetworkHeader seem to be 8 bytes long. So you can send up to 24 bytes in one package.
EDIT:
Here is the stripped RF24NetworkHeader declaration code from which can be seen sizeof(RF24NetworkHeader) is 8 bytes.
struct RF24NetworkHeader {
  uint16_t from_node;           // 2 bytes
  uint16_t to_node;             // 2 bytes
  uint16_t id;                  // 2 bytes
  unsigned char type;           // 1 byte
  unsigned char reserved;       // 1 byte
  static uint16_t next_id;      // static member doesn't count for sizeof()
  RF24NetworkHeader() {}
  RF24NetworkHeader(uint16_t _to, unsigned char _type = 0): to_node(_to), id(next_id++), type(_type) {}
  const char* toString(void) const;
};

Thanks, I hoped it is written somewhere in the library docs but this approach sounds very plausible too.

Maybe it even is written somewhere but I've never used Arduino and I don't even have one so I don't know :-) I've been using AVRs for years but only with AVR Studio and ISP programming. Now that you said, if you look at the source of the .h file, there is the: The actual frame put over the air consists of a header (8-bytes) and a message payload (Up to 24-bytes), line in the comments so it might have been picked by some doc generators.


text:
2G/3G vs 4G/LTE Cell Connectivity for Sensor Prototype?
Would love any advice on Arduino cell connectivity. From what I understand:

2G (GSM/GPRS) is a dying technology. AT&T is shutting down its 2G network on Jan 1, 2017.
2G (CDMA) will have a longer lifespan than GSM in the U.S., although the options for CDMA modules are much more limited than GSM.
3G has poorer coverage than 2G and is no longer growing.
4G is overkill but is also future-proofed.
4G LTE ^ ditto

I am prototyping sensors that will send GPS/accel/gyro/temp data to a server every 30 seconds or so. They will be in the U.S., operate outside of wifi range, and likely not move very much (roaming isn't a factor).
Am I right in ruling out 2G GSM at this point? From what I've seen, the AT&T 4G LTE IoT Dev Kit looks like a decent option but this is the first time I've worked with IoT devices so any suggestions are welcome (http://cloudconnectkits.org/product/att-cellular-iot-starter-kit).

I'm voting to close this question as off-topic because it is about mobile network standards, not about Arduino.

2G GSM/GPRS are almost dead in the US. CDMA is still working and it would be supported atleast till 2020 becaasue it is used in M2M devices. 3G is still one of the most widely used networks and it has great coverage and it would not likely be phased out till 2024. 4G is widely deployed now and is the future.
Coming back to this from the perspective of developing hardware projects/products and availability of module for DIY use.
2G chip-sets are very cheap (~$10) and easily available with lots of documentation. Example 2g module here
3G modules have been in the market for a little while and there are a couple of modules at a good price-point with decent documentation. Example 3g module here
4g is still bleeding edge and there are not a lot of modules available for DIY users with great documentation and at a good price. I was able to find one with good documentation here.
There are a couple of other factors that come in play when you are working on a project. One is just the support and documentation around the hardware. These modems usually need a good library built around them which can handle most of the functionality and most of the time, the manufacturer gives just a datasheet specifying what all the functionality is and the user is supposed to build the libraries for them in the platform of their choice. Here is adafruit's library for the cellular module to show you the complexity. Also, when you are just using a few of these then the modules are just building blocks and it usually makes sense to use the modules with the best possible support around them.
Tl;dr, use a 3G module with good software support for your platform.


text:
Communication between Raspberry PI (Windows IOT) and Arduino with ESP8266
I'm currently working on a Home Automation project where I have a Raspberry Pi on Windows IoT which communicates with multiple arduinos running on FreeRTOS (I need multi-tasking).
At the moment the communication is through the serial port using Xbees, the Pi sends a command, and the arduino send's back a string in JSON format.
For cost optimisation reasons, I want to try to switch the Xbees with ESP8266 modules. Is it possible to get the same kind of serial communication over WIFI?Thanks.

Is it possible to get the same kind of serial communication over WIFI?

Not precisely, no - but TCP sockets are a similar concept.
You would be best programming the ESP8266 directly to implement a simple TCP to UART bridge firmware instead of fighting with the crummy AT firmware that comes with them.

Its possible to do something similar, but you could reduce the cost even more and drop the Arduinos if you can get FreeRTOS to work on ESP-8266.
These links gives you a brief guide to using the ESP8266 shield for serial over WIFI and how to program the ESP8266 directly.
https://learn.sparkfun.com/tutorials/esp8266-wifi-shield-hookup-guide
https://learn.adafruit.com/adafruit-huzzah-esp8266-breakout/using-arduino-ide
Of course you could also look at an ESP32s which is a dual core microprocessor with loads of networking stuff baked into the chip, its about £7/$8 at the moment.

Carlos, have a look at the ESP-Link project that will, I believe, provide the system you require.  As said you may be able to drop the Arduino's using ESP12's.  You may also like to consider MQTT to communicate from the Pi to the ESP's