text:
How do you figure out an efficient battery setup for a project?
I have a project where I need an Arduino Uno and 4 DC motors to run on batteries. My first thought was that I'll just hook up 3 or 4 AAs to the Arduino and a 9V to the motor drivers.
I googled to be safe and the internet consensus seemed like that method would be very inefficient. Voltage wasn't the problem, but apparently 9V have very low current and I'd be wasting money, and the Arduino wastes current like a madman. Most solutions involved buying additional hardware.
Is there a way I can efficiently power my project without buying more chips?

Our beloved admin Nick Gammon has made a very neat articile on this subject, I suggest you read it and apply as many of the methods he described.
Also, it can be worth to check the requirements of your project, how long should it work on battery to be acceptable? Set some realistic boundarys to avoid getting lost in (trying to) optimizing beyond all practical purposes.
There are two places where you can save power:
In software
The Atmega328P has a few tricks to save power.
Most notably is powering down peripheral devices and/or using sleep modes.
I believe the P version of the Atmega328 also has more power saving modes/ is more efficient overall.
Also take a look at this.
In hardware
An Arduino board has a lot of chips that may not even be neccesary on your battery project.
Most notably the USB interface chip, if you're going to run off battery, you most likely won't need this chip.
But also, the voltage regulator on the Arduino is, I believe, a linear regulator and is likely to be inefficient.
Also power/status LED's will some current.
You can choose to put a ATMega328P on a breadboard, and power it directly with a source that will be between the min/max voltage of the ATMega328P. This way you don't get the losses that a regulator will have.
If you want to use a regulator (for a higher voltage source) you should use a switching regulator, they're typically more efficient.
Mind that on low voltages, the ATMega328P can't do a 16Mhz, but it's actually a pretty interesting point, since it will consume less power on 8Mhz, or even less on 1Mhz.

But wait, you're using motors?
In a project like this, the motors are likely to consume a lot more power as the Arduino. It may not really be worth it to decrease the power useage of the Arduino.

If you can't run the motors for long enough. You will need a more efficient motor driver and/or probably a bigger battery.

Agreed, the DC motors would drain the 9V in no time.
Consider the other way around. The 9V powers the Arduino and the 4 AA batteries power the motor.
Then again, you probably don't need the 9V at all, just power everything off of the 4 AA batteries.
I suggest using a large capacitor (something in the 470-1000uF region) to hold up the supply to the Arduino. Adding a diode before the capacitor will prevent the capacitor discharging to the motors when the motors are drawing a lot of current.
Using 4x 1.5V batteries will result in a voltage of just over 6V. The diode will have a voltage drop of around 0.6V, so the resulting voltage would be 5.4V.
This voltage is to low for the onboard voltage regulator on the Adruino. It is within limits for the raw 5V input (ie. 5.5V).
Optionally you can add a 5V zener diode across the Arduino's power input to protect ti from overvoltage. A 6.8 ohm resistor is added to limit the current flowing through the zener diode. As the voltage drops below 5V, the zener diode will turn off, allowing the micro to operate down to 4.5V. If you change to a lower frequency crystal/resonator you can operate the microcontroller down to 2.7V (1.8V is possible is the clock frequency is 4MHz or less but I doubt the motors will run).

simulate this circuit – Schematic created using CircuitLab

What if you put the resistor on the same line as the zener diode? And not between the capacitor and 5V?

@Paul, The resistor would have a voltage potential across it, meaning that  the voltage across both the resistor and zener would be greater than 5V (ie. 5V + Vresistor). In short, it wouldn't limit the voltage into the Adruino to 5V. I hope this makes sense.


text:
How can I pulse a stepper motor whilst also wanting to handle other tasks?
A Polulo A4988 driver board listens for a LOW -> HIGH pulse on a digital pin to step a stepper motor.
A simple way to pulse this with a delay of say 100μs, is to use the delayMicroseconds function:
#define STEP_PIN  3
#define DELAY     100

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

void loop(){
    //heavy computation taking time
    digitalWrite(STEP_PIN, LOW);
    digitalWrite(STEP_PIN, HIGH);
    delayMicroseconds(DELAY);
}

Although this works, the issue is that all the time that the processor spends in the delayMicroseconds function is wasted. This means that if I wanted to, for example, handle inputs from a serial line, I would have no time to do this. In addition, the time for these computations to complete would result in the pulse time increasing which is not ideal as the speed of the stepper would no longer be uniform.
How can I efficiently pulse the stepper at the correct time, whilst leaving my self room to run other tasks between pulses?

P.s. This is for this project: https://github.com/joeiddon/chess_robot.

Use a library that makes the pulses for you: https://www.airspayce.com/mikem/arduino/AccelStepper/ Which arduino board do you use?

@Jot I'm using an Arduino Nano. As for the library, I am more interested in understanding how stepper control works, rather than the final outcome. :)

I that case you could have a look at the source code of AccelStepper. Having a quick look, it seems that they are using the same method as Joe Iddon describes below, with some additions to make the speed of the motor ramp up and down. An entirely different solutions is to use a timer and timer-interrupt to run code at a set interval.

@Gerben Thanks for the link, I'll take a look at the source. Also the interrupt driven system sounds interesting, I hadn't considered that. It is working well now though, so I doubt I will spend too much longer perfecting this. Thanks for the input though :)

Instead of delaying between pulses, loop around the main loop() function as fast as possible constantly checking the time to see if we should pulse the motor.
This means that computations can occur in the loop (so long as they are reasonably fast).
To implement this, the micros() function can be used to get an unsigned long representing the microseconds that have passed since the start of the program.
Then in each loop cycle, we need to check if the difference between the current time and the last time that we pulsed is >= the pulse delay. In which case, we send a pulse to the motor
However, instead of setting the last pulse time variable to the current time, we instead increment the last pulse variable by the delay time. This has the affect that even if we were slightly late in pulsing, we pretend that we did in fact pulse at the right time so that they do not drift over time.
This would look something like:
#define STEP_PIN  3
#define DELAY     100

uint32_t last_pulse;

void setup(){
    pinMode(STEP_PIN, OUTPUT);
    last_pulse = micros();
}

void loop(){
    //heavy computation taking time
    if (micros() - last_pulse >= DELAY){
        last_pulse += DELAY;
        digitalWrite(STEP_PIN, LOW);
        digitalWrite(STEP_PIN, HIGH);
    }
}

Note that there is a slight subtlety here in that the result from micros() and therefore the value of last_pulse will overflow after ~70 minutes. However, because we are taking a difference of two unsigned numbers, this method will still work, so long as micros() is never a whole cycle ahead of last_pulse which in practice will never be the case.

source: Stack Exchange

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

sort: votes


text:
Use Print library to set string variable
I need a function that has the basic functionality of the Print library, accepting different kinds of argument types and parsing them. However, I would like to then store the result in a string/char array. Does anybody know how I might utilize the Print library to do so?

RTFM: https://www.arduino.cc/en/Reference/StringConstructor

Sorry. I typically work in C. I didn't realize the string constructor was so robust. Thanks.

my StreamLib published in 2018 has CStringBuilder

You can get all the functionality of Print by creating your own class
that inherits from it. For this, you only need to implement the
size_t write(uint8_t) method that prints a single character. Here is a
simple class that inherits from both Print and String, i.e. you get
a String you can print() and println() into:
// A String you can print() and println() into.
class PrintString : public Print, public String
{
public:
    PrintString() : String() {}

    size_t write(uint8_t c) {
        *this += (char) c;
        return 1;
    }
};

And here is how you could use it:
PrintString answer;
answer.print("The answer is ");
answer.println(42);

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

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


text:
ESP8266 connecting keypad and lcd display
I have ESP8266 type -
I have added a keypad
With a standard lcd display.
I have connected the keypad from d0 to d7, however after watching some tutorials i have to connect the lcd display(SDA,SCL) to D0 and D1, where i should connect the display to when they are taken by the keypad?

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


text:
Shift Register w/ Internal Pullups?
Is there a chip that is just a parallel in / serial out shift register but with integrated internal pullups?
I could use a full-blown I/O expander but I really just need more momentary button inputs. I don't need outputs and I would rather not bother adding resistors or with writing commands to initialize the chip.

Have you considered using a button matrix instead?

No but unfortunately that doesn't really help me. Not unless there were a chip that automatically handled the decoding and output serial.

You say "more", which presumes that you're already handling some. Just change how they're being handled.

Probably doesn't exist. http://forum.arduino.cc/index.php?topic=162710.0

Logic integrated circuits such as shift registers normally do not contain pull up resistors on their input(s).  This is because they are normally connected to a totem pole driver.  Such a driver eliminates the need to avoid floating inputs.
Also, pull up resistors require current when the input is driven toward the opposite power rail.  Even though adding internal pull up resistors may not change the overall behavior of the chip, designers will avoid parts if they unnecessarily add to the over all power demand.
Based on your comments and your question, consider an old ps/2 keyboard. It is essentially a switch matrix with a built in decoder chip which may fullfill your requirements. The chip scans the switch matrix, debounces the switches and converts button presses & button releases into a serial stream of data.
Added later...
Here is a description about connecting a ps/2 keyboard to an Arduino.  Included are schematics, code examples and supporting library.
(USB keyboards are not well suited for this purpose as they require a USB Host.  As most Arduinos do not have this, a USB Host shield is required.)

I think you mean debounces... ;)

That's funny!  I should never answer a technical question on a tablet.  I'll change it. Thanks.

I guessed you had. Mine tried to change it in exactly the same way. Android?


text:
POWER_MODE_IDLE wake on any input change?
I want to be able to put an Arduino to "sleep" but I want it to immediately resume if any panel tactile buttons are pressed.
The purpose is to try to minimize any digital noise in an nearby high gain analog circuit.
My guess at this point is that I want to put the Arduino into POWER_MODE_IDLE but it is less clear to me the best way to wake up.
How can I instantly wake up from POWER_MODE_ILDE if any input changes? I don't want to have to hold down a button or even use a specific input. Is there a "catch-all" interrupt that will react immedately to a change on any or on a large set of inputs?

Look for "pin change interrupts" (PCINT).

As I mention on my page about interrupts you can use pin-change interrupts on the Atmega328P to wake from the deepest sleep mode (SLEEP_MODE_PWR_DOWN).
Example code:
#include <avr/sleep.h>

const byte LEDLOOP = 8;
const byte LEDWAKE = 9;

ISR (PCINT1_vect)
 {
 // handle pin change interrupt for A0 to A5 here

 // toggle LED
 digitalWrite (LEDWAKE, !digitalRead (LEDWAKE));
 }  // end of PCINT1_vect

void setup ()
  {
  pinMode (LEDWAKE, OUTPUT);
  pinMode (LEDLOOP, OUTPUT);
  digitalWrite (A0, HIGH);  // enable pull-up

  // pin change interrupt
  PCMSK1 |= bit (PCINT8);  // want pin A0
  PCIFR  |= bit (PCIF1);   // clear any outstanding interrupts
  PCICR  |= bit (PCIE1);   // enable pin change interrupts for A0 to A5

  }  // end of setup

void loop ()
{

  set_sleep_mode (SLEEP_MODE_PWR_DOWN);
  sleep_mode ();

  // flash to indicate we got out of sleep
  digitalWrite (LEDLOOP, HIGH);
  delay (100);
  digitalWrite (LEDLOOP, LOW);
  delay (100);

  } // end of loop

This has the advantage of consuming very little power while asleep, and also waking on any pin (of an Atmega328P).
Running on 5V at 25°C you should only consume around 150 nA of current while asleep (on a "bare bones" board without USB chip, voltage regulator or power LEDs).
Other sleep modes may use more power but wake more quickly.

The Arduino can only be woken from sleep by a change on pins 2 and/or 3.

On the hardware front, the Arduino is equipped with two interrupt
  ports: digital pin 2 and 3. So the Arduino can sense those pins for an
  event to wake up and resume execution of code.

http://playground.arduino.cc/Learning/ArduinoSleepCode
However, the datasheet indicates that any pin can be used:
http://www.atmel.com/Images/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_Datasheet.pdf Section 17. EXINT - External Interrupts

The External Interrupts are triggered by the INT pins or any of the PCINT pins.
  [...]
  The Pin Change Interrupt Request 2 (PCI2) will trigger if any enabled
  PCINT[23:16] pin toggles. The Pin Change Interrupt Request 1 (PCI1)
  will trigger if any enabled PCINT[14:8] pin toggles. The Pin Change
  Interrupt Request 0 (PCI0) will trigger if any enabled PCINT[7:0] pin
  toggles. The PCMSK2, PCMSK1 and
  PCMSK0 Registers control which pins contribute to the pin change
  interrupts.

Pin change interrupts can be used as well. Even for deeper sleep modes with disabled IO clock or with stopped oscillator.


text:
config file for Arduino Uno installed on Raspberry PI
The Arduino code shown runs successfully. My problem is configuring the Arduino IDE so it fits within the Raspberry Pi window. The second image, the built-in serial port /dev/ttyAMA0, is produced. It is blank.
The Arduino Menu bar cannot be accessed. Therefore, the Tools button and other buttons for running the code are not available. The user can adjust the width of the Arduino IDE window but cannot move it around the screen or up or down.
The /boot/config file is setup up for a Adafruit 5" Backback monitor. No other app, Thonny Pi, or the terminal has these problems.
It appears to me that the config file needs some work. That is only a guess.
Any suggestions will be greatly appreciated.

Please edit the post to remove non-code text from code tags

In Linux you can move things around in different ways. For example:

Hold ALT and click and drag anywhere in the window. The whole window will move and you can get to the edge to resize it.
Press ALT-Space then M and you can use the cursor keys to move the window around
Press ALT-Space then X and it will maximise the window to the screen size

Thank you. The command key works.

What you can do is set the default IDE window size by editing preferences.txt:
Click the link on the line following File > Preferences > More preferences can be edited directly in the file.
This will open the Arduino15 (or similar folder name) folder.
Close the Arduino IDE.
Open the file preferences.txt in a text editor
Change the editor.window.height.default and editor.window.width.default properties to your desired window size.
Save the file.


text:
How to program Arduino LCD shield with Python?
so I want to run a Arduino LCD shield with Python code..But after having some research on the Internet, I can not found any tutorial, some just give some basic code with LED.
And one things that how can I add a LCD library (LyquidCrystal.h in Arduino code) if i program in Python.
Thank you guys very much.

You cannot program an Arduino with Python

It's like @chrisl wrote in the comments. You cannot program Arduino with python.
You can however upload an open source Firmata protocol implementation onto the Arduino and then write python code on your PC that will send commands to the Arduino by USB cable to tell it what to do.
This way you actually execute your code on PC, but control Arduino pins. Only drawback is that you need to have a PC connected to the Arduino at all times. This is not very practical.
There is a really nice tutorial here
Example python code looks like this:
import pyfirmata
import time

board = pyfirmata.Arduino('/dev/ttyACM0')
while True:
    board.digital[13].write(1)
    time.sleep(1)
    board.digital[13].write(0)
    time.sleep(1)

I'm afraid that only solution to controlling LCD shield this way without writing any C is to write the entire LCD library in python basing on pyfirmata calls to control the Arduino pins. It's not as hard as it sounds, and even a beginner could easily succeed.

However, if the task is to run an existing Arduino LCD library, it has to run on the Arduino.
If it needs data from a python script, it's questionable, whether firmata is the proper transport mechanism. And if that python script gets all data from the Arduino, one should consider to run that logic directly on the Arduino, instead of that generic firmata overhead.

@DataFiddler Yes, if I can not program all things on Python..so I wonder that if there any ways to pass data from Python (for ex. "Hello World") to Arduino LCD sheild.

As it's unclear to me what you want to outsource from Arduino to a Python node, I have no idea, whether pyfirmata or pyserial is your way to go. ( If at all, IMO )


text:
Multiple Atmega328p wired communication
I am using multiple ATMEGA328Ps  (4 ATMEGA328P) (OR Arduino Unos). The distance between two farthest ATMEGAs is 14 meters (One is Master Device and Other is Node), and other 3 are connected to each other at a distance of 3 meters from the Master Device.
I have a case where i cannot use Wireless communication hence i will have to go Wired. I am also looking to achieve the Mesh topology if possible.
There are many examples on the internet regarding this case but still i am not be able to choose/compare which would be more reliable.
Please suggest me the best solution to work on this.
Thanks.

Mesh is kind of silly, if it's wired. You haven't told us what you want to communicate. That is; how much data, at what data-rate? Master to slave only, or bi-directional?

a token-ring-like topology will be easier to manage; just give each device a unique ID and each message a list of IDs which are intended recipients. Once a node receives the message, it removes its ID and forwards the message, if there are any IDs left to consume... Somewhat like I2C.

How about 1-Wire? Here is an example of a 1-Wire Master and Slave that allows distributed digitalRead/Write/pinMode/etc. Master https://github.com/mikaelpatel/Arduino-OWI/blob/master/examples/Arduino/Arduino.ino, and Slave, https://github.com/mikaelpatel/Arduino-OWI/blob/master/examples/Slave/Arduino/Arduino.ino.

@Gerben : Thanks for the quick reply. My Goal is to achieve bi-directional , one master and multiple slaves ( request , response , ack , broadcasting ), long distance upto 20 meters , max to max 20 bytes of data to be sent.

@dandavis : thanks i will think about this. nice idea.

@MikaelPatel : 1-wire not recommended over long distance.


text:
HC-SR04 systematically finding a weird value
I have a HC-SR04 connected to my Arduino. its all working very nice. Yet with a constant interval a weird value appears (see the Serial Plot picture). I am wondering what causes this. I will soon upload my Sketch (Making it bit more readable).
Or are there to many possible factors that could influence the HC-SR04 behaviour that it is impossible to determine the cause?

Y-axis shows distance in cm, x-axis shows iteration (once a second)
Thanks in advance!
Kind Regards, a fellower Arduino User

It's probably less likely the HC-SR04 and more likely Arduino interrupts and micros() jitter.

Yes I am using millis() ! To make my distance sensor not lockup the remaining of the sketch

I am thinking more with the pulseIn() function that is commonly used for reading the HC-SR04. That uses micros() for the timing, and if that gets interrupted (by the timer0 millis() interrupt, or a serial interrupt, for instance) it could skew the results.

Sounds logic, aswell as I do use PulseIn and serial connection. Is there a way I can Predict when it occurs?

For absolute precision, you should be using one of the timer Input Compare peripherals, though I don't know of an Arduino library offhand that does it.


text:
Rounding up and Down
My arduino is meisuring the tempature and gives values like: 28.58 Degrees Celcius. I would like to round this up to one decimal. I could make the variable one shorter by cutting the "8" off which would desplay 28.5.
Yet this feels a bit like cheating as it mathimatical not correct. Does anyone know how to round up/down. Which would show my tempature as 28.6.
Extra advice needed. I am sending the tempature by Serial to my RPi which has a python code running. Would you suggest doing the rounding in the Arduino code or in The Python code.
Thanks in Advance!

Wouldn't it be better to round to nearest rather than systematically rounding up.

Yea I would love to able to round it the mathematical way. 28.65 <, will become 28.6 and 28.65 ≥, will become 28.7

Then let Serial.print() do the rounding, as per @Jot's answer.

Personally, I would not round until the data is on the Pi. Why lose precision when you don't need to? What if, at some later point, you decide you need to do more calculations on the data on the Pi? Python has a round() function built in.

As far as I know, the Serial.print (or println) does rounding up and down. All you have to do is take a float variable and do Serial.print( value, 1);
Without extra parameter, the default is choosen, which is 2 decimal digits: Serial.print( value, 2);
Why do you want to shorten the bytes over the Serial ? You can just as well send two decimal digits and process the value in Python.

Thats what the last part of my question is about ;) wondering where to process, in python on my Rpi or before sending.

Any rounding should be done as close to the final output as possible. If your serial port is fast enough then send 2 or 3 digits and round when the Pi is outputting the data. You don't want to base calculations on rounded values if you can help it, that introduces the possibility of errors.  That said it's a complete waste of time sending random numbers, if the temperature sensor has an error of +/- 1 degree then the first decimal place may be useful, anything after that is meaningless.

Okay agreed! It more precise to process at the final stage, yet the accuracy of the sensor is not there, so I will save bandwidth by using Serial.print(value, 1);

You can round in C by multiplying for the significance, adding +0.5, round down (equals as casting to an integer) and divide.
float f_rounded = ((int) (f * 10.0 + 0.5) / 10.0);

28.6 will be:
float f_rounded = ((int) (28.6 * 10.0 + 0.5) / 10.0)
                = ((int) 286.5) / 10.0 = 286 / 10.0 = 28.6

In Python it is equal (except the cast operator is int(...)
Update: for negative numbers +0.5 should be -0.5
Credits for Edgar Bonet: using round works for both positive and negative numbers:
float f_rounded = round(f * 10) / 10.0;

This would round -28.58 to -28.5.

@JohnnyMopp Updated my answers, thanks for the comment

Why not just float f_rounded = round(f * 10) / 10.0;? This handles both the positive and negative cases.


text:
compiler says I have to declare my hexidacimal I try to compare
#include <IRremote.h>

int RECV_PIN = 11; // IR Receiver - Arduino Pin Number 11
IRrecv irrecv(RECV_PIN);
decode_results results;

int led = 12;

void setup() {
  pinMode(led, OUTPUT);
  digitalWrite(led, LOW);
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
}

void loop() {
  if(irrecv.decode(&results)) //this checks to see if a code has been received
{
    if(results.value == FF6897) //if the button press equals the hex value FF6897
    {
        digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
        delay(1000);               // wait for a second
        digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
        delay(1000);               // wait for a second//do something useful here
    }
    irrecv.resume(); //receive the next value
}
  }

The issue is in the second if in the void loop the error I get is

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

why does he do this? Why doesnt it just accept my IRcode for comparison.

I think this is a good question, because it isn't obvious why its failing unless you know C/C++, the numbering prefix is not intuitive.  Maybe a little research before asking would have helped, but...

Nothing here that hasn't been covered in comments already but just putting it in the form of an answer to save digging...
How is the compiler supposed to know that a number is hex rather than decimal?
Sure 1234beef is obviously hex but what about 12345678? Is that hex or decimal?
You need some method for the compiler to know.
You also need some way for the compiler to know if something is a number or a variable. Take the code if (x == deadbeef) {...} is deadbeef a hex number or a variable name?
C uses a very simple convention. If it starts with a number it's a number, if it starts with a letter it's a variable. This is why variable names can contain numbers but can't start with them.
If an integer starts with an 0 e.g. 0123 then it's in octal.
If an integer starts with 0x e.g. 0x123 then it's in hex.
If an integer starts with something other than a 0 e.g. 123 then its in decimal.

e.g.
printf("123 = %d\r\n0x123 = %d\r\n0123 = %d\r\n", 123 , 0x123 , 0123);

returns
123 = 123
0x123 = 291
0123 = 83

This convention, especially the 0x prefix for hexadecimal, is very widely used in other programming languages.

By comparing my code to another one, I found out that putting 0x in front of the hex will fix it, I don't have a clue why this is though.

Hexadecimal literals are typically preceded by 0x, else how would the compiler distinguish the variable name deadbeef from the hexadecimal value deadbeef?

There is also the prefix 0 and b for declaring Octal (base 8) and binary.  Octal can cause you issues when declaring decimal numbers that you want to pad with zeros, i.e. 00100 is 64 not 100 with to leading zeros.

@CodeGorilla the 0b prefix for binary isn't very standard yet. I believe C++ 14 makes it standard but c++ 11 is only just becoming common so that's at least a few years off general usage. Until then its down to individual compilers and extensions whether it's supported. Personally right now I'd avoid it even if the tool I was using supported it, the lack of portability isn't worth the minimal benefits it gives.

@Andrew - The only place I had seen it was here :)  I agree about avoiding binary, but mainly because hex is much easier.


text:
Partially clean a LCDScreen
I have connected an 16x2 LCD to my Arduino. It shows my Room Temperature and Behind that variable is the string "Celcius". Everytime the temp is diffrent than shown on the screen it updates the screen by clearing the screen.
Is there a way I could clear just a part of the screen? or is this technically impossible. Or is it a waste of code? :D
Thanks in Advance!
Anton

The easiest is to clear the entire screen (I'm sure there is a function for that).
What you also can do:

Create lines which are 16 characters wide and print them, so the old text is overwritten
More complicated: store the text that is written in two strings (one per line) and check where are not spaces, to overwrite it with spaces to clear.

You would have to do a performance/time check to see what works best.
If performance is not an issue (which I doubt), keep it simple and just overwrite the two lines (without a clear, assuming you call the clear function yourself).
Another solution is to keep the word Celcius always on the same location... this means you might have to change formatting:

_28.6 Celcius
__3.8 Celcius
_-12.3 Celcius

Where _ are spaces (so the word Celcius is always on the same location)

and about the LCD itself, is often refreshing and rewriting the same string, dangerous for its durability?

I doubt, an LCD display has diodes, the same diodes that can blink many times per second without deteriorating.

Sending "Celsius " with a trailing space or two would likely accommodate changes in the number width, but using a fixed-width number format with zero blanking and keeping the "Celsius" in a fixed position might be more pleasing - it's almost a matter of opinion.

There is only a function to clear the entire LCD display, and that is in most cases visible.
Clearing only a few characters is done by writing spaces to it. After that you can write the new temperature to that part of the display.
You could also create a fixed length format of the temperature and use spaces to fill the unused characters. Then you can use just one write to the display.
It begins by designing the layout of the text on the display. Then you know where everything will be and how many characters are needed for each value.
@MichelKeijzers, I'm aware that my answer is almost the same as yours, but your answer seems to be for clearing an entire line. I would write the word "Celsius" or "°C" to the screen just once, and only update the value of the temperature.


text:
serial data gets spoiled
I use this small program on my Raspberry Pi to recieve a string sent by my arduino.
import time
import serial

ser = serial.Serial('/dev/ttyACM0', 9600)

def check_for_command():
    bytestoread = ser.inWaiting()
    if bytestoread != 0:
        temp = ser.read(bytestoread)
        print(temp)

while 1:
    check_for_command()
    time.sleep(0.1)

the code on the arduino is rather simple:
void setup(){
Serial.begin(9600);
}

void loop(){
Serial.println(“Hello Pi”);
delay(2000);

the annoying part is. I recieve this:

b'Hello Pi\r\n'

instead of the clean

Hello Pi

How do I get rid of those extra bits without using a list for each character.
Thank in advance!

The python code does not need to be anywhere near this complicated.  Once you open the device to the handle ser, then all you need is --
linenin=ser.readline() --- and it is good that you are using -- Serial.println -- on the Arduino that sends the \n character at the end of the string so it will work just fine.  Then all you need in Python is --  print linein -- to see what you have received.  Nothing complicated is required.  Just treat it like a file, and remember that ser.readline() is a blocking function.  It will stop everything and wait for input.

The b prefix in Python 3 just means that it is a bytes literal. It's not part of the output, that's just telling you the type.
The \r\n is a common Carriage-Return and Newline line-ending characters. You can remove that from your string by calling strip().
Since these are floating-point numbers being returned, I'm guessing you're going to want to use them in some way after they are read, too:
import serial

ser = serial.Serial('/dev/ttyACM0', 9600)
while True:
   value = float(ser.readline().strip())
   print('New value is {0:0.2f}'.format(value))

See also:

What does the 'b' character do in front of a string literal?

trying to use your lines it gives me a format error on the last line. just before the .format

Can you copy and paste the exact error?

fixed that error found a new one that sometimes occurs, the first problem was: I am using python 3 so print needs brackets. :)      the other error is when by accident serial chains two numbers:  ValueError: could not convert string to float: b'21.020.5'

I have updated my code to include python 3 style prints.

and now you suggest a try and catch to avoid the ValueError?

The ValueError occurs only when serial chains two numbers, right? In that case you could either use a try and catch or increase the delay in Arduino's loop.

if I would like to send a string instead of a float and want to get rid off the b prefix? changing float into string doesnt work.

What is the exact error message?

Use this line
temp = ser.readline(bytestoread).decode('ascii')

instead of
temp = ser.read(bytestoread)

As the bytes sent by Raspbian is encoded in UTF-8, use the following line in order to avoid a strip() at a later-on stage:
temp = ser.read(bytestoread).decode('utf-8')

Well, it's not the Raspi sending but the Arduino. And decode() does not strip the '\r\n' from the decoded string.


text:
everything works independitly but not together. Piezo not generating a tone
My goal with the code is simple. Let the Piezo buzz when temperature reaches 25 degrees. My piezo is hooked up correctly, because It makes a buzz when the arduino boots or when I put this line of code anywhere else in my code.
I also checked if the If statement was called. And yes it is! So the if statements is happening yet I don't hear a buzz.
I am aware that I am breaking my seven segmented screen by using the delay. But I don't mind the screen working when the buzzer is.
void loop()
{
  //local vars
  if (millis() % 5000 <= 10) {
      float lm35TempC = lm35.getTempC();
      sevseg.setNumber(lm35TempC, 2);
      if (lm35TempC > 25.00) {
        tone(1,500,1000);
        delay(3000);  <------- WHERE IT PROBABLY GOES WRONG
      }
      if (lm35TempC < 25.00) {
        noTone(1);
      }
  }
  sevseg.refreshDisplay(); // Must run repeatedly; don't use blocking code (ex: delay()) in the loop() function or this won't work right
}

To conclude: The If-statement is working yet I don't hear a buzz. How does this happen?
Thanks in Advance!

The windows of millis() % 5000 <= 10 is only 10ms every 5 second. How long does the function sevseg.refreshDisplay take? more than 10ms?

No I dont think that function will take much longer, but I have to admit its a ugly way of creating a delay of 5 seconds, but if I for example increase 10 to 50, my display will sometimes refresh twice within a short timeframe

Then stop doing it in a ugly way. Use https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay with an interval of 5 seconds. After that you have to fix the tone, I think that is ugly as well. A tone with duration will delay and does not need noTone. There might be hardware problems as well. Fix everything one by one.

You connected the piezo to pin 1? Chose other pin. Pin 1 is Serial TX. You 'pump' PWM to USB.
tone() function will make sound no matter if you have a delay there. You set 1 sec with 1000 as third parameter. It will sound 1 sec and the turn of. You do not need the delay() and noTone().
500 is low frequency. If it sounds only one second, can you catch it?
try tone(TONE_PIN, 4500, 500). with speaker it is a nice beeeep

You were right! The only reason I used pin 1 was, that I allready used all the other Digital Pins (expect 0 but that one is like 1). I have now configured an Analog Pin as output and it works Perfectly!


text:
Very bright cursos positions

As you may can I see on the picture. I try to display the word "goodbye". Yet the problem is that the cursor positions are to bright. I hooked up a 10k ohm potmeter to the Anode. To change the backlight. Is there a way to make the cursos positions less visible?
Kind Regards,
Q

Adjust the contrast pot that you should have wired in?

as the brightness of the blue backlight changes so do the cursos positions. In the end the cursor positions are equally as bright as the backlight

Which pot are you adjusting?

connected to the Anode (pin 15)

No, you should be adjusting the other pot. The contrast pot.

that one goes to ground on my setup

Well, there's your problem then. If you created the circuit properly you'd be able to adjust the contrast. As it is you have no control. Every tutorial I have ever seen has specified a pot for the contrast. They don't do that just for fun - they do it for a reason.

issue fixed: I adjusted the Anode (pin15) instead of the contrast (pin3).
Look at the conversation between me and Majenko to see the realisation.


text:
Turning on many (30) leds arduino mega
I´m new working with Arduino. Right now I have a project thar requires to turn on 30 LEDs at the same time with an Arduino Mega. The problem is that it would exceed the max current that the chip can tolerate.
It is possible to do this by turning on one LED at the time, very fast?
If it is, any clue on the code to achieve that will be apreciated.
Thank you very much
P.S.: I know there are components to expand the quantity of pins that work like that, but the idea is to avoid using one.

Do you need to run them at high brightness (=high current)?  Strobing them will have the effect of reducing the brightness, and if you don't need high brightness then you can use higher current-limiting resistors so save the effort of strobing them. If you need them to be bright, you'll need some sort of driver - the right transistor will probably be sufficient.

This page explains that the ATmega2560 could drive up to 800mA: Arduino Playground: Arduino Pin Current Limitations
There are limitations for groups of pins, so you have to be careful.
The 800mA is a lot in my opinion. I wonder how hot the chip will become.
What kind of leds do you use ? Normal 20mA leds ? Or is 10mA leds also possible ? 30*20mA = 600mA, but 30*10mA is only 300mA. The 300mA seems a lot safer to me.
With Charlieplexing the leds are not 'on' all the time. However, with the Arduino Mega 2560 you have enough pins, and you could just lower the current through the leds.
Turning them on for a short time (without Charlieplexing) is the same as turning them continuous on with a lower current.
The most common way to drive 30 leds is with a led strip. For example a led strip with neopixels. That led strip has to be powered seperately.
My advice is to lower the current for the leds to 10mA and hope that the ATmega2560 doesn't get too hot.
[ADDED] 300mA is still a lot. Start with 5mA per led for a total of 150mA when they all are on at the same time. Many modern and good quality leds are bright at 5mA.

Note that, if the LEDs are not blue nor white, and if the don't have to be individually addressed, they could be wired by pairs in series.

usually, 10ma is not much "dimmer" than 20ma, so if it's not for illumination nobody will notice.

Use external drivers, like a transistor.
If you have to tie them to the avr, use large or larger current limiting resistors. Or to multiplex so only some of them are on at a given time.

Use the MAX7919. It is a driver for multiples leds. It lets you output up to 64 leds at a high enough brightness.
https://playground.arduino.cc/Main/LEDMatrix
Its usually made to drive LED matrices or 7-segments LEDs.


text:
Questions on how to connect Arduino to Matlab through the serial port
I have an Arduino board with Intel Edison on it. I have tried to read data in Arduino from MatLab through the serial port. I'm sure the Arduino board is working because when I use the serial monitor from Arduino, it shows the data read from the Arduino board. My command is like this in Arduino:
   reading = Wire.read();
   Serial.println(reading)

I got errors in Matlab when I tried to work with these piece of code:
   s=serial('COM4');
   set(s,'BaudRate',9600);
   fopen(s);

MatLab complains that "Port: COM4 is not available. No ports are available.
Use INSTRFIND to determine if other instrument objects are connected to the requested device." I have tried with "instrfind()" in matlab and got this:
   Instrument Object Array

   Index:    Type:     Status:   Name:
   1         serial    closed    Serial-COM4
   2         serial    closed    Serial-COM4
   3         serial    open      Serial-COM4
   4         serial    closed    Serial-COM4
   5         serial    closed    Serial-COM4

I still can't get any clue on this. Can anybody help me?

I'm not a fan of how Windows handles COM ports.  I think the most successful applications scans all the COM ports and identifies with a connected device through proprietary means (for example, maybe the application is looking for the company's name as a response).  I might try to reboot (its Windows after all) with out the Arduino plugged into the USB port, bring up the device manager and open the COM section and watch which COM becomes available when you do plug in the Arduino's USB cable.  Then try connecting to that COM with matlab. Don't use anything else that may connect to that COM port.

Hi, I can't believe I forget "reboot the system" for this. Your idea works. Thanks very much.

Great news.  In order to count this question as solved: I can copy the comment to the Answer box where, if you would be so kind, accept it.

I might try to reboot with out the Arduino plugged into the USB port, bring up the device manager and open the COM section and watch which COM becomes available when you do plug in the Arduino's USB cable. Then try connecting to that COM with matlab. Don't use anything else that may connect to that COM port.


text:
What am I doing wrong with my millis()?
Im new to Arduino and have been trying to use the millis() function for an assignment of mine. I have had a lot of trouble trying to get the millis() function to work but now it seems to be working properly as far as I can tell through the serial viewer but it wont stop my loop once it goes higher than the run time. Im trying to stop my loop after 10 seconds, but it continues going and I feel like it has something to do with my millis().
 // Pin 13 is the LED

 int led = 13;        // pin 13 on the board
 int ledOFF = 8;      //led off time delay
 int ledON = 5;            //led on time delay
 unsigned long Timer = 0;      // store time
 int runtime = 10000;      // run loop for 10s

 void setup() {
   pinMode(led, OUTPUT);

   Serial.begin(9600);
   delay(1000);
 }

 void loop() {
   Timer = millis();
   int state = 0;
   while(millis() - Timer <= runtime){
     Serial.println(Timer);
     if(state==0){
       digitalWrite(led,LOW);
       state = 1;
       delay(ledOFF);
     }
     else{
       digitalWrite(led,HIGH);
       state = 0;
       delay(ledON);
     }
    }
   }

as @Andre said on comment, you give variable 'Timer' a new value each loop. One of the solution is putting Timer = millis(); on the void setup instead on void loop

Thanks for your reply as well, that was exactly my problem. I cant believe I been over looking that all this time.

You are always re-init Timer as millis on every loop. So millis() - Timer is probably always a few milisecond and never reaches your runtime value.


text:
RF24Mesh master-base node communication delay
I'm trying to build a mesh network using 4 nRF24L01 modules directly connected with Arduino Uno where 1 module is master node and the rest are base nodes.
The workflow is exactly as follows
I'm sending a command in the Arduino IDE serial monitor. The master node receives this command and send it to other base nodes. There's no problem receiving the command on the base node side (from master node) as well as sending the command on the master node side (to base nodes). Upon receiving the command from the master node, base nodes successfully able to read the command and send the response. No problem at all.
But when the master node receives the response status from the base node(s), there's the problem. Master node is not receiving the data immediately. I have to send the command from the Arduino serial monitor repeatedly and on the 10th time, the master node is able to read the response status from the base node(s). Exactly on the 10th times every time.
Here's the source.
master node
// global variables
int dat2;
String temp1 = "";
boolean actualDataSent = false;

// get input from arduino serial monitor

 while (Serial.available() > 0) {
      // my command
      String temp1 = Serial.readString();
}

// write block
if (actualDataSent == false && temp1 != "") {

    // send this data to the base node one by one char
    for (int j = 0; j < mesh.addrListTop; j++)
    {
      for (int k = 0; k < temp1.length(); k++) {
        char ch = (char)temp1.charAt(k);
        Serial.print("NodeID: ");
        Serial.print(mesh.addrList[j].nodeID);
        Serial.print(" RF24Network Address: 0");
        Serial.println(mesh.addrList[j].address, OCT);
        RF24NetworkHeader header(mesh.addrList[j].address, OCT);
        Serial.println( network.write(header, &ch, sizeof(ch)) == 1 ? F("Send OK") : F("Send Fail"));
      }
      actualDataSent = true;
    }
    temp1 = "";
  }

// read block
else if (network.available() && actualDataSent == true) {
    RF24NetworkHeader header;
    network.peek(header);

    switch (header.type) {
      case 'M':
        network.read(header, &dat2, sizeof(dat2));
        Serial.print("Got: ");
        Serial.print(dat2);
        Serial.print(" from RF24Network address 0");
        Serial.println(header.from_node, OCT);
        actualDataSent = false;
        break;
      default: network.read(header, 0, 0); Serial.print("Not M case"); Serial.println(header.type); actualDataSent = false; break;
    }
  }

base node:
//global variables

String mypayload = "";
int res1;

// receive command from master
while (network.available()) {
    RF24NetworkHeader header;
    network.read(header, &payload, sizeof(payload));
    mypayload.concat(payload);
  }
  if (mypayload != "")
  {
    Serial.print("Received data: ");
    Serial.println(mypayload);
    if ((mypayload == "100%"))
    {
      res1 = 1;
      Serial.println("Turn ON");
      if (!mesh.write(&res1, 'M', sizeof(res1))) {
      if ( ! mesh.checkConnection() ) {
        Serial.println("Renewing Address");
        mesh.renewAddress();
      } else {
        Serial.println("Send fail, Test OK");
      }
    } else {
      Serial.print("Send OK: "); Serial.println(res1);
    }
    }
    else if (mypayload == "0%")
    {
      res1 = '1';
      Serial.println("Turn OFF");
      if (!mesh.write(&res1, 'M', sizeof(res1))) {
      if ( ! mesh.checkConnection() ) {
        Serial.println("Renewing Address");
        mesh.renewAddress();
      } else {
        Serial.println("Send fail, Test OK");
      }
    } else {
      Serial.print("Send OK: "); Serial.println(res1);
    }
    }
    mypayload = "";
  }

What output are you getting on the terminal (on the base node) for tries 1 .. 9 ?

@KennetRunner - on base node's terminal the output is always same i.e. send is OK. Apparently it seems that there's no problem at the base node. The problem is only at the master node, I suppose. But the question is why the desired status would come on the 10th time?

The nRF24L01 "ACK_PAYLOAD" feature allows for two-way data transfer in a single radio transaction.  This is more complicated to set up but plenty of tutorials can be found online, on arduino stackexchange and of course another very helpful source is the nRF24L01 data sheet.  This should solve your problem by ensuring the master/slave radio messages are sent in the same, rather than independent, radio transactions.


text:
How to make auto keyboard using arduino nano V3.0 ATmega 328P ?
I have an Arduino Nano v3.0 ATmega328p board. I want to make an auto keyboard that types in a string when its plugged in. I have googled and found that these chips doesn't support that feature unlike "pro micro". keyboard.h is not supported with this chips. So is there any alternative way to use it as a HID and emulate keyboard inputs using any other additional shield other than using the built in USB port. Im a noob in this field, please help. Thanks in advance.

You can emulate USB on the atmega328. Look at the VUSB project. You just need a few resistors, diodes, and a USB cable.

I found this link : http://www.practicalarduino.com/projects/virtual-usb-keyboard Is that what you've been looking for?

Thank you @Gerben If you could give me some useful links so that i can get the basic codes, that would help me :)

Just google "vusb" and "vusb keyboard". Maybe some of the Adafruit guides for their pro trinket which uses VUSB. I'm currently on my mobile so linking is kind of difficult.


text:
Global variables use to much space in the dynamic memory
I use two simple libraries (see 1, 2) I found online for my code on the Arduino Uno, unfortunately I also use ROS and all those libraries take away to much space, when I compile my code I get this error:
Global variables use 2,112 bytes (103%) of dynamic memory, leaving -64 bytes for local variables. Maximum is 2,048 bytes.

I shortened my Strings, but it was not enough. How can I change the code in the libraries to achieve less used memory?
I think I don't understand the concept of global variables completely. For example I changed all double variables in the libraries to float variables, but it did not change dynamic memory use at all. How can I use less memory?

Did you placed your string literals into the flash memory?

I shortened them down to 1 letter, to see how far it reduces the size, but putting it into flash memory won't solve the problem, since it is not enough.

Well, then you should provide your code so we can try it...

I checked and about 75% of global variables are already used by the libraries I use. Since they are open source I was hopping to change those. They are provided in the links I gave in my question.

A very generic description: Variables that hang around (global, static, ect) are assigned their own memory location in RAM, variables that have limited scope are temporarily assigned a memory location in the RAM in an area called the stack & variables that never change can be put into program memory.  On an embedded processor this usually means putting variable into flash.

This is "off the cuff" advice, hence it is only a comment, not an answer, but, if you are hurting for memory why not switch to an ARM based Arduino.  Many ARM based Arduino's have much more memory than, say, an Uno.

How many of those objects do you instanciate? The most obvious candidate for memory saving is double lastInputs[100]; in class PID_ATune. It takes 400 bytes. If you shorten this array, make sure you don't access it out of bonds.

@EdgarBonet I reduced the number to 80, it helped, thank you! Why does it not change memory consumption if I change the double to float?

@Jonas, because on arduino, double and float have the same size : https://www.arduino.cc/en/Reference/Float or https://www.arduino.cc/en/Reference/Double

The first library defines a class PID_ATune which contains a lot of members, including an array of 100 double, i.e. 400 bytes for each instance of PID_ATune. Not sure so many double are needed there, but you could first try to reduce this number.

have you solved this, I am facing the same exact issue! as I am currently using the autotune library ! and can't optimize the sample code! please help

Unfortunately I could not solve the issue. I think I moved to a larger microcontroller that time. Sorry. You could try to use the source code of the autotune library directly and fine tune it?

When you write a program, some memory can be determined in compilation time, due to it's predefinition, (float and double in Arduino - not Due model - use 4 bytes each - in Due, double uses 8 bytes for 64 bit precision).
But there is some memory that only can be known at runtime; where we are talking about objects (or arrays determined by user input). In these cases, programs need to dynamically allocate memory, for which the C++ language integrates the operators new and delete. More info at: Dynamic memory.
You should control the creation of objects and arrays (those are created with new and then deleted with delete).
If your requirements are greater than the resources of any Arduino (except Arduino Due), you should change to the Due model, which has more memory space and computing power (but changes the 5 V to 3.3 V, be careful).

There is also the Mega 2560, which has the same architecture as the Uno (AVR), but 4 times as much RAM.

@jonas I had a similar problem not quite exceeding the limit.  One item you can do is move the strings to Flash.
<pgmspace.h> there is the definition of PSTR which will place the literal in flash
the patternname, which we normaly just use strcpy, we need to use strcpy_P.
strcpy_P states the string will come from Flashmemory and copy it into SRAM space.  Once it is in SRAM sapce we can maniputate it all we want.
for example:
setPatternName((char*)PSTR("My PatternName"));

void setPatternName(const char* text) {
  memset(patternName, MAX_PATTERN_NAME_LEN + 1, 0 );
  strcpy_P(patternName, text);
  int length = strlen(patternName);
}

This should have a significant reduction in mem usage.

char buf[50];

char* tm1Txt (byte num){
  if (num == 0){strcpy_P(buf, (char*) F("t1 - Задepжka koмaнды xoд"));}
  if (num == 1){strcpy_P(buf, (char*) F("t2 - Bpeмя cepвoфиkcaции "));}
  if (num == 2){strcpy_P(buf, (char*) F("t3 - Bpeмя дoтягивания   "));}
  if (num == 3){strcpy_P(buf, (char*) F("t4 - Bpeмя тopмoжeния    "));}
  if (num == 4){strcpy_P(buf, (char*) F("t5 - Наложениe тормоза   "));}
  if (num == 5){strcpy_P(buf, (char*) F("t6 - Снятия нагр воздуха "));}
  return buf;
}


text:
Is there an advantage to set pinmodes via bitmask and register?
I'm working with the capacitive sensor library currently and the author does not use digitalWrite(), but instead sets the output of a pin via functions changing the bitmasks of certain registers:
https://github.com/PaulStoffregen/CapacitiveSensor/blob/master/CapacitiveSensor.h#L39
I looked into the OneWire library description those functions come from, but I still can't see any advantage over simply using the standard way Arduino proposes.

Up to 10X faster! In some applications this is important for timing, for instance, 1-Wire where the timing is faster what can be produced with digitalWrite().

Can you explain why it works faster? Or better said, why is the classical approach so much slower?

See the source of digitalWrite(): there is quite a lot going on here, compared to a single machine instruction with direct port access.

It is possible to achieve both high abstraction and performance without resorting to direct port manipulation. One example is Cosa which is 5-10X faster than Arduino core but at the same time high abstraction and rich functionality; See https://github.com/mikaelpatel/Cosa and for instance https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/GPIO.hh. There are also benchmarks https://github.com/mikaelpatel/Cosa/blob/master/examples/Benchmarks/CosaBenchmarkGPIO/CosaBenchmarkGPIO.ino.

The “classical” approach is direct port access. It has been the standard way of programming AVRs way before Arduino even existed.

I still can't see any advantage over simply using the standard way Arduino proposes.

The standard functions are slower.

There is a very good reason that the Arduino "standard" functions digitalRead, digitalWrite and pinMode are slower than direct port manipulation: They take a variable as the pin number and value to set it to.
This means that the functions in question then have to do a table lookup to translate the pin number to a port number and a bit position. The advantage is you can write code like this:
for (int i = 0; i < 20; i++)
  {
  pinMode (i, OUTPUT);
  digitalWrite (i, LOW);
  }

That's quite handy!
However if you have timing-critical code, and you happen to know the pin number in advance, and it won't change, then you can use a library digitalWriteFast which can optimize that for you. The library cleverly detects if a particular call is given a variable or constant. If a constant then it does the faster port manipulation method (this can now be done at compile-time to find the port and bit number).
There seem to be a few different versions of this library around. The one I linked above fails if you don't pass a constant, others fall back to just doing a digitalWrite (etc).
Inside the library there is code like this:
if (__builtin_constant_p(P) && __builtin_constant_p(V)) { \

In other words it uses a compiler directive to detect if the argument (P = pin, and V = value) are constants or not.

You can also, of course, do direct port manipulation but be warned that if you do then your code becomes pretty non-portable. Try going from an Atmega328 to an Atmega16U4 and the ports and bit positions will change.

Another library: https://code.google.com/archive/p/digitalwritefast/downloads

With direct access to the pin registers, there is no need to call a function (since the digitalWrite function itself calls some functions), which is slower than manipulating the bits directly. You are also able to set the bits of several ports at the same time.
The manipulation of port registers is described in the PortManipulation chapter. It states:

Generally speaking, doing this sort of thing is not a good idea

However it could/should be used for time-sensitive applications. This is an interesting read on this topic.

Is there an advantage to set pinmodes via bitmask and register?

I can name a few:
1) speed - I benchmarked the arduino pin ops vs. direct register ops here;
2) size - the code size is considerably bigger with the arduino library;
3) portability - the bitmark approach is supported by any C-compiler;
4) convention - i'm used to the bitmask approach and wrote all of my libraries around it;
...
as i'm sure others have their reasons to use the bitmasks.

The reason for using direct port operations in capacitive-sensor code is that such code works ok, and slower code won't.  Here's an extract from CapacitiveSensor.cpp in Stoffregen's CapacitiveSensor code:
int CapacitiveSensor::SenseOneCycle(void) {
    noInterrupts();
    DIRECT_WRITE_LOW(sReg, sBit);   // sendPin Register low
    DIRECT_MODE_INPUT(rReg, rBit);  // receivePin to input (pullups are off)
    DIRECT_MODE_OUTPUT(rReg, rBit); // receivePin to OUTPUT
    DIRECT_WRITE_LOW(rReg, rBit);   // pin is now LOW AND OUTPUT
    delayMicroseconds(10);
    DIRECT_MODE_INPUT(rReg, rBit);  // receivePin to input (pullups are off)
    DIRECT_WRITE_HIGH(sReg, sBit);  // sendPin High
    interrupts();

    while ( !DIRECT_READ(rReg, rBit) && (total < CS_Timeout_Millis) ) {  // while receive pin is LOW AND total is positive value
        total++;
    }
//...
}

The general idea is that a source pin and receive pin are driven low, briefly, to discharge associated capacitance.  Immediately upon changing the receive pin to an input we want to change the source pin high, and begin counting the total number of cycles that elapse before the receive pin charges to above about 2.5 V.
Code using digitalWrite(), digitalRead(), and pinMode() calls at four to five microseconds each would take so long to switch from output to input, or to read the source pin and receive pin, that the charging event would be over before the count loop began.


text:
Encoder + Bounce2 Library
I am working towards debouncing my keyes rotary encoder using the Bounce2 library found here ( https://github.com/thomasfredericks/Bounce2 ).
I believe the problem lies in my code as there isn't much in terms of a circuit. The encoder is connected to my arduino as follows

5V : connected to 5v out on arduino
GND : connected to GND
SW : connected to pin A1
DT : connected to pin 3
CLK : connected to pin 2

I am trying to call an ISR from a CLK input. When the ISR is called it should increment or decrement a value based on the direction the encoder was turned. This encoder is tied to an ISR because it will be used for user input and I would like it to remain responsive throughout the sketch.
Previously, I was using millis() to debounce the encoder, but I was still having trouble receiving more than one input from the encoder. I was hoping that this libary would resolve this issue.
The current output of the code I have included never increments/decrements the starting value no matter which direction the encoder is turned. In short, it always outputs 0.
If someone could explain what I am doing wrong that would be wonderful! Then maybe, but just maybe, I can stop beating my head against my desk. :p
Thanks,
Kevin
#include <Bounce2.h>

#define sw A1
#define LED_PIN 9
#define clk 2
#define dt 3

int ledState = LOW;
int onOff = LOW;

volatile int virtualPosition = 0;
int lastCount = 0;

// Initiate bounce objects
Bounce debouncerSW = Bounce();
Bounce debouncerROT = Bounce();

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

  pinMode(sw, INPUT_PULLUP);
  pinMode(clk, INPUT);
  pinMode(dt, INPUT);
  pinMode(LED_PIN, OUTPUT);

  // set up button instace
  debouncerSW.attach(sw);
  debouncerSW.interval(100);

  // set up rotary encoder instance
  debouncerROT.attach(clk);
  debouncerROT.interval(10);

  // setup the LED
  digitalWrite(LED_PIN, ledState);

  // attach ISR
  attachInterrupt(digitalPinToInterrupt(clk), isr, LOW);

  Serial.println("Start"); // just to let me know sketch has finished setup
}

void loop() {

  debouncerSW.update();

  if ( debouncerSW.fell() ) {
    ledState = !ledState;
    onOff = !onOff;
    digitalWrite(LED_PIN, ledState);

    //read-outs
    Serial.print("onOff = ");
    Serial.println(onOff);
  }
  virtualPosition = lastCount;

  //read-outs
  Serial.print ("lastCount = ");
  Serial.println (lastCount);

  delay(1000); // for readability / simulates delay time for rest of main sketch
} // end main loop

void isr ()  {

  // Update the Bounce instance :
  debouncerROT.update();

  if (debouncerROT.fell()) {
    if (digitalRead(dt) == LOW)
    {
      virtualPosition -- ; // Could be -5 or -10
    }
    else {
      virtualPosition ++ ; // Could be +5 or +10
    }

    // Restrict value from 0 to 100
    virtualPosition = min(100, max(0, virtualPosition));
  }
} // end ISR

I also want to note that no form of hardware debouncing is in use. The rotary encoder is connected directly to the arduino with no passive components in place.

See my answer to How to read RPS for fast rotation with status change method in Arduino?.  Also see my comment to other answer there,  “Implemented with a state machine, quadrature coding does not need debouncing. Bounce can cause invalid states or extra states, but they cancel out.”  In other words, debouncing rotary encoder inputs is a wrongheaded approach.

@jwpat7 Thank you! I will take a look!

I’ve always found with encoders that hardware denouncing saves me a lot of trouble.  All you need is a couple of small caps.


text:
Arduino Uno rev 3 - what are the additional 2x3 set of pins for?
I recently bought Arduino Uno rev 3 board and I spent a lot of time trying to figure out the function of each individual pin. I googled all the fancy terms like IOREF, SDA, etc. and one by one I figured out the functional purpose for most of the pins.
However, there are few pins (actually pin groups) which have no labels around and I find it really difficult to figure out what these pins are supposed to do.
Again, I googled around and found this schematic from which I figured out that the 6-pin group  at the bottom is about something called ICSP (or at least this is what is written there). When I googled this term, I found this excellent explanation about the serial communication protocols.
However, at this point I am really confused.

The explanation about the serial protocols doesn't mention at all ICSP. By googling even further I only get more and more confused. Yes, I found the ICSP wiki page but I am not 100% sure that the bottom 6 pins are related to ICSP.
From the same schematic which I found I see there are 4 additional soldered pads with label JP2 right above them. Currently I have no clue about the function of these pads. Question 1 - what are these soldered pads for?
Right next to the JP2 stuff is a group of 6 pins (3 rows, 2 columns). The schematic is not clear about these pins. Question 2 - what is the purpose of these pins? Question 3 - where can I find the actual schematic (layout) about each individual pin?
I am not 100% sure that the bottom group of pins (2 rows, 3 columns) is related to ICSP. Maybe that's the case, maybe it's not. Question 4 - what is the purpose of these pins? Question 5 - where can I find the actual schematic (layout) about each individual pin?

Thank you in advance for your help!

The ICSP pins have two functions:

For programming the ATMega328P directly using a hardware programmer (In Circuit Serial Programmimg)
SPI connections for shields in a standard place.

They are used for SPI because different boards have the SPI pins on the main headers in different locations. All boards should have this 6-pin block in the same place though meaning that shields can then work with more boards.
On the Uno they share the same physical connections as digital pins 11-13 plus reset and power.
JP2 and the other 6-pin block are connected to the USB interface chip (ATMega16U2). The 6 pin block provide ICSP for programming that chip. The other 4 (unpopulated) pins connect to GPIO pins on that same chip. They can be used for anything you like if you replace the firmware on the USB chip.
For now ignore those two pin groups. They aren't really anything to do with the Arduino side of things, only the USB interface.
You can find all this on the official Uno schematic which is on the official Uno product page: https://www.arduino.cc/en/Main/ArduinoBoardUno


text:
Extracting bits from hex encoded binary
I've been using an Adafruit Huzzah ESP8266 Breakout to read data from an OpenTherm Gateway connected to my central heating unit, and publish that to MQTT. I'm programming the ESP8266 using the Arduino IDE.
The gateway publishes messages to the ESP8266 via serial. These messages look like this: T901812F3 or B501812F3
The first letter indicates whether the message comes from the thermostat or the boiler, while the remaining characters represent four bytes, hexadecimally encoded.
These four bytes are structured as follows:

I'm trying to extract the MSG-TYPE, DATA-ID, and DATA-VALUE from the four bytes, but I'm getting weird (to me) results. I'm new to Arduino and C in general.
I'm familiar with PHP, and extracting the data using that is easy:
$decimal = hexdec(substr("B501812F3", 1));      // 1343754995
$messageType = (($decimal & 0x70000000) >> 28); // 5
$dataId = (($decimal & 0x00FF0000) >> 16);      // 24
$dataValue = ($decimal & 0x0000FFFF);           // 4851

However when I try something similar in the Arduino IDE, and upload it an Arduino, I get a different result:
void setup() {
    Serial.begin(9600);
    delay(500);

    parseLine("B501812F3");
}

parseLine(char* message) {
    // Extract data
    char messageType;
    unsigned long data;
    int numberExtracted = sscanf(message, "%c%08x", &messageType, &data);

    // Decompose a single message
    int flag = (int) ((data & 0x70000000) >> 28);
    unsigned char openThermId = (unsigned char)((data & 0x00FF0000) >> 16);
    unsigned short openThermPayload = (unsigned short)(data & 0x0000FFFF);

    Serial.println(data);             // 4851
    Serial.println(flag);             // 0
    Serial.println(openThermId);      // 0
    Serial.println(openThermPayload); // 4851
}

I (perhaps incorrectly) assume that the effect will be the same when I upload the code to an ESP8266.
What am I missing here? I suspect it has something to do with the different max integer value on the Arduino, but I'm not really sure how to proceed.

You're best off using strtoul():
messageType = message[0];
uint32_t data = strtoul(message + 1, NULL, 16);

The trick here is that message is just an array, so you can get the first letter with message[0]. Also, since C arrays are themselves just pointers to blocks of memory, message + 1 actually points to the location in memory of message[1], so you start processing the numbers from the second character in the string, thus omitting the first letter.
strtoul() takes a third parameter which is the base to decode from - 16 in this case for hexadecimal.
From there you can then use your bit shifting and masking to slice up your 32-bit value into your required sub values.

A C/C++ struct with bit-fields can sometimes be an effective solution to this type of problem. The bit-field order depends on the endianness of the CPU. AVR uses little-endian order and thus the fields are from right to left.
union msg_t {
  struct {
    uint16_t value;
    uint8_t id;
    uint8_t spare:4;
    uint8_t type:3;
    uint8_t parity:1;
  };
  uint32_t as_uint32;
};

A simple test sketch to verify:
void setup() {
  Serial.begin(9600);
  while (!Serial);
  msg_t msg;
  msg.uint32 = 0x501812f3;
  Serial.println(msg.parity);   // 0
  Serial.println(msg.type);     // 5
  Serial.println(msg.spare);    // 0
  Serial.println(msg.id);       // 24
  Serial.println(msg.value);    // 4851
}

void loop() {
}

I think you're missing the bit that mentions that the value is in a string prefixed with a character (B or T). msg.uint32 = 0xb501812f3; will overflow since you have 36 bits there, and 0xt501812f3 isn't valid hex.

@Majenko Missed that but I am addressing methods of extracting bit-fields :). I do not want to event approach the whole idea of going for text notations.


text:
How to burn bootloader and upload sketches on custom arduino?
Ive turned a project I breadboarded with arduino and other modules into one pcb on EAGLE. The pcb includes the ATMEGA328p smt version that doesn't have the bootloader installed. My question is then what module or components can I use to burn the bootloader onto the atmega and upload programs to it together?

Sidenote; a bootloader isn't always required. I never used it in my projects. I program my sketches directly via ISP. The bootloader is only there so you can program the chip over Serial (over USB).

when laying out a pcb you may wish to include a 6-pin ISP connector for programming the part, either with ArduinoISP or a programmer like the USBASP.

You can use a second Arduino as a standalone programmer for it, either to upload your sketch directly, or to upload a bootloader (after which you'd upload your sketch in the normal way). The example program, ArduinoISP, uploaded into the second Arduino is what can do this. Here is a link to a how-to article for doing just that.
If you haven't already populated your PCB, good - sometimes your external (to the MCU) circuitry can interfere - but it's worth a try, even if you have.


text:
Using serial communication in .c-files
I am currently trying to connect my Arduino Uno to my computer and let them communicate via UART. I started using a project from Github (here), which I'm trying to modify to get the next step via UART. Because of that, I'm not able to switch programming languages and also need to override the bootloader.
However, I can't get the serial connection to work.
#include "Joystick.h"
#include <avr/io.h>
#include <util/delay.h>
#include <Arduino.h>

These are the #include statements at the top, but <Arduino.h> can't be found...
If I remove these statements, Serial can't be found (from the main-Method: Serial.begin(9600);)
It's my first time to program with C, did I overlook a stupid mistake? Thanks for any help...

Are you using the Arduino IDE to compile this?

@chrisl No, I'm using the makefile that is contained in the GitHub project. I modify the $PATH variable every time to contain arduinoInstallDir/hardware/tools/avr/bin, which includes the avr-gcc needed for it to compile.

You can very easily combine C and C++ code. Just compile your parts of the code as C++, and include the existing C functions you need as extern "C". If you need to call your C++ function from C code, declare it extern "C" as well. You can then use all of the C++ features from the Arduino core if you want.

@tttapa I've tried my best to work out how that works, but I can't get it. I found examples for how to include one method, but not for an entire library. Is also thought about converting that whole project to C++, but that also won't work as I don't fully understand it. If you could give me an example on how to include a full library like <Arduino.h> in a C file and make it still usable, I would be really thankful.

I started to look into it, but it seems to me that the code is intended to run on the ATmega16U2 of the UNO, not the ATmeg328P. In that case, I don't think there's an Arduino Core available for that chip, so you would have to program the USB CDC stack yourself (should be possible using LUFA, but I don't have the time to look into it). And IMHO, it's absolutely not worth any more time. I'd use a microcontroller that supports USB natively, and has decent software support, like a Teensy 3.x.

@tttapa The project I linked from discord already does what I want, but now I want to extend that program to read the next button press from a serial connection with a PC, but to read from serial, I have to use the library from Arduino which I can't access. So the USB Connection thing is no problem.

I don't think you understood my comment. The UNO has 2 microcontrollers, one can run Arduino code (ATmega328P), the other can not (ATmega16U2). You cannot use Serial.begin on this second microcontroller. The reason that you cannot write Arduino code for it is because nobody has written an Arduino Core library for it. You can do that yourself, you can probably recycle a lot of code from the ATmega32U4 core, but that would be a waste of time, IMHO, and it will probably conflict with the existing LUFA code you have.

@tttapa Would it maybe be possible to let the first controller (ATmega 328P) receive the data from serial and pass them on to the ATmega16U2?

The ATmega16U2 has a UART you have access to, so you could use that, but I thought you wanted Serial over USB?

@tttapa The code from GitHub already uses the USB-Port, so I thought I could put the other communication onto the UART connection. So I'm currently trying to let the 16U2 read from UART, and pass that data on via USB.

I would consider using HoodLoader2 instead of that LUFA project. If you can't do that, you can compile parts of the Arduino Core together with the LUFA project.
The main steps:

Add the necessary Arduino source files to the SRC variable in the Makefile.
Add the Arduino core folder to the include path by appending to the CC_FLAGS and CXX_FLAGS variables.
Move the main function to a new main.cpp file and add it to the Makefile SRC as well.
Include the Joystick.h file in your main file in an extern "C" block.
Include the HardwareSerial.h file in your main file as well.

My files after these changes:
Makefile
# Set the MCU accordingly to your device (e.g. at90usb1286 for a Teensy 2.0++, or atmega16u2 for an Arduino UNO R3)
MCU          = atmega16u2
ARCH         = AVR8
F_CPU        = 16000000
F_USB        = $(F_CPU)
OPTIMIZATION = s
TARGET       = Joystick
SRC          = $(TARGET).c Descriptors.c main.cpp $(LUFA_SRC_USB)
LUFA_PATH    = ./lufa/LUFA
CC_FLAGS     = -DUSE_LUFA_CONFIG_HEADER -IConfig/
LD_FLAGS     =

ARDUINO_PATH = ${HOME}/.arduino15/packages/arduino/hardware/avr/1.8.1/cores/arduino
SRC         += $(ARDUINO_PATH)/HardwareSerial.cpp
SRC         += $(ARDUINO_PATH)/HardwareSerial1.cpp
SRC         += $(ARDUINO_PATH)/Print.cpp
CXX_FLAGS   += -I$(ARDUINO_PATH) -I./HoodLoader2/avr/variants/HoodLoader2
CC_FLAGS    += -I$(ARDUINO_PATH) -I./HoodLoader2/avr/variants/HoodLoader2

...

main.cpp
extern "C" {
#include "Joystick.h"
}

#include <HardwareSerial.h>

// Main entry point.
int main(void) {
    // We'll start by performing hardware and peripheral setup.
    SetupHardware();
    // We'll then enable global interrupts for our use.
    GlobalInterruptEnable();
    // Initialize the UART
    Serial1.begin(115200);
    Serial1.println(F("Hello, world"));
    // Once that's done, we'll enter an infinite loop.
    for (;;)
    {
        // We need to run our task to process and deliver data for our IN and OUT endpoints.
        HID_Task();
        // We also need to run the main USB management task.
        USB_USBTask();
    }
}

Joystick.c
Deleted the main function.
To get it to compile after these changes:
# (inside of the snowball-thrower folder)
git submodule add https://github.com/NicoHood/HoodLoader2.git HoodLoader2
make

This compiles without problems for me, but I have no idea if it actually works.
Edit:
You'll notice that the program uses more RAM than the ATmeg16U2 has available. You could solve this by moving the step array to PROGMEM, or by shrinking the Serial buffers.
avr-size --mcu=atmega16u2 --format=avr Joystick.elf
AVR Memory Usage
----------------
Device: atmega16u2

Program:    5076 bytes (31.0% Full)
(.text + .data + .bootloader)

Data:        527 bytes (102.9% Full)
(.data + .bss + .noinit)

 [INFO]    : Finished building project "Joystick".

I've tried that, but I can't confirm that the program really started. I've connected an UART-to-USB-Bridge and tested it before, but PuTTY doesn't output the starting test entry. Instead, the last thing that was programmed with Arduino gets executed and outputted to PuTTY... I've got around the RAM-Issue by just deleting the last part of the step-array, because I'm trying to completely avoid that by streaming the entries via UART. However, neither the starting output gets displayed nor the switch notices a new controller connected.

I need to correct myself: It get's noticed from the switch if I disconnect TX&RX while flashing the new .hex file. But still no output from PuTTY (and yes, I reconnect TX & RX after finished flashing the image). The connection/interaction with the switch is the same as before, so that is perfectly fine, but the Serial-Connection still does not work.

@MonsterDruide1 Upload an empty sketch to the ATmega328P first (using the original '16U2 Arduino firmware), or connect its reset pin to ground. And also swap your RX/TX pins. The RX of the UART-to-USB adapter should be connected to the RX pin of the Arduino (this is the TX pin of the '16U2), and TX to TX. Internally, the RX/TX pins are connected like this (ignore the ESP8266, imagine that it's the UART-to-USB adapter).

YES!!!! Thank you VERY much for all of that help. Everything now works as expected!


text:
LED goes off in nodemcu If I turn on other LED
I developed an android app to control a robot using nodemcu. I have added some buttons to on/off or blink some LEDs. It works fine but, if I on the one LED or drive the robot, the other LEDs goes off. What I want is the LEDs should be off only if I press the off button for that respective LED.
My code for nodemcu -
#define RIGHT_MOTOR_1  15       // L298N in1 motors Right           GPIO15(D8)
#define RIGHT_MOTOR_2  13       // L298N in2 motors Right           GPIO13(D7)
#define LEFT_MOTOR_1   2        // L298N in3 motors Left            GPIO2(D4)
#define LEFT_MOTOR_2   0        // L298N in4 motors Left            GPIO0(D3)

#define FRONT_LED    16        //Front LED        GPIO14(D0)
#define REAR_LED_1   5         //Rear LED        GPIO12(D1)
#define REAR_LED_2   4         //Rear LED        GPIO12(D2)

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>

String command;

const char* ssid = "NodeMCU";
const char* password = "10101010";

ESP8266WebServer server(80);

void setup() {

  pinMode(RIGHT_MOTOR_1, OUTPUT);
  pinMode(RIGHT_MOTOR_2, OUTPUT);
  pinMode(LEFT_MOTOR_1, OUTPUT);
  pinMode(LEFT_MOTOR_2, OUTPUT);
  pinMode(FRONT_LED, OUTPUT);
  pinMode(REAR_LED_1, OUTPUT);
  pinMode(REAR_LED_2, OUTPUT);

  Serial.begin(74880);

  // Connecting WiFi
  WiFi.mode(WIFI_AP);
  WiFi.softAP(ssid, password);

  IPAddress myIP = WiFi.softAPIP();
  Serial.print("AP IP address: ");
  Serial.println(myIP);

  // Starting WEB-server
  server.on ( "/", HTTP_handleRoot );
  server.onNotFound ( HTTP_handleRoot );
  server.begin();
}

//LED Logic
void frontLEDon(){
  digitalWrite(FRONT_LED, HIGH);
}

void frontLEDoff(){
  digitalWrite(FRONT_LED, LOW);
}

void frontLEDblink(){
    digitalWrite(FRONT_LED, HIGH);
    delay(500);
    digitalWrite(FRONT_LED, LOW);
    delay(500);
}

void rearLEDon(){
  digitalWrite(REAR_LED_1, HIGH);
  digitalWrite(REAR_LED_2, HIGH);
}

void rearLEDoff(){
  digitalWrite(REAR_LED_1, LOW);
  digitalWrite(REAR_LED_2, LOW);
}

void rearLEDblink(){
    digitalWrite(REAR_LED_1, HIGH);
    delay(50);
    digitalWrite(REAR_LED_1, LOW);
    delay(50);
    digitalWrite(REAR_LED_1, HIGH);
    delay(50);
    digitalWrite(REAR_LED_1, LOW);
    delay(50);
    digitalWrite(REAR_LED_2, HIGH);
    delay(50);
    digitalWrite(REAR_LED_2, LOW);
    delay(50);
    digitalWrite(REAR_LED_2, HIGH);
    delay(50);
    digitalWrite(REAR_LED_2, LOW);
    delay(50);
}

void forward(){
  digitalWrite(RIGHT_MOTOR_1, LOW);
  digitalWrite(RIGHT_MOTOR_2, HIGH);
  digitalWrite(LEFT_MOTOR_1, LOW);
  digitalWrite(LEFT_MOTOR_2, HIGH);
}

void backward(){
  digitalWrite(RIGHT_MOTOR_1, HIGH);
  digitalWrite(RIGHT_MOTOR_2, LOW);
  digitalWrite(LEFT_MOTOR_1, HIGH);
  digitalWrite(LEFT_MOTOR_2, LOW);
}

void right(){
  digitalWrite(RIGHT_MOTOR_1, HIGH);
  digitalWrite(RIGHT_MOTOR_2, LOW);
  digitalWrite(LEFT_MOTOR_1, LOW);
  digitalWrite(LEFT_MOTOR_2, HIGH);
}

void left(){
  digitalWrite(RIGHT_MOTOR_1, LOW);
  digitalWrite(RIGHT_MOTOR_2, HIGH);
  digitalWrite(LEFT_MOTOR_1, HIGH);
  digitalWrite(LEFT_MOTOR_2, LOW);
}

void robotStop(){
  digitalWrite(RIGHT_MOTOR_1, LOW);
  digitalWrite(RIGHT_MOTOR_2, LOW);
  digitalWrite(LEFT_MOTOR_1, LOW);
  digitalWrite(LEFT_MOTOR_2, LOW);
}

void loop(){
      server.handleClient();
      command = server.arg("State");

      if(command == "Forward"){
        forward();
        frontLEDon();
      }
      if(command == "Backward"){
        backward();
        rearLEDon();
      }
      if(command == "Left"){
        left();
      }
      if(command == "Right"){
        right();
      }
      if(command == "Stop"){
        robotStop();
      }
      if(command == "FrontLEDon"){
        frontLEDon();
      }
      if(command == "FrontLEDblink"){
        frontLEDblink();
      }
      if(command == "FrontLEDoff"){
        frontLEDoff();
      }
      if(command == "RearLEDon"){
        rearLEDon();
      }
      if(command == "RearLEDblink"){
        rearLEDblink();
      }
      if(command == "RearLEDoff"){
        rearLEDoff();
      }
}

void HTTP_handleRoot(void) {
  if( server.hasArg("State") ){
       Serial.println(server.arg("State"));
  }
  server.send ( 200, "text/html", "" );
  delay(1);
}

the android app may be the cause


text:
6v between vin and pin even though pin is off
I have a arduino uno and i am trying to make a lightstrip work.
i have made a program for this but when i turn off the pins to make the light
strip turn off it still glows.
red the reason is that there is still 6v between vin and the port even though there should be 0v.
here is my code
void setup() {
pinMode(13, OUTPUT);
digitalWrite(13, LOW);
}

void loop() {
}

any way to fix this

Please show us your circuit, so that we can see, how the lightstrip is connected. The problem must lie there

A low output is (almost) the same as ground. Between VIN and GND you will get VIN. Between VIN and an IO pin set to LOW you will get VIN - since LOW and GND are the same.

That would be the correct reading.
If (LOW) 0 is near GND.
All your measurements should be from(against) GND
Never connect any pins into voltage before regulator(V-in) or voltage over 5v (I usualy target 4.6v as MAX voltage to give myself a margin of error) and even that should only be done in the event of input or high (1) mode.
You are lucky if your multi-meter had big enough resistance and did not damage your Arduino yet.
Arduinos pins have no real protection and very little resistance when in output mode.
Even though pro's keep saying that it is pointless I find that when connecting items sensitive to even tiny current using NPN transistor i tend to use pull-down 10K-ish resistor against GND


text:
Teensy to Teensy serial communication via USB connector
I have 2 Arduino Teensy 3.2 boards that I'm trying to implement serial communication between the 2 boards.  I have successfully done this by connecting RX1 of the 1st Teensy with TX1 of 2nd Teensy and TX1 of 1st to RX1 2nd.
However I was wondering if I could send serial messages between the Teensys i.e. do the same thing, by connect the 2 Teensys via the USB port?  Or is this USB port reserved to connecting the Teensy to a computer?

There is alpha software at https://github.com/felis/UHS30 to setup USB host mode, so it could be possible, but you might be better off doing what you are doing.

But why? Uart is good and easy, RS485 is more robust. USB is complicated and not very beneficial.

I thought you could reuse the D+ and D- pins to do e.g. software serial over them. But it seems like you can't use those pins as GPIO.

Note: The Teensy you pictured is an ARM based (NXP MK20DX256) Arduino which is very different from well established legacy Arduinos. There have been (and, maybe, still are) "bugs" in some ARM Arduino code.  So Teensy pins used outside their normal (expected) purpose my or may not work like similar pins on legacy Arduino platforms.
In order for 2 USBs to talk to each other, one needs to be a USB Host and the other a USB Device.  There can be multiple USB Devices so the USB protocol is made more complex to handle this feature.  There can be many types of USB Devices each with their own underlying protocol so the USB protocol is made more complex to handle this additional feature.  A serial port USB Device uses the CDC or Communications Device Class protocol.
So, in order to have two Teensy board to talk to one another using the USB CDC protocol, one of the Teensy boards needs to be turned from a USB Device to a USB Host.  Which is not trivial.  Most developers will turn to the OEM of the processor.  As most processor OEMs offer free software for such purposes to promote the sales of their hardware.

How about connecting the USB of 1 teensy to the UART of a second?  I know there are usb to uart adapters but from what I understand they are for PCs?

There is soooo much USB overhead (because of all the features USB supports) that you would need some fairly complex software behind the "other teensy's" UART.  Not to mention you need some hardware to convert from USB levels to TTL levels.  See the V-USB project for more details.

Teensy 3.5, 3.6, 4.0 and 4.1 have a second USB interface which is configured as USB Host. You can use this interface in CDC mode (see @st2000 answer) and connect it to the normal USB device plug of any other Teensy if you need to. But please note that a T3.2 can transmit up to about 3 MBaud over its serial UARTS. So, I don't see any reason to use USB for board to board communication.


text:
What is VREF pin?
Was searching for some help on connecting Flir camera w/ Lepton board to arduino and found this thread

for power you can reroute the 3-5V to the VREF pin, then you have a nice clean solution.
You have to use a Ardunio with at least 16k or ram so you can buffer the image.
Was that a typo and he meant AREF?  If so would the VIN from the camera be connected to the VIN on arduino otherwise?
Thread:
https://forum.arduino.cc/index.php?topic=266361.0

VREF normally means Voltage REFerence.  Such pins are usually associated with ADCs (Analog to Digital Converters).  For example a 3.3 volt microprocessor may have a VREF pin fed by 2 volts.  The 10 bit ADC inside the microprocessor sees this as the upper limit.  That is, a 2 volt input to the ADC will produce the maximum value or 2^10 or 1024.

Yes, he meant AREF.  What he is showing there is the board plugged direct into the Arduino's header, but the VIN of the Lepton board connects to AREF not a voltage pin. By connecting your supply voltage (5V) direct to that AREF pin you are then able to provide power to the Lepton board, and it has no noticeable effect on the Arduino since connecting 5V to AREF is a perfectly valid thing to do (though pretty pointless).
AREF and VREF are both pretty much interchangeable. Analog REFerence, and Voltage REFerence. It could be said that one is the Analog voltage REFerence, and the other is the Voltage REFerence for analog. Some chips call it AREF and some VREF. Some even provide VREF+ and VREF- or AREF+ and AREF- depending on the complexity of the ADC in the chip.


text:
looking for a very accurate and sensitive accelerometer
For a research type project, we are looking for a very accurate and sensitive accelerometer (preferably 6-axis). The average range of the acceleration that we need to record is about 0.0003g (g=gravitational acceleration=9.81m/s2). The minimum sampling rate of measurements should be about 250Hz. We have no electronic engineering background and so we are looking for a readily available module that can be simply installed and connected to a data processor (eg Raspberry pi or a similar one) for recording data. we need to use these sensors for one of our mechanical engineering projects.
Your comments and help are appreciated.
Thanks.
M.

You may find Robotics Stackexchange more useful for this question.  Copy your question there, then delete it here.

I'm voting to close this question as off-topic because questions seeking recommendations for specific products or places to purchase them are off-topic as they are rarely useful to others and quickly obsolete. Instead, describe your situation and the specific problem you're trying to solve.


text:
Best practice to declare a 'static' text and save memory
I'm working on a project where I need to create a JSON to send back state of an object. I created the code to achieve it and all works fine, but I used this to declare the JSON fields:
static const String JSON_FIELD_A;

then in the .cpp file
const String MyClass::JSON_FIELD_A = "field_a";

In this way I can use that in several point inside my class (eg. to create and parse JSON) without needs to write the field name each time which may cause inconsistency after a refactoring.
I'm not sure about this way anyway... is there a more efficient way to achieve that? Using #define may be a solution?

This looks reasonable

You should look at the F() macro, and the __FlashStringHelper stub class. As well as the _P variants of the standard string library functions.

The "traditional" way is to use PROGMEM and use const char * strings.
I don't use the "traditional" way. Instead I use some "helper" classes and macros that WString.h provides.
This does mean, though, due to limitations in C++, that you have to create your string constants in two stages.
First is to define your variables:
const __FlashStringHelper *stringOne;
const __FlashStringHelper *stringTwo;

Then you need to assign the actual strings to those variables within a function. This could be in setup(), but I prefer to define an initializeStrings() function that setup() calls:
void initializeStrings() {
    stringOne = F("This is the first string")
    stringTwo = F("This is the second string");
}

void setup() {
    initializeStrings();
}

You can then pass these objects (they're not really objects, it's all just some magic casting done by the compiler) as parameters to other functions using const __FlashStringHelper * as the type.  They can also be passed directly to any of the .print() and .println() functions provided by the Print class (which all Stream objects ultimately inherit).
If you want to use the standard C string library functions _P variants for manipulating the strings (concatenating them to other strings, for instance), you can simply cast them to PGM_P:
char temp[50];
strcpy_P(temp, (PGM_P)stringOne);
strcat_P(temp, (PGM_P)stringTwo);

Another alternative to all that is to use precompiler macros.
#define STRING_ONE F("This is the first string");
#define STRING_TWO F("This is the second string");

Again, you can cast those to PGM_P to use the _P variants of the standard C string library functions, and pass them directly to print functions, since they are replaced verbatim as F("This is the first string"), and F() does a reinterpret-cast to const __FlashStringHelper *.

it is all `const char* and we must track which one is in flash and which in RAM and use the right functions. __FlashStringHelper is a trick to match the flash variants. but a trick not recognized by _P functions. so we need to cast it back to const char*. but I doubt a beginner can understand this

@Juraj Ah... the complexities of Harvard architecture. It's such a joy. One of the many reasons I never use AVR chips :)

const String does make nothing constant. You create an object, which can't be reassigned, but all methods work. Because it handles the characters inside and the const declaration doesn't change it. You can delete the content, change the content, append the content of the String object.
You should use const char* or const char[]. It is an c-string and the compiler checks if it is handled as a constant at gives at least a warning if not.
To save RAM the const char[] should be declared as PROGMEM. At runtime then this string isn't copied into RAM. You can use it with functions with _P postfix or copy it temporally to RAM.
Example from my project:
global char array with PROGMEM
const char data[] PROGMEM = "{\"suspension_time_seconds\":10800}";
use in a function
client.print(F("Content-Length: "));
client.println(strlen_P(data));
char buff[64];
strcpy_P(buff, data);
client.print(buff);

You don't need to copy a PROGMEM string into RAM just to "print" it. Just cast it to const __FlashStringHelper *: client.print((const __FlashStringHelper *)data);

I know. Wrong example with print. It should be some function that has not a variant for progmem.