text:
Two serials can't work on the same speed
I have a device which sits on pins 10/11 of Arduino UNO. I am trying to send commands from my PC using Arduino to relay my commands to the device via Serial.
The problem is that if I use speed 9600 both for device and USB communication, then my commands gets damaged. Some letters are replaced by strange symbols, etc. The device uses 9600 baud rate.
If I change speed of the PC communication to 4800 (or any speed other than 9600), everything is fine. But I have to use different speeds for the communication.
I am not comfortable with the workaround, because I don't understand what's going on. Could somebody explain why the same serial port speeds causes problems?
Here is my code:
#include <SoftwareSerial.h>

#define rxPin 11
#define txPin 10

SoftwareSerial mySerial =  SoftwareSerial(rxPin, txPin);

 void setup()
 {
   digitalWrite(4,HIGH); // 1 - disable
   mySerial.begin(9600);
   Serial.begin(19200);
   while (!Serial) {;}  // wait for serial port to connect. Needed for native USB port only
   Serial.println("Begin");
 }

 void loop()
 {
  if (mySerial.available())
  {
    char c = mySerial.read();
    Serial.write(c);
  }
  if (Serial.available())
  {
    char c = Serial.read();
    mySerial.write(c);
  }
 }

SoftwareSerial is not my favorite and I didn't have a good taste with it. But, anyway, maybe you should give some more detail about the device you connect on pin 10 and 11.

@Sener The device is RMCS 2201 servo: Link to specs
It has fixed 9600 baud rate. I connected it directly to COM with a TTL converter and it works fine. So I guess, there is a problem somewhere in my code. Will try your buffering code. Thank you!
Maybe you can suggest something to replace SoftwareSerial?

Thank you for the device details. If it is working with USB to TTL module, then we should think about the code. Please give a try the code I mentioned. And even further, try to use hardware serial instead.

But, Arduino Uno has only one hardware serial with pins 0:RX, 1:TX.
Then, you can't use PC communication via USB. You may like to consider also Arduino Mega which has 4 Serial ports.

Perhaps the interrupt from the incoming byte changes something in the outgoing byte of the SoftwareSerial. It is possible. Perhaps the servo motor has some kind of software serial as well and requires perfect timing of the serial signal. To avoid collisions, you can first read a full line as the answer by @Sener shows. But you better use a hardware serial port of the arduino mega or arduino leonardo.

The baudrate of the servo motor could be a few percent higher or lower. The SoftwareSerial uses fixed baudrates, you can not change that. The hardware serial calculates the value for the uart register. I think the hardware serial can set a slightly different baud rate.

@Jot, buffered read didn't help. I ordered a Mega to solve this. Thank you!

@konstantin can you try to "sniff" the communication? I mean, when the communication is ongoing, connect the RX wire of the USB TTL to the TX pin of the Arduino, then to the RX, and check where the communication is corrupted

Software serial works only half duplex (you cannot send and receive in the same time).  AltSoftSerial is a very  good option.  https://www.arduinolibraries.info/libraries/alt-soft-serial

If you're using an UNO then why do you have this line:   while (!Serial) {;}   which even the comment in your own code says isn't necessary for your board?

I spent some time playing with your code and it seems your code actually loops the serial therefore if they are both set at 9600 as example and you print what the other one is sending like in your code you end up in a loop if you want to read what your serial is sending it is better put that values in a variable and send it
if you load your code you will get the following message in the arduino IDE once you try to connect to the serial monitor:
Error opening serial port 'COM8'. (Port busy),
your port is busy because the one serial port is reading the other all the time
one more thing I would use the following if you want to repeat a serial port:

  if (mySerial.available())
  {
    //char c = mySerial.read();
    Serial.write(mySerial.read());
  }

Hope this hels you

If you are confident with the device you connected to your Arduino Uno in terms of it has a reliable serial communication firmware running on it, You might need some buffering before relaying your commands;
#define RECORD_SIZE 100
void loop()
{
    RelayDataIfAvaliable();
}
void RelayDataIfAvaliable() {
    static char buffer[RECORD_SIZE];
    if (Serial.available())
    {
        if (readline(Serial.read(), buffer, RECORD_SIZE) > 0) {
            mySerial.write(buffer);
        }
    }
}
//Reads entire incoming data into buffer once
int readline(int readch, char *buffer, int len)
{
    static int pos = 0;//This was zero initially. But, it was missing first character!
    int rpos;
    //Serial.print(readch);
    if (readch > 0) {
        switch (readch) {
        case '\n': // Ignore new-lines
            break;
        case '\r': // Return on CR
            rpos = pos;
            pos = 0;  // Reset position index ready for next time
            return rpos;
        default:
            if (pos < len - 1) {
                buffer[pos++] = readch;
                buffer[pos] = 0;
            }
        }
    }
    // No end of line has been found, so return -1.
    return -1;
}

I have played with this approach. Buffered read doesn't help. The same problem: everything is fine until I set the same speed for both serials. I have ordered a Mega board. This should solve the problem for sure. :)
Thank you very much!

But, there is another way before going on that road. When I checked that datasheet for the motor, it can also communicate over I2C or SPI. Wouldn't you consider to do that as well?
For example, that sample is looking quite promising:
RMC220x demo

Ah, one more thing, did you give that down vote for my answer (work in progress)? it was the only place I could place a formatted coding so i did not necessarily a final answer. I believe that at least it deserves some respect.

not it's not my down vote. I've marked your answer as useful. Since I don't have enough reputation it's recorded, but not displayed. Your answers help me a lot!

Thank you for your  feedback and marking my answer. Good luck with your project.


text:
Cannot run WiFi sketch on ESP-01
I can upload simple sketch on my ESP-01 like:
void setup() {
  Serial.begin(115200);
  Serial.println("Hello there");
}
void loop() {
  Serial.println("Hello from loop");
  delay(1000);
}

I also ran successfully the sample ESPWebServer -> HelloServer
But if just modify my sketch to include #include <ESP8266WiFi.h>
#include <ESP8266WiFi.h>

void setup() {
  Serial.begin(115200);
  Serial.println("Hello there");
}
void loop() {
  Serial.println("Hello from loop");
  delay(1000);
}

I got this result in the serial monitor:
  ets Jan  8 2013,rst cause:4, boot mode:(3,7)

wdt reset
load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
vbb28d4a3
~ld

My ESP-01 is connected to my computer through FT232RL FTDI with the following cabling:

FTDI GND - GND
ESP TX - FTDI RX
ESP RX - FTDI TX
ESP VCC - VCC 3.3V
ESP GND - GND
ESP CH_PD - VCC
ESP GPIO2 - VCC
ESP GPI00 - GND to upload sketch, VCC to run sketch

Here is a picture of my cabling (the USB of both the TTL and power supply MB102 are connected to my laptop):

Also, regularly my sketch fails to load correctly:
-Sometimes it does not load at all and I get this after compilation before uploading starts:
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

- Sometimes it fails at the end of the upload:
Uploading 256064 bytes from C:\Users\20000263\AppData\Local\Temp\arduino_build_32221/ESP01-Basic.ino.bin to flash at 0x00000000
................................................................................ [ 31% ]
................................................................................ [ 63% ]
................................................................................ [ 95% ]
..........warning: espcomm_send_command: didn't receive command response
warning: espcomm_send_command(FLASH_DOWNLOAD_DATA) failed
warning: espcomm_send_command: wrong direction/command: 0x01 0x03, expected 0x01 0x04
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

Any idea about what is wrong ?

FTDI adapters often don't provide enough current to run the power-hungry wifi features of the ESP8266. So as soon as you fire up wifi, you brownout the chip and cause it to reset.
Use a battery, a dedicated ESP8266 flasher, a 3.3v LDO, or something besides the on-board 3.3v connection the USB-Serial adapter provides.

I already have a separated power supply for the ESP8266 of this type: MB102 breadboard power supply module

source: Stack Exchange

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

sort: votes


text:
for() loop doesn't seem to break?
So I'm quite new to the whole Arduino coding but constructed a sketch that does work, but I think it doesn't work properly. So I'd love to get some advice on how to improve it.
This script is currently running on a Wemos ESP8266 chip attached to a 1 meter WS2812 144 LED strip.
My questions:

The loop is set to break when fadein is higher then 254.
When I try to break it at fadein == 255 the loop doesn't work anymore as it the fadein value directly jumps to 255. Why?

When I set the delay to zero the led flicker due to too fast updating. however, this flickering continues even after the for loop is broken, which makes me conclude that the for loop is still running even when the break is applied.
Of course this is no longer an issue when the delay is set higher (as it is supposed to be) but it still seems a waste of processing power to keep the for loop active while it's not doing anything new anymore
how can i completely stop the loop from being executed?

How can this be done differently / more effective?

The code
#define FASTLED_ALLOW_INTERRUPTS 0                                    //fix jitter in led strip
#include <FastLED.h>                                                  //add fastled lib
#define NUM_LEDS 144                                                  //set number of leds
#define DATA_PIN D4                                                   //set data pin leds

CRGB ledStrip[NUM_LEDS];                                              //init led strip
int fadeIn = 8;                                                       //init fade in counter
int led = 0;                                                          //init led counter

void setup() {
  Serial.begin(115200);                                               //setup comm channel
  FastLED.addLeds<WS2811,DATA_PIN, RGB>(ledStrip, NUM_LEDS);          //setup ledstrip config
}

void loop()
{
for (int led = 0; led < NUM_LEDS; led++) {                            //move led up the strip till max count is reached
    ledStrip[led] = CHSV( 0+led*1.77, 255, 225);                      //set animated led hue value to make a rainbow
    FastLED.show();                                                   //show led color
    ledStrip[led] = CHSV( 0+led*1.77, 255, fadeIn);                   //set non animated led hue to same hue value while increasing the fade value
    delay(3);
    if (fadeIn > 254) {                                               //if the fadeIn value exceed 254
      break;                                                          //stop led animation
    }
}

    if (led = 144 && fadeIn < 254) {                                   //when the 144th led is reached and the fadein value is less then 255
      fadeIn+=16;                                                      //increase fadeIn value with 16
    }
    if (led = 144 && fadeIn < 255) {                                   //when the 144th led is reached and fadeIn is smaller then 255 show debug messages
      Serial.println(led);                                             //print led counter value
      Serial.println(fadeIn);                                          //print fadein value
    }
    if (fadeIn > 255) {                                                 //if the fadeIn value exceed 255
      fadeIn = 255;                                                     //clamp fadeIn value to 255

    }

}

+1 for properly formatted code .... if i could, i'd give you another +1 for the comments being out of the way of the code

Consider the sequence of values of "fadeIn". It starts at 8 and in incremented by 16.  So: 8, 24, ... 248, 264, ... .  It is never exactly 255.  So you never break out of your "for" loop.
There is only 1 delay in your example code.  It is difficult to associate the described behavior in your question and the location of the delay.
Arduino programming is actually C and C++ programming.  Developed at Bell Labs, this language has been around for decades and there are countless books on the subject.  Rather than rewriting your program (someone might yet still do this) I would recommend leaning C programming and if you want to write Arduino library software then C++ programming as well.

correct, i wanted to be flexible with the increment value. therefor this if was added at the end:
if (fadeIn > 255) {                                                 //if the fadeIn value exceed 255
fadeIn = 255;                                                     //clamp fadeIn value to 255
}

As you are new to stack exchange I would recommend the following: Ask one question at a time.  And do not hesitate editing your question to make the question better.   This is not a forum.  The questions should stand on their own and not depend on the discussion.  Be careful not to ask open ended questions nor opinions.   These types of questions usually get flagged and people will not answer them.  When writing your questions keep in mind others will search for your question and the answers posted.  So make the question concise and easy to understand.

thanks for the suggestions. I'll keep them in mind with future posting
I know there are books and I'm reading as much as I can online, but to do a full course on programming to get 1 led function to run would be a bit unbalanced for me (plus i'm a graphics man, not a heavy coder).
so I was hoping to get some advice on this 'simple' function that looks to be constructed properly from all references I found but somehow doesn't seem to work like it should

This is doing an assignment, not the comparison  you are expecting
if (led = 144

Need == for the comparison

I believed so too originally, but when I try this the function breaks and the fadeIn never increases.. so I left the led = 0 in it as led == 0 doesn't work

okay.. figured this one out.. it's never 144 as I have 144 leds but it start counting at 0 thus never reached 144 but only 143 as max

You close your for() loop right after the if statement that contains the break. No where in that for() loop do you change fadeIn, so there is nothing to break out of.
If you move the } that closes the for loop to below the code that changes fadeIn, then the break has an opportunity to be executed:
void loop() {
  for (int led = 0; led < NUM_LEDS; led++) {                            //move led up the strip till max count is reached
    ledStrip[led] = CHSV( 0+led*1.77, 255, 225);                      //set animated led hue value to make a rainbow
    FastLED.show();                                                   //show led color
    ledStrip[led] = CHSV( 0+led*1.77, 255, fadeIn);                   //set non animated led hue to same hue value while increasing the fade value
    delay(3);
    if (fadeIn > 254) {                                               //if the fadeIn value exceed 254
      break;                                                          //stop led animation
    }

    if (led = 144 && fadeIn < 254) {                                   //when the 144th led is reached and the fadein value is less then 255
      fadeIn+=16;                                                      //increase fadeIn value with 16
    }
    if (led = 144 && fadeIn < 255) {                                   //when the 144th led is reached and fadeIn is smaller then 255 show debug messages
      Serial.println(led);                                             //print led counter value
      Serial.println(fadeIn);                                          //print fadein value
    }
    if (fadeIn > 255) {                                                 //if the fadeIn value exceed 255
      fadeIn = 255;                                                     //clamp fadeIn value to 255
    }
  }
}

well, that the funny thing.. when i tried this before (or use your code) the loop doesn't run at all somehow.
I thought i needed to keep those last 3 if's out of the loop

There are other bugs, pointed out in the other answers, such as the assignment operator used in place of a comparison operator. I was only noting the bug of a loop break condition not able to be met if the condition doesn’t change within the loop.

Ok, thanks for all your help, found the solution to make it stable.
I think I got thrown off by the fact the led = 144 did (magically) seem to work outside the loop but led == 144 didn't work at all.
turns out i was counting the leds wrong (it's from 0-143 instead of 1-144) and that made all the other pieces fall into place.
tnx
#define FASTLED_ALLOW_INTERRUPTS 0                                    //fix jitter in led strip
#include <FastLED.h>                                                  //add fastled lib
#define NUM_LEDS 144                                                  //set number of leds
#define DATA_PIN D4                                                   //set data pin leds

CRGB ledStrip[NUM_LEDS];                                              //init led strip
int fadeIn = 8;                                                       //init fadein value
int fadeIncr = 16;                                                    //init fadein increments

void setup() {
  Serial.begin(115200);                                               //setup comm channel
  FastLED.addLeds<WS2811,DATA_PIN, RGB>(ledStrip, NUM_LEDS);          //setup ledstrip config
}

void loop()
{
for (int led = 0; led < NUM_LEDS; led++) {                            //move led up the strip till max count is reached
    ledStrip[led] = CHSV( 0+led*1.77, 255, 225);                      //set animated led hue value to make a rainbow
    FastLED.show();                                                   //show led color
    ledStrip[led] = CHSV( 0+led*1.77, 255, fadeIn);                   //set non animated led hue to same hue value while increasing the fade value
    delay(1);
    if (led == 143) {                                                  //when the 144th led is reached and the fadein value is less then 255
      fadeIn+=(fadeIncr);                                              //increase fadeIn value with 16
      fadeIn=constrain(fadeIn, 0, 255);                                // clip value range
        Serial.println(led);                                           //print led counter value
        Serial.println(fadeIn);                                        //print fadein
    }
    if (fadeIn == 255) {                                               //if the fadeIn value exceed 255
      break;                                                           //stop led animation
    }
  }
}

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


text:
Atmega328p - Going low power 1.8V using 4Mhz oscillator - Bootloader flash
I would like to use an Atmega328p micro-controller with a 4 Mhz oscillator in order get some low power consumptions. I am using an Arduino board to flash the bootloader into the Atmega.
EDIT
In order to compile the optiboot bootloader I had to install the avr-libc package and clone the repo
sudo apt-get install avr-libc
git clone https://github.com/Optiboot/optiboot.git

and edited the Makefile in /optiboot/bootloaders/optiboot/Makefile by adding a new entry called atmega328_4
HELPTEXT += "target atmega328     - ATmega328p 4Mhz\n"
atmega328_4: TARGET = atmega328
atmega328_4: MCU_TARGET = atmega328p
atmega328_4: CFLAGS += $(COMMON_OPTIONS)
atmega328_4: AVR_FREQ ?= 4000000L
ifndef BIGBOOT
atmega328_4: LDSECTIONS  = -Wl,--section-start=.text=0x7e00 -Wl,--section-start=.version=0x7ffe
else
# bigboot version is 1k long; starts earlier
atmega328_4: LDSECTIONS  = -Wl,--section-start=.text=0x7c00 -Wl,--section-start=.version=0x7ffe
endif
atmega328_4: $(PROGRAM)_atmega328_4.hex
atmega328_4: $(PROGRAM)_atmega328_4.lst

atmega328_4_isp: atmega328
atmega328_4_isp: TARGET = atmega328
atmega328_4_isp: MCU_TARGET = atmega328p
ifndef BIGBOOT
# 512 byte boot, SPIEN
atmega328_4_isp: HFUSE ?= D9
else
# 1k byte boot, SPIEN
atmega328_4_isp: HFUSE ?= D9
endif
# Low power xtal 46MHz) 16KCK/14CK+65ms
atmega328_4_isp: LFUSE ?= 7D
# 2.7V brownout
atmega328_4_isp: EFUSE ?= FE
atmega328_4_isp: isp

I saved the file, run the make command and got the following error:
userk@norepinephrine:~/development/git/optiboot/optiboot/bootloaders/optiboot$ make atmega328_4
avr-gcc (GCC) 4.9.2
Copyright (C) 2014 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

BAUD RATE CHECK: Desired: 115200, Real: 125000, UBRRL = 3, Difference=8.5%
avr-gcc -g -Wall -Os -fno-split-wide-types -mrelax -mmcu=atmega328p -DF_CPU=4000000L  -DBAUD_RATE=115200 -DLED_START_FLASHES=3           -c -o optiboot.o optiboot.c
optiboot.c:348:6: error: #error BAUD_RATE off by greater than 5%
     #error BAUD_RATE off by greater than 5%
      ^
optiboot.c:359:2: error: #error Unachievable baud rate (too fast) BAUD_RATE
 #error Unachievable baud rate (too fast) BAUD_RATE
  ^
<builtin>: recipe for target 'optiboot.o' failed
make: *** [optiboot.o] Error 1

So I changed the -DBAUD_RATE parameter to 19200 and rerun the make command
BAUD_RATE_CMD = -DBAUD_RATE=19200

Then 2 new files were created: optiboot_atmega328_4.elf and optiboot_atmega328_4.hex
Then I copied these files into the arduino configuration folder located
 at: /home/userk/.arduino15/packages/arduino/hardware/avr/1.6.21/bootloaders/optiboot
TIDE
I am using a custom board configuration file board.txt
##############################################################

nz.name=Arduino Noize

nz.vid.0=0x2341
nz.pid.0=0x0043
nz.vid.1=0x2341
nz.pid.1=0x0001
nz.vid.2=0x2A03
nz.pid.2=0x0043
nz.vid.3=0x2341
nz.pid.3=0x0243

nz.upload.tool=avrdude
nz.upload.protocol=arduino
nz.upload.maximum_size=32256
nz.upload.maximum_data_size=2048
nz.upload.speed=19200

nz.bootloader.tool=avrdude
nz.bootloader.low_fuses=0x7D
nz.bootloader.high_fuses=0xD9
nz.bootloader.extended_fuses=0xFE
nz.bootloader.unlock_bits=0x3F
nz.bootloader.lock_bits=0x0F
nz.bootloader.file=optiboot/optiboot_atmega328_4.hex

nz.build.mcu=atmega328p
nz.build.f_cpu=4000000L
nz.build.board=AVR_UNO
nz.build.core=arduino
nz.build.variant=standard

Flashing the Bootloader
I have followed these steps:

Uploaded the ArduinoISP sketch onto the Arduino UNO board.
Wired up the Arduino board and microcontroller as shown in the diagram below

Select "Arduino Noize" from the Tools > Board menu.
Select "Arduino as ISP" from Tools > Programmer
Run Tools > Burn Bootloader

At this point I got a success message from IDE. So the bootloader has been correctly flashed into the Atmega328p
The Problem
When I try to upload a sample sketch (blink) using the wiring below I get a timeout from the IDE.

I have double checked the connections but the sketch doesn't upload.
Do you have any advice?

How did you compile the optiboot bootloader? You need to tell the bootloader at what speed it's running.

Thanks, I am updating the post with the optiboot's Makefile

So you compiled optiboot with a baudrate of 19200, but specify 9600 in your boards.txt.

Sorry I didn't update the question after the addition of the optiboot configuration. Now it is updated. I still have the same timeout problem.

As Gerben notes in the comments, the bootloader has to know how fast the board is running. It uses this to work out the baud rate settings for the serial communication.
If you haven't compiled the bootloader yourself with the right clock settings you will probably find that it is operating at a quarter of the speed you expect it to. Dividing your upload baud rate by four in your board settings may make it work, but you really should compile the bootloader to match the board properly.

Thanks, I have edited the question with the information related to the optiboot bootloader compilation

As mentioned before, you need to compile the Optiboot bootloader with the correct clock frequency. Here's a guide that shows you how to do that, as well as adding an option to the Arduino IDE menu to select the right clock speed without having to add your own board definition.
Optiboot - ATmega328P at custom frequency

Good tutorial, I am trying to follow the provided steps but the example is for 12Mhz clock. Please see my edits

The principle is exactly the same for clock speeds other than 12 MHz. I think that you selected the incorrect baud rate for uploading. Either change nc.upload.speed in your boards file to 115200 baud, or recompile the bootloader with a baud rate of 19200.

nz.bootloader.low_fuses=0x7D
nz.bootloader.high_fuses=0xD9
nz.bootloader.extended_fuses=0xFE

Extended fuse byte. bits 2,1,0 determine the brown out level (bits 7-3 not used)
110 = 1.7 to 2.0V, 1.8 typical
Low fuse byte bits 3,2,1 determine the clock source
110 = low power crystal oscillator in 3-8 MHz range.
So those settings look okay.


text:
Checking a jumper between two pins on Arduino
I'm in the process of making a tag scanner (which transfers the tag ID to the computer), and I figured I'd use an Arduino Micro for that and just use the keyboard function on it to save myself a whole lot of hassle. From what I've read, however, having the keyboard open all the time can make it tricky to program it.
I figured my solution would be to use two of the pins as a jumper check, and have some code in the setup to read the input pin; if the circuit is closed between them, the keyboard function never activates, and if it's open, the Arduino will act as a keyboard. That way I should be able to put the jumper on if I need to program it, and leave it off if I just want it to run.
Unfortunately, I've never really done anything like this before, and I don't really want to just start plugging things around and run the risk of damaging my board. I've read around a bit, but I figured I wanted to bounce my ideas off of someone before I try it.
First, would you recommend a different approach? I did see a question that used the internal pullup resistor to check if a jumper connected it to ground, but since I only want to make this check once, is that a good route to go?
Secondly, if I connect it between two pins, am I correct in thinking I'd need a resistor between them (the Arduino website suggested 470ohm to 1kohm when connecting to other devices, so I'm guessing this would be a good number)? How would I set the pins up to make this work; should I put one pin as output and the other as input, and just read the input pin (after which I'd simply turn the output pin off), or would I need to add additional connections?
Thirdly, since this will use the USB port on the Arduino that is used to program it, is there a way to wipe the code from the Arduino in case of Serious Bugs, or is it possible to "brick" the board by tying up the USB permanently? I mean, I'll definitely make use of the Serial connection to test the output (and also to test the above jumper), so I think the odds are small enough to try it anyway, but... better safe than sorry?

why on-hold as too broad? there are two perfect answers

I had voted to close because multiple questions were asked in one question. I think Juraj is right, there are two great answers so I'm voting to re-open. +1 for each of the answers.

First of all, welcome here. Usually questions should contain, well, only one question ;)
In any case the usual circuit with buttons (a jumper can be seen as a button) are these ones:

simulate this circuit – Schematic created using CircuitLab
In the left case, usually the arduino pin is "pulled down" by the resistor when the button is not pressed (or the jumper is not present), so it will read "LOW". When the button is pressed, the arduino will see a "HIGH" value, since the button is "stronger" than the resistor and is able to force its value. The resistor is called "pull-down".
In the right case, the voltages are inverted. You read a "HIGH" value when the button is not pressed, and a "LOW" value when it is. The resistor is called "pull-up" for obvious reasons.
The resistor is needed because you need to have a "weak" component that can pull the arduino pin to a voltage value; it needs to be weak, so the button can override it.
The arduino, however, as a very common feature, called "internal weak pull-up" on the digital pins. This means that internally there is already the possibility to enable a weak resistor pulling the voltage to +5V. For this reason, what you need is to just connect the jumper to ground and read it.

simulate this circuit
You will need, in your setup, to set the pin as INPUT_PULLUP, and then check the value you read:
const byte jumperPin = 2;

void setup() {
  pinMode(jumperPin, INPUT_PULLUP);
}

void loop() {
  if (digitalRead(jumperPin) == LOW)
  {
    // Jumper is inserted
  }
  else
  {
    // Jumper is not inserted
  }
}

This is what the DigitalInputPullup example is for...
Regarding your other question, there is a connector on every board named ICSP (of if there isn't, you should have access to the ICSP pins from somewhere else). This connector is used to flash the bootloader again (or to flash a program with an external programmer). You will need a atmel programmer to restore the original bootloader and "unbrick" it.
Luckily any arduino board can be used for this task; you will just need to download on another board the sketch ArduinoISP (already included in Arduino IDE) and you can use it to flash. There is plenty of tutorials online to do it. So to "unbrick" it you will just need another arduino board

First off, the premise:

having the keyboard open all the time can make it tricky to program

is completely false.
The problems that people experience with programming are when the Arduino is sending keystrokes all the time without external stimulus.  This makes it tricky to do anything - not just program. Just like it's hard to write a letter when you have a cat walking all over your keyboard.
So as long as you aren't just sending keypresses all the time, and only send them when you actually read a card, there is no problem for you to try and fix.
Secondly, the idea:

use two of the pins as a jumper check, and have some code in the setup to read the input pin; if the circuit is closed between them, the keyboard function never activates, and if it's open, the Arduino will act as a keyboard.

is overly complex and meaningless.  If all you want to do is check a state of "set" or "not set" using some external "device", what you're talking about is a button, or a switch.  You don't need two pins for that - only one. And there's a myriad of tutorials available on the internet showing you in detail how to read the state of a button (or switch). (Hint: use a pin set to INPUT_PULLUP and connect that pin to GND to "activate" it. Include a small [100Ω] resistor for safety if you like).
So in summary:

Unless you're being really daft in your program, there is no problem to solve.
You are over-thinking your solution.


text:
1-10 volt analog signal
I have an Arduino project where I am using an ESP8266 (Wemos D1 mini) powered via USB. I want/need to output an analog voltage from 0 to 10V.
Goal:
A solution that is pre-made (eg a shield or sparkfun type module) or easy to build circuit that does not require a new power supply (besides the ones I have which is 3.3V and 5V, thanks to Wemos USB power).
Many devices allow you to control them using a 1-10V signal. I have two LED drivers at home that I would like to interface with: specs1, specs2.
What would be the easiest solution to generate a 1-10 Volt signal? Is there a module I can use?
I read about Op-amps but I don't yet have the knowledge to build one myself.
Another method is a DAC, but that seems to require a separate 10 Volt power supply.

Why the downvote? Please let me know so I can improve the question

Seriously! My question might have issues, but downvoting without leaving an explanation is to say the least not constructive. This gives me a sour taste as a new user. My only option now is to leave as I am clearly not welcome here for reasons unknown to me,

Welcome to Arduino:SE. I'm not one of those who downvoted, but the question does look to be off-topic here.  There is a good guide on How to ask a good question for Arduino Stack Exchange on our meta site.

I didn't downvote, but I did vote to close, unfortunately. This would be better asked on SE.Electronics as it isn't really Arduino specific (unless I am missing something)

@Greenonline, the question is here, so we can answer, how to do it with Arduino. my answer is on-topic, I think

But @Juraj, whilst your answer seems to be a good answer, it doesn't really mention Arduino (apart from your link), and it seems to be an electronics interfacing question & answer, rather than Arduino specific. I'll cast a reopen vote though

This question in my opinion exists in the grey area between Arduino and Electronics Stack Exchange.  I think if your question included more mentions of "Arduino" and/or "Arduino project" I think it may have been OK. On the other hand, there is no other way to generate a voltage of 1-10V without using external electronics. The question would then be what circuit is best suited for your situation. With all that said, the majority of Arduino projects need some electronics - just look at the examples and most of them give a circuit to use. I think this would be useful for other Arduino users.

You do not need a DAC. In this 'regulation cases' PWM on digitalPin is used. See analogWrite Arduino function.
I use Grove MOSFET module to have PWM of desired voltage. The MCU generates a 3.3 V PWM. MOSFET module gets in my case 5 V as input voltage. You would use 10 V as Vin. MOSFET switches the 10 V line on and off at 'PWM speed' resulting in 10 V PWM.
As 10 V source you could use a 'boost' converter, to convert 5 V to 10 V.
This is the schema of the Grove MOSFET module:

i would add a cap to the output to filter the PWM into a steady voltage.

The ADM660, link below,

is a charge-pump voltage converter that can be used to either invert the input supply voltage giving VOUT = -VIN or double it (ADM660 only) giving VOUT = 2 x VIN.

It accepts an input range between 1.5V-7V so if you use the 5V from the Wemos USB power you'll be able to reach the desired 10V for your application, and it's cheap :)
http://www.analog.com/media/en/technical-documentation/data-sheets/ADM660_8660.pdf


text:
Looking for a waterproof SPI temperature sensor
In my current project I'm using a DS18B20, which seems to be the only temperature sensor to show up when googling for waterproof temperature sensor for an arduino.
The sensor itself is fine, however, I'm outputting the sensor's data to a SPI screen, and whenever the sensor is called to read data I believe the SPI communication is interrupted because of 1-Wire, and you can see a white flicker on the screen. The background LED is flashing more brightly for one frame. It's almost unnoticeable, but it bothers me.
I'm not using delays, and I'm not redrawing unnecessary elements on the screen again. Only dynamic elements are refreshed when they need to, static elements are only drawn once on the screen. The sensor is called every 5 seconds with a comparison:
if(currentTime - lastTimeQueried >= delay){
    lastTimeQueried = currentTime;
    temperature = new temperature;
    return temperature;
} else {
    return temperature;
}

I also tried a function where I'm constantly calling the sensor and only drawing on the screen if there's a change in temperature, but then the screen is flickering all the time. Thus I conclude that the flickering is caused by the actual calling of the sensor, and not from redrawing anything on the screen.
So I'm wondering if there's an alternative to the DS18B20 that communicates via SPI, and that I can use in an aquarium, so I don't have to use both protocols in my project.
Edit:
As requested some more of my code and wiring:
The screen is wired to the ICSP headers on my Arduino Mega 2560 and power is supplied via 5V on a powersupply that is connected to my breadboard.
The DS18B20 is wired to pin 29 on the Arduino and is also supplied with power via 5V on the same powersupply.
//TFT SPI
#define TFT_DC 9
#define TFT_CS 10
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC);

//SD Card Reader SPI
//#define SD_CS 4

//Touchscreen I2C
UTouch  myTouch(5, 8, 6, 7, 2);  //(T_CLK, T_CS, T_DIN, T_DOUT, T_IRQ)

#define ONE_WIRE_BUS 29
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

Here are some more variables that I have defined to help with using the sensor:
//Temperature measurement
unsigned long lastTempMeasure;  //Holds last unix timestamp temperature was measured at
char tempMeasureDelay = 5;      //Call temperature every 5 seconds
float sensorTemp;               //Holds measured temperature

In my loop I then use this function:
tft.print(temperatureCall());

and then:
float temperatureCall(){
  //get unix time for right now
  unsigned long currentUnix = now();

  //if 5 seconds passed since last poll, ask for new temperature, else return old measurement
  if(currentUnix - lastTempMeasure >= tempMeasureDelay){
    lastTempMeasure = currentUnix; //save last polling time

    sensors.requestTemperatures();
    sensorTemp = sensors.getTempCByIndex(0);

    return sensorTemp;
  } else {
    return sensorTemp;
  }
}

As I said, the flicker only occurs when these two are used every 5 seconds:
sensors.requestTemperatures();
sensorTemp = sensors.getTempCByIndex(0);

Edit 2:
Pic of wiring:

Can you share your wiring including LCD display over SPI and DS18B20 and some more of your code?

@Sener I have updated my post

It sounds more like a power issue rather than a communication issue. How are you powering the backlight for the display?

Thanks for the details, seeing big picture helps most of the time.
I consider, SPI pins are not shared with some other SPI device.
So, the sensor is on one of the digital pins which is also fine. But, since the onewire is using bit-banging, trying some other pins for the sensor would be wise.
Besides this, the backlight led is not obvious. I think it is directly connected to 5V, isn't it? I recommend measuring voltage and the current board draws. If they fluctuates (voltages drops) or making a sudden move than we can take it from there.

What I have also thought of that it might indeed be a powering issue since the sensor is using a pullup resistor on the data line which is connected to 5V.
@Majenko the backlight LED is powered by the powersupply via 5V.
I will update my post with a picture of the wiring

@Sener why would it be wise to try a different pin for the sensor? What other pin would you recommend?

It really looks like sudden voltage drop or lack of current (tiny) when the sensor is active.for reading. But, datasheet says it is not dramatic, 1mA to 4mA.
But, apart from this, what I say that, I have those LCD's running on one of my products are not rock solid. In a batch, some of their backlight are bright some faded, some flickering.

Trying different pin is always a case I follow when debugging some issues in order to eliminate inconsistent design on some gates particularly clone components. You never know.

Hm, definitely food for thought. Will look more into this. Unfortunately I can't really measure any voltage drop with my multimeter which just shows mostly constant values on the backlight. Definitely no drops or peaks every 5 seconds.
This project might become a product, but at that stage I will be working together with a friend who is an electrician to help me with this, so he might know more.
Thanks for sharing your knowledge guys, this was really driving me a little nuts, knowing what's behind it or at least pushing me into the right direction definitely eased my mind.

Any time. A last note, you may try to place a 10uF Electrolytic on your power rail between GND and 5V. This can buffer (buy) some time when power is affected during sensor reading. Good luck with your project.

The 1-wire protocol uses specific timing. To do that, the OneWire library turns off the interrupts temporarily to create that signal. You can test that by turning off the interrupts for some time to see what will happen. Is there really no time for the OneWire library without disturbing the display? Perhaps the sketch needs to be fixed. There are good i2c temperature sensors. You can make them waterproof with food-safe materials. The best solution might be to replace the display and use a smart display with serial communication.

@Jot there is a clock on the display that also shows seconds. Maybe I can jerry-rig something in, but then it may slow down the entire sketch.

@Sener I have added a capacitor to my wiring. Another interesting observation I have made is that if I connect ground from my rail to the ground of my arduino, the screen turns completely white after the sketch ran for 5 seconds, presumably because it then calls the temperature of the sensor..
When I remove the capacitor, the same thing happens, but only after 10 or 15 seconds.

What you are saying reminds me my another experience with running two SPI's together. If you don't place resistors (4k7) serially connected to MOSI and SCK pins, they were effecting each others and my TFT 2.2'' display was going white. If so, what @jot says may be quite relevant to your issue.
You may be also try another version of 1-wire libraries.
Let's say 1-wire library

@Sener I already used 1k resistors on every data line. I tried 5k resistors, but then I couldn't keep the display running. It would display one frame and then do weird stuff. Tried with 2k resistors too which seems to have improved the issue a little. Unfortunately I don't have 4.7k resistors on hand...I should really expand from the parts that I have available from my tutorial kit.

There is a delay in the DallasTemperature requestTemperatures() function - it blocks until the temperature conversion is complete unless you have previously called setWaitForConversion(FALSE). If you did that, you would still have to wait for the conversion but you can do it an a non-blocking manner, and I don't see that happening in your code.

Thank you.
Is this something I need to call once in the setup? Or every time I am polling temperature from the sensor?

Looking at this DS18b20 library, the flag does not appear to get changed except by an external call, so setting it once should be sufficient. [Sorry for my typo in the original reply].


text:
problem with reading PS3 controller buttons
I'm working on a camera slider mount with an X stepper (to move along slider), Y stepper (pan left right) and Z stepper (tilt up down). All of this is being controlled by a PS3 controller (PS3BT library).
I've implemented a feature in which all three steppers move from one saved position to other and then back again.. this keeps repeating infinitely. It works fine - except I can't stop it - it's more of a programming issue I think. Here's the code in question
// MultiStepper instance - at the top somewhere
MultiStepper StepperControl;

void loop(){
    if(PS3.getButtonClick(START)){ // START to start movement between two POS's.
        Serial.print("\n Starting Movement between POS1 and POS2");
        while(!PS3.getButtonClick(CROSS)){
          StepperControl.moveTo(POS1); // go to POS1
          StepperControl.runSpeedToPosition();
          delay(200);
          StepperControl.moveTo(POS2); // go to POS2
          StepperControl.runSpeedToPosition();
          delay(200);
        }
      }
}

My issue is that pressed X (cross) on the keypad, doesn't quit out of the loop. What I feel is happening is that the loop is running too fast and all the moveTo() commands are stacking on top of each other. And so, even if I do press X, too many moveTo() commands have already happened and it just keeps running those "queued" commands.
I've also tried putting an if statement inside the while loop that breaks out of the loop when CROSS is pressed - no luck.
// This isn't the entire code, just the parts I think are relevant.

you need to identify the problem correctly before you can arrive at a solution ..... the description of your problem has nothing to do with the AccelStepper Library - moveTo() ..... remove all the stepper code from your sketch (or start a new sketch) .... keep the PS3 code and use serial.print() to debug your code ..... determine which code you need, to correctly detect which buttons are being pressed

The while(!PS3.getButtonClick(CROSS)) is only checked once per loop, so your system will complete a move to POS1, wait 200ms, complete a move to POS2, and wait another 200ms before it can check the controller for another button press.
runSpeedToPosition() is "blocking", which means NOTHING else can happen while it is doing it's task.
Instead, you probably want to avoid blocking functions and set up a finite state machine and use the run() function of AccelStepper, which you should call as often as you can and it will move the stepper one step toward the target position, if it's not yet at the target position.
The following rewrite is not tested, but the general structure should show you how you can change the way the program is written. You should think of the loop() function running and completing a million times a second, and each time through, you check the state (that is, on what step is the system currently on) and act accordingly. Change to a new state when appropriate.
In the example, there are 5 states, corresponding to all possible combinations of what your program could be doing:

STOPPED: the initial state, the stepper has no target
RUNTO1: the stepper is moving toward POS1, but hasn't reached it yet
WAIT1: the stepper has reached POS1 and is now waiting for a specified delay before moving to the next state. This state uses the process shown in the BlinkWithoutDelay standard Arduino example sketch for delaying without blocking.
RUNTO2: the stepper is moving toward POS2, but hasn't reached it yet
WAIT2: the stepper has reached POS2 and is now waiting for the next state

You can also see the situations where a state is changed:

When START is pressed, set a new target position and enter the
RUNTO1 state
When CROSS is pressed, stop all stepper action and enter the STOPPED state
When in RUNTO1 or RUNTO2, and the distanceToGo() is zero, enter to the corresponding WAITn state
When in the WAITn state and the specified time has elapsed, enter the corresponding next RUNTOn state.

Example:
#define POS1 80
#define POS2 0

const uint16_t DELAY = 200;
enum stepperstates {STOPPED, RUNTO1, WAIT1, RUNTO2, WAIT2};

[...]

void loop() {
  static uint16_t last_millis;
  static stepperstates xStepState;
  if (PS3.getButtonClick(START)){
    xStepState = RUNTO1;
    StepperControl.moveTo(POS1); // go to POS1
    Serial.print("\n Starting Movement between POS1 and POS2");
  }
  if (PS3.getButtonClick(CROSS)) {
    xStepState = STOPPED;
  }

  StepperControl.run();

  switch (xStepState) {
    case STOPPED:
      StepperControl.stop();
      break;
    case RUNTO1:
      if (StepperControl.distanceToGo()==0) {
        xStepState = WAIT1;
        last_millis = millis();
      }
      break;
    case WAIT1:
      if (millis() - last_millis >= DELAY) {
        xStepState = RUNTO2;
        StepperControl.moveTo(POS2);
      }
      break;
    case RUNTO2:
      if (StepperControl.distanceToGo()==0) {
        xStepState = WAIT2;
        last_millis = millis();
      }
      break;
    case WAIT2:
      if (millis() - last_millis >= DELAY) {
        xStepState = RUNTO1;
        StepperControl.moveTo(POS1);
      }
      break;
  }
}

Ahh. That makes so much more sense. So basically with my original code - the user got almost no chance to even press X because delay() was blocking and so was the moveToPosition(). And now with this code - run() is not blocking and each time run() happens, we check if X was pressed and if so enter the STOP state.


text:
How do I select Sensor using chip 74HC138 on Wemos D1 Mini?
I have a project for my graduate degree.
It's about Monitoring Temperature and Humidity using Message Queuing Telemetry Transport on Serial NodeJS. To get sensor data to Wemos D1 Mini and NodeJS had done, also on my MQTT had done. My lecturer wants to get data from two sensors at the edges of the room, he suggests using a 74HC138. I'm using this 74HC138 Datasheet and I'm using this BME280 Library.
This is my schematic:

This is my code:
#include <BME280.h>

const uint32_t SERIAL_SPEED = 115200;
const uint8_t SCK_PIN = D5;
const uint8_t MISO_PIN = D6;
const uint8_t MOSI_PIN = D7;
const uint8_t SPI_CS1_PIN = 15;
const uint8_t SPI_CS2_PIN = 14;
const uint8_t GPIO[3] = {D1, D2, D3};

static int32_t temperature, humidity, pressure;
int i;

BME280_Class   BME280;

void setup() {
  Serial.begin(SERIAL_SPEED);
  pinMode(SCK_PIN, OUTPUT);
  pinMode(MOSI_PIN, OUTPUT);
  pinMode(MISO_PIN, INPUT);

  SPI.begin();
  SPI.setBitOrder(LSBFIRST);

  Serial.println(F("condition before loop = "));
  //status_pin();
  for (i = 0; i < 3; i++) {
    pinMode(GPIO[i], INPUT);
    digitalWrite(GPIO[i], HIGH);
  }
  pinMode(SPI_CS1_PIN, OUTPUT);
  pinMode(SPI_CS2_PIN, OUTPUT);

  Serial.println(F("Starting Hardware SPIDemo example program for BME280"));
  Serial.print(F("- Initializing BME280 sensor\n"));

  if ( (!BME280.begin(SPI_CS1_PIN) && (!BME280.begin(SPI_CS2_PIN) ) {
    Serial.println(F("-  Unable to find BME280. Waiting 3 seconds."));
    delay(3000);
  }

  BME280.mode(SleepMode);
  Serial.print(F("- Sensor detected in operating mode \""));
  Serial.print(BME280.mode());
  Serial.println(F("\"."));
  if (BME280.mode() == 0) {
    Serial.print(F("- Turning sensor to normal mode, mode is now \""));
    Serial.print(BME280.mode(NormalMode));
    Serial.println("\"");
  }
  Serial.println(F("- Setting 16x oversampling for all sensors"));
  BME280.setOversampling(TemperatureSensor, Oversample16);
  BME280.setOversampling(HumiditySensor,   Oversample16);
  BME280.setOversampling(PressureSensor,   Oversample16);
  Serial.println(F("- Setting IIR filter to maximum value of 16 samples"));
  BME280.iirFilter(IIR16);
  Serial.println(F("- Setting time between measurements to 1 second"));
  BME280.inactiveTime(inactive1000ms);
  Serial.print(F("- Each measurement cycle will take "));
  Serial.print(BME280.measurementTime(MaximumMeasure) / 1000);
  Serial.println(F("ms.\n\n"));
}

void loop() {
  static uint8_t loopCounter = 0;
  byte pin1 = 0x74;
  byte pin2 = 0x71;

  if ( BME280.begin(SPI_CS1_PIN) == 1 ) {
    selpin(pin1);
    Serial.println(F(" Data Bme = "));
  } else if ( BME280.begin(SPI_CS2_PIN) == 1 ) {
    selpin(pin2);
    Serial.println(F(" Data Bme = "));
    printdata();
  }

  if (++loopCounter % 10 == 0) {
    Serial.print(F("\n- Turning "));
    if (BME280.getOversampling(HumiditySensor) == 0) {
      BME280.setOversampling(HumiditySensor, Oversample16);
      Serial.print(F("ON"));
    } else  {
      BME280.setOversampling(HumiditySensor, SensorOff);
      Serial.print(F("OFF"));
    }
    Serial.println(F(" humidity sensing"));
    Serial.print(F("- Each measurement cycle will now take "));
    Serial.print(BME280.measurementTime(MaximumMeasure) / 1000.0);
    Serial.println(F("ms.\n"));
  }

  Serial.println(F("condition after loop = "));
  //status_pin();
  Serial.println();

}

float altitude(const float seaLevel = 1013.25) {
  int32_t temp, hum, press;
  BME280.getSensorData(temp, hum, press);
  float Altitude = 44330.0 * (1.0 - pow(((float)press / 100.0) / seaLevel, 0.1903));
  return (Altitude);
}

void printdata () {
  BME280.getSensorData(temperature, humidity, pressure);
  Serial.print(F("Temperature : "));
  Serial.print(temperature / 100.0);
  Serial.println(F(" *C"));
  if (BME280.getOversampling(HumiditySensor) != 0) {
    Serial.print(F("Humidity : "));
    Serial.print(humidity / 100.0);
    Serial.println(F(" %"));
  }
  Serial.print(F("Pressure : "));
  Serial.print(pressure / 100.0);
  Serial.println(F(" hPa"));
  Serial.print(F("Altitude : "));
  Serial.print(altitude());
  Serial.println(F(" m"));
  Serial.println();
  delay(5000);
}

Serial output always says Unable to find BME280. Waiting 3 seconds. I know it's because CS pin cannot detect. I think something is missing my code.
SOLVED
Thanks to my pal @Majenko, I'm out of the 74HC138 stock but i have 74HC139, i think that's same to me, i tried advice from @Majenko early morning after i make assembly of my board own for define Chip Select Wemos to my enable pin and get back my missing code whom not understand me.
See below for verbose log of uploading my sketch.

See below for serial monitor.

Thanks.

Using a 74HC138 in this situation is both pointless and wasteful. You're using 3 pins (or 4 - see below) to drive a chip to select between 2 pins. That's wasting one more pin than you would by directly driving the CS pins.
The only time it would make sense would be if you were wanting to connect with 5 or more devices, in which case you would get a saving in the number of pins used.
Anyway - what you are missing from your code is absolutely everything to do with the 74HC138. First off, you're using a library which assumes the CS pins are directly connected to the MCU. Second, there is no code to set the A/B/C pins to the right state to select an output.
If you really must use the 74HC138 I would suggest:

Use the same CS pin in your code for every BMS280 instance.
Connect that CS pin to G2A on the 74HC138
Use the following procedure to access a sensor:

Select the correct output on the 74HC138 by setting the A/B/C pins to the binary representation of the output you want
Perform the BME280 operations you want on the relevant instance

simulate this circuit – Schematic created using CircuitLab
The CS pin you passed to the BME280 instances will control the state of the currently selected output on the 74HC138, turning it into a demultiplexer controlled by the A/B/C pins.  Using multiple instances of the BME280 class associated with each selected output will allow proper tracking of any internal state and data associated with the device connected to that output.
Or, and this is just throwing ideas out there, don't use the 74HC138 and tell your "lecturer" that it's a stupid idea to use 3 pins (4 including the chip select pin) to control a pair of devices that need a total of 2 pins.

i'm still little confuse sir, your mean "Connect that CS pin to Q2A on the 74HC138" i must connect CS to enable input pin and where i must connect Y1-Y2 output pin? where i can find example of send the binary representation to chip. i really noob about chip gate sir

Sorry, that's a G on your little picture, not a Q.  Looks the same to me.  You don't "send" the binary representation to the chip. You set your three pins connected to A/B/C to that binary representation. Output 0 is LOW/LOW/LOW.  Output 1 is HIGH/LOW/LOW. Output 2 is LOW/HIGH/LOW, Output 3 is HIGH/HIGH/LOW, etc.  Outputs go as they are now.

yes that's G, it's fine, ok i can see what do you mean on your picture, to set A/B/C pin what i must using pinMode or digitalWrite sir?

Both. pinMode to set them as outputs, and digitalWrite to set the logic levels.

hello again my pal, if my lecture want to set enable pin as low, which one i do declare CS pin to my 74hc139 sir? i didn't get option anything.

I don't understand what you're asking (language barrier).

sorry my bad, if my lecturer want to connect enable pin to gnd as active low, how i do connect cs pin in wemos to IC 74hc139 sir?

With a wire? I still don't understand what you want.

yes with a wire, if GA pin to GND pin as active low , how i do initialize CS pin in wemos to IC ?

The bme280 library should be doing all that for you

if i define D8 pin, where i must connect to 74hc138 in order to get data?

G2A as I have shown in my schematic.

if i connect D8 pin to G2A pin whether it is active low

G2A and G2B are active low. G1 is active high. All three need to be active for the chip to operate.

is it D8 pin becomes active low?

Outputs don't have a concept of "active", only a currently selected level. If you use D8 in the begin function to a BME280 object then the BME280 code will drive it low for you when it needs to.

if i connect G2A pin to GND pin as active low, how i use D8 pin to make the begin function?

The wemos connects it to ground for you. You don't connect it to ground. D8, when low, connects the pin to ground.

i see now, a voted for you!!


text:
How do I create a state machine for my purpose?
I am new to Arduino.
I have a motor which drives a sliding door back and forth. The motor is connected to an H bridge which has two control pins (direction, speed). I have a switch which is intended to activate the motor for a set amount of seconds to open the door fully. When the switch is deactivated, the motor reverses for the same duration as opening.
I have written some basic code using the 'if' argument, but my issue is that the code under the 'if' argument loops when my switch is activated/deactivated whereas I want it to run once per switch activation. Looking online I saw that a state machine may be my solution, but my lack of expertise with coding means I cannot create a state machine. This is my code:
const int Switch = 2;
const int hbridge1 = 13;
const int hbridge2 = 12;
const int threshold = 400;

int buttonState = 0;

void setup() {

  pinMode(hbridge1, OUTPUT);
  pinMode(hbridge2, OUTPUT);
  pinMode(Switch, INPUT_PULLUP);

  Serial.begin(9600);
}

void loop() {
  int buttonState = digitalRead(Switch);
  Serial.println(buttonState);

  if (buttonState == HIGH) {
    digitalWrite(hbridge1, HIGH);
    digitalWrite(hbridge2, LOW);
    delay(4000);
    digitalWrite(hbridge1, LOW);
    digitalWrite(hbridge2, LOW); //I only need the motor to activate for four seconds, but 'if' loops it infinitely
  } else {
    digitalWrite(hbridge1, LOW);
    digitalWrite(hbridge2, HIGH);
    delay(4000);
    digitalWrite(hbridge1, LOW);
    digitalWrite(hbridge2, LOW); //Same issue  here
  }

;
  delay(1);
}

to open it when it is switched on .... to open what? ... the switch?

code under the 'if' argument loops infinitely ..... that is not correct .... code in the loop() function loops infinitely

look at the BlinkWithoutDelay example sketch .... it shows how to time an event .... you also need to store the value of buttonState and run the code only when it changes (store the new value of buttonState at the end of the code)

Creating a few boolian variables could help with this.
bool opening = 0
bool closing = 0

const int Switch = 2;
const int hbridge1 = 13;
const int hbridge2 = 12;
const int threshold = 400;

int buttonState = 0;

void setup() {

  pinMode(hbridge1, OUTPUT);
  pinMode(hbridge2, OUTPUT);
  pinMode(Switch, INPUT_PULLUP);

  Serial.begin(9600);
}

void loop() {
  int buttonState = digitalRead(Switch);
  Serial.println(buttonState);

  if (buttonState == HIGH && opening == 0) { //variable "opening" is tested
    opening == 1  //variable "opening" is set to on
    closing == 0  //variable "closing" is set to off
    digitalWrite(hbridge1, HIGH);
    digitalWrite(hbridge2, LOW);
    delay(4000);
    digitalWrite(hbridge1, LOW);
    digitalWrite(hbridge2, LOW);
  }
    else if (buttonState == Low && closing == 0){ //variable "closing" is tested
      opening == 0    //variable "opening" is set to off
      closing == 1    //variable "closing" is set to on
      digitalWrite(hbridge1, LOW);
      digitalWrite(hbridge2, HIGH);
      delay(4000);
      digitalWrite(hbridge1, LOW);
      digitalWrite(hbridge2, LOW); //Same issue  here
  }
  delay(1000) // delay is in milliseconds. So 1000 = 1 second
}

These new variables are set when the code is ran the first time. Therefore, no looping.

A schematic will help to create a solution. Are you using a resistor, like 10K, to pull the switch pin low? If the button is not pressed and the code keeps looping through like it is pressed, I recommend adding the resistor. You may need to add another component though. Like a micro-switch on the frame of the door that gets tripped while it is closed. Or a button to close the door. Without that every loop through the code will think the switch is held low and activate the motor. Which might burn out the motor or trip a fuse.
if(buttonstate == high){
//open door
}
else{
if(microswitch == high){
//H-bridge pins low, low
{
else{
//close door
{

simulate this circuit – Schematic created using CircuitLab

Thank you for your response. I am using the inbuilt pull up resistor to pull the switch pin low. As for the microswitch, it is a good idea however for my purposes I would like to control the motor using a fixed duration (I have timed how long it takes for the motor to open/close the door using a stopwatch). When the switch is low, activate the HBRIDGE1 pin for closing duration then halt till the switch is activated. When the switch is high, activate HBRIDGE2 pin for opening duration.

every time void loop() loops it will look at the switch and see it is low and activate the else{} loop of the if. So the door will be closed and it will do else{} you might need something more. like
if(buttonstate == high){
//open
//delay
//close
}
else{
//h bridge low, low
}

I'll do that until I can work out how to make a state machine. Thanks.

K.I.S.S. Keep It Simple Stupid. I think that is the simplest solution. It will open, delay, close, then if it is low it will sit with the motor in break mode


text:
INPUT_PULLUP not work for D8 in my NodeMCU v3
I changed my arduino NodeMCU application pin mode to use INPUT_PULLUP mode instead of INPUT. D8 input pin is not working as expected, I is always in LOW even the button is pressed or not.
I have 3 input pins (D2, D7, D8), when I changed to internal pull up resistor, I removed each external resistors from input and changed the circuit accourding to this: https://www.arduino.cc/en/Tutorial/InputPullupSerial
D2 and D7 works well, but D8 is not. I checked with a volage between GND and pins:

when button on D2, D7 is not pressed: 2.95 - 3 V
when button on D8 is not pressed: 0.8 V
when button on D2, D7, D8 is pressed: 0V (as expected)

You can see my code in github:
https://github.com/kisdaniel/HomeDashboardGarageDoorOpener

Pin D8 is esp8266 pin 15. This pin is one of the boot configuration pins and for use on a dev board, it must be pulled down at boot. So the NodeMcu has a pull down circuit on this pin and internal pullup is weaker then this external pulldown.


text:
Serial communication between python and arduino
I am working on object tracking robot. I am using python and OpenCV to detect the object and send the proper data to the arduino that controls two servo motors.
The data which should be sent to the arduino are servo motors angles ranging between 0-180. I am using sample codes to understand how python and arduino communicate using serial bus.When I send a single digit, the arduino receives it and work as intended, but when I send more than one digit nothing happens.
This is the arduino code:
#include <Servo.h>
int data;
Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards
int pos = 0;    // variable to store the servo position

void setup() {
  Serial.begin(9600); //initialize serial COM at 9600 baudrate
  pinMode(LED_BUILTIN, OUTPUT); //make the LED pin (13) as output
  digitalWrite (LED_BUILTIN, LOW);
  myservo.attach(9);
  Serial.println("Hi!, I am Arduino");
}

void loop() {
while (Serial.available()){
 //to receive more than one character
 char buffer[] = {' ',' ',' ',' ',' ',' ',' '}; // Receive up to 7 bytes
 while (!Serial.available()); // Wait for characters
 Serial.readBytesUntil('n', buffer, 7);
 data = atoi(buffer);

}
myservo.write(data);
}

And here is the python code:
import serial
import time  # Required to use delay functions

arduinoSerialData = serial.Serial('com14', 9600)  # Create Serial port
object called arduinoSerialData
time.sleep(2)  # wait for 2 secounds for the communication to get
established

print arduinoSerialData.readline()  # read the serial data and print it as
line
print ("Enter 1 to turn ON LED and 0 to turn OFF LED")

while 1:  # Do this forever

    var = raw_input()  # get input from user
    print "you entered", var  # print the intput for confirmation

    arduinoSerialData.write(var)

the only debugging code that you have is Serial.println("Hi!, I am Arduino"); .... put in more debugging code to determine what is being received

If the python Serial write function sends byte, then you should read it in Arduino with Serial.read().
void loop() {
  if (Serial.available()){
    byte data = Serial.read();
    myservo.write(data);
  }
}

If python sends the number as text, then you can read it with parseInt().
void loop() {
  if (Serial.available()){
    int data = Serial.parseInt();
    myservo.write(data);
  }
}

The parseInt is one of the blocking functions and will by default wait one second for next char after the last sent digit was received. But the number is sent at once from python so the delays between digits are small. Set in setup() Serial.setTimeout(10);

I need to update the servo's angle continuously. Is there something wrong with that?

I don't know. I never controlled servos.

How arduino saves the received data? in what data type?

I edited the answer

please check this post:
https://arduino.stackexchange.com/questions/55986/delay-in-serial-communication-between-python-and-arduino

read the last paragraph of this answer

Besides timeout, parseInt also returns on a non-valid characters for an integer. If you send the number as a line, there shouldn't be any delay. You just need to clear the leftover characters from the buffer, because parseInt doesn't consume them.

but here it is machine to machine. and perhaps manual entry from Serial Monitor for test.


text:
How to detect when intercom is ringing?
For my apartment, I need to check when intercom is ringing and call an API in that case. I was thinking about using an AC input / DC output relay, since the buzzer signal is an AC signal. Is there an equivalent pre-built component similar to this?

As it sounds like you do not own the buzzer (it is part of the appartment), someone may not like you directly connecting to it.
If this is a classic buzzer with an electromagnet, consider using a Hall Effect Sensor.  The magnetic field generated by the buzzer may be able to activate the Hall Effect Sensor and inform the Arduino the buzzer has been activated.  This article talks about Hall Effect sensors and an Arduino.
Image of Arduino and Hall Effect Sensor from linked to article:

Further, this is a much safer way connect to a buzzer.  As a classic buzzer can generate very high voltages that can damage processors and other sensitive electronic devices when directly connected.

Can you please share a wiring diagram?

There is a diagram from the article linked to in the answer.  I'll add the same image to the answer.

Most Arduino solutions / answers will use an Arduino Uno.  An ESP8266 is a very complex chip and through the efforts of a few has been added to the list of chips which can be supported using the Arduino Integrated Development Environment (IDE).  The problem with the specific board you have chosen, the eps01 board, is that it brings out very few of the ESP8266's pins to the user.  Further, the ESP8266 is very different from the usual ATmega328P processor used on most Arduino boards. Making it even more difficult to look for examples of exact solutions to your situation.

Your solution is nice but requires the circuit to be close to the buzzer. What about using a rectifier and a 12V relay to close the arduino 3.3V / input loop?

The question hinted at using an EP01 device which contains a WiFi radio.  If so, this small "IoT" device could be, as long as power was available, right next to the buzzer.  As it could communicate the state of the buzzer to any other WiFi device wirelessly.  You could use a relay.  But are you sure of the type of signal used by the installed buzzer?  You assumed AC (recommending a rectifier) but it could be DC.  And it may not be 12 volts.


text:
TinkerCAD switch seems to be not working (always closed)
I am using TinkerCAD to simulate the functionality of a slide switch. Please comment if you think this question is off-topic.
/*
  LiquidCrystal Library - Hello World

 Demonstrates the use a 16x2 LCD display.  The LiquidCrystal
 library works with all LCD displays that are compatible with the
 Hitachi HD44780 driver. There are many of them out there, and you
 can usually tell them by the 16-pin interface.

 This sketch prints "Hello World!" to the LCD
 and shows the time.

  The circuit:
 * LCD RS pin to digital pin 12
 * LCD Enable pin to digital pin 11
 * LCD D4 pin to digital pin 5
 * LCD D5 pin to digital pin 4
 * LCD D6 pin to digital pin 3
 * LCD D7 pin to digital pin 2
 * LCD R/W pin to ground
 * LCD VSS pin to ground
 * LCD VCC pin to 5V
 * 10K resistor:
 * ends to +5V and ground
 * wiper to LCD VO pin (pin 3)

 Library originally added 18 Apr 2008
 by David A. Mellis
 library modified 5 Jul 2009
 by Limor Fried (http://www.ladyada.net)
 example added 9 Jul 2009
 by Tom Igoe
 modified 22 Nov 2010
 by Tom Igoe

 This example code is in the public domain.

 http://www.arduino.cc/en/Tutorial/LiquidCrystal
 */
#include <LiquidCrystal.h>

const byte pin8 = 8;

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
  Serial.begin(9600);      // open the serial port at 9600 bps:
  lcd.begin(16, 2);
  lcd.setCursor(0, 0);
  lcd.print("Welcome.");
}

void loop() {
  byte val = digitalRead(pin8);
  Serial.println(val);
  if(val == HIGH)
  {
    lcd.setCursor(0, 1);
    lcd.print("Switch on right.");
  }
  else
  {
    lcd.setCursor(0, 1);
    lcd.print("Switch on left.");
  }
}

The serial monitor and the output of the LCD screen are showing the slide switch to always be on the right side (not creating an open circuit when the switch is on the left side).

As seen in the picture, the switch is on the left. And the code, I think, is correct. So it should display, "Switch on left." This is because pin8 is low (not connected to 3.3V).
So I'm very confused. The switch appears to be shorting all three rails to which it's connected. When the switch is removed, that part becomes open; pin8 is low.

General idea not to leave your pin floating.
If I were you I would use a pull-down resistor (10K) from pin8 to GND.

Is there a way to make your circuit and code public? so we can try it?

As  Sener said, "use a pull-down resistor (10K) from pin8 to GND."

And in case anyone notices, yes, I'm aware of clear().

TinkerCAD must be assuming a floating input reads high instead of an intrinsically floating ground. The most simple solution is adding pinMode(pin8, INPUT_PULLUP); to the setup() function. Then, tie the opposite (than with a resistor) side of the switch to ground: Modified circuit TinkerCAD simulation.

Yes, it is also way to do but then you have to invert the switch function. Means, instead of going 3.3V it should be GND this time.


text:
Specific values not showing when using a numeric keypad
I have attached a 3x4 keypad to my Arduino Leonardo as an input method. Whenever I press the buttons, the majority of the keys work but specific ones don't. Here's my code, I've set it up to beep a piezo buzzer when it gets a keypress.
#include <Keypad.h>

int buzzerPin = 0;
const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns
char keys[ROWS][COLS] = {
    {'1','2','3'},
    {'4','5','6'},
    {'7','8','9'},
    {'*','0','#'}
};
byte rowPins[ROWS] = {12, 13, 8, 10}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {11, 7, 9}; //connect to the column pinouts of the keypad

Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);

void setup(){
    Serial.begin(9600);
    pinMode(buzzerPin, OUTPUT); //Set buzzerPin as output
    keypad.addEventListener(keypadEvent); //Add an event listener for the KeyPad
}

void loop(){
    char key = keypad.getKey();
}

void keypadEvent(KeypadEvent eKey) {
        // When the KeyPad will be pressed, the results will appear on the serial monitor.
        switch (keypad.getState()) {
        case PRESSED:
                Serial.print("Enter: ");
                Serial.println(eKey);
                beep(10);
                delay(10);
                break;
        }
}

void beep(unsigned char delayms) { //creating function
    tone(buzzerPin, 2000); //Setting pin to high
    delay(delayms); //Delaying
    noTone(buzzerPin); //Setting pin to LOW
    delay(delayms); //Delaying
}

I based my rows/columns off of this pin-out: https://www.jaycar.com.au/12-key-numeric-keypad/p/SP0770,
but I later found out some of the columns had to be swapped :P
Here's a diagram of what's happening:

The keys in red do not work.
I wouldn't have posted this on stack exchange but it looks like an oddly specific pattern, and no matter what I changed, it didn't work.
(And yes, that is the exact keypad I bought from Jaycar)
Edit: I forgot to mention that I was using a prototype shield to plug the keypad into, but all pins are confirmed working on that.

If either row #2 or column #2 is used it does not work, unless both are used. Have you exchanged/mixed row #2 and column #2 somehow? There must be some logic in it. Can you disconnect the keypad and test every button with a multimeter? Please tell which arduino pins are connected to which keypad pins.

One more question: is it a cheap clone board? Because row #2 is connected to pin 13. The official arduino leonardo has a extra logic chip, so pin 13 can be used as a input without problem. Try to use another pin for row #2. Update your question with the extra information.

Agree w/@Jot, row #2 is swapped w/column #2.  Try changing your code to read "byte rowPins[ROWS] = {12, 7, 8, 10}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {11, 13, 9}; //connect to the column pinouts of the keypad" to see if a code change can clear up the problem.

are you sure that 5 actually works?

Right so I've figured it out now (thanks to you guys), it turns out that yes in fact row 2 and column 2 were swapped around. I also forgot to mention that this was a prototype shield I was plugging the pins into, but thanks everyone for the quick and useful replies. In terms of marking this question as answered, I'm fairly new to this... Do I just quote one of you above in my answer button? Or do I requrie a moderator or something?

When @Jot sees this they will likely post their response as an answer and you can then select it as the answer.

A row against a row does not work, or a column against a colum.
That means there is a logical explanation. Row #2 is swapped with column #2.
Button 5 does work, because that still has a row against a column (but then the other way around).


text:
Connecting 2 arduino on same ground
I'm working project which consist of 2 arduino running a 2 different sketch, However, can i make these 2 ic to run on same power +ve and same ground?

Yes, I think you can connect both gnd and both 5v pins. Which arduino board is it? The voltage regulator might get damaged when a strong 5v is suddenly applied to the 5v pin. When using a power supply for one board, it might be safer to connect both Vin and both gnd. Always connect the grounds (gnd pins) when more than one arduino board is used in the same project.

Yes, you can. Just be sure, that you connect both Arduinos in parallel to the power source (both power inputs together to the power output of the source and both grounds together to the ground of the source), so that the current for the second Arduino won't flow through the first Arduino. Also use a power source, that is capable oft providing enough current for your needs.


text:
Using serial.available to return number of bytes
My code:
char data;
int numOfBytes;
void setup() {
    Serial.begin(9600);
}
void loop()
{
    if (Serial.available() > 0)
    {
        int numOfBytes = Serial.available();
        Serial.print("numOfBytes: ");
        Serial.println(numOfBytes);

        data=Serial.read();
        Serial.print("data: ");
        Serial.print(data);
        Serial.print("\n-----------\n");

        delay(500);
    }
}

I expected that this code returns 5 and then 4,3,2,1.
But it returned: 1,4,3,2,1
Why?

This is because at the first execution only one byte was received. The Serial interface does not send the data in one big packet of 5 bytes, only because you typed five bytes and started the transmission of all with one press in enter. It is sending the bytes one by one, in other words serial (hence the name). The exact transmission time is dependend on many factors (especially, when other technologies are involved, like the USB interface, when you are transmitting over the Arduinos USB to serial converter).
In this case the first byte is sent, followed by a short break, then the other bytes. The Arduino is fast enough in checking the Serial interface to sense this at 9600 baud.


text:
What is the output format of PINxn on atmega328p
I have written this simple code to run on my Arduino:
#ifndef F_CPU
#define F_CPU 16000000UL // 16 MHz clock speed
#endif

#include <avr/io.h>
#include <util/delay.h>

int main(void)
{
  Serial.begin(9600);
  DDRD = 0x00;
  PORTD = 0x80; //activate pull-up resistor on first pin on port D

  while (1)
  {
    Serial.print(PIND);
  }
  return 0;
}

I simply set my D port as an input and read the value in a loop. The output of PIND is 253. What is this number representing? is it in decimals? where can I see a list of these? How can I see a binary repression of the PIN output (8 bits of them). I don not want to use bit shifting.

FYI, I ran your code with my MEga2560 and I all get 11111111 constantly.
Maybe you should try another PORT block or even another Arduino.

I just tried PORTB and it's all 1's 111111, (side question, why is port B having only 6 bits?). So whats going on with PORTD here, broken board?

Serial.print(PIND, BIN); will write the value in PIND to the serial port in Base-2 representation.

so 253 is decimal then (11111101 in base 2). isn't it supposed to be 1000 0000 since only pin 1 is turned into input? what does this number mean

That depends on what you have connected to all the pins of PORTD. If only pin 7 has something connected, and the others do not have the pull-up enabled, they are floating and could be any value.

I just enabled the pull up on all PORD by PORTD = 0xFF; with nothing connected to them and it's still outputting 11111101

From the Atmega 323p datasheet: "Writing a logic one to PINxn toggles the value of PORTxn, independent on the value of DDRxn", which is probably not what you meant to do. To read the current state of register D, you need to read PORTD, or
Serial.print(PORTD);

in your example.
Update:

... what is PIND used for ...

PINx is called the Port x Input Pins Address and a note under it says "Writing to the pin register provides toggle functionality for IO" and refers us to the general pin-driver circuit schematic (Section 41.2 in my copy of the datasheet). That section tells us that "Writing a logic one to PINxn toggles the value of PORTxn, independent on the value of DDRxn." That is the only reference to this register I could find.
Note that the PORTx registers are bi-directional; the same register is used for reading or setting the states of the port's bits.

Also i'm not Writing a logic one to PINxn anywhere, i'm just reading
  it

The datasheet doesn't mention what is read from the port, at least nowhere that I found, despite that the PINx register is described as Read/Write, so your guess is as good as mine! ¯\_(ツ)_/¯
But to read a port's data, you need to read its PORTx register.
Update 2:

6 & 7map to the crystal pins and are not usable

They are usable. You can use them for I/O or for an external crystal, but not both. The "why?" is properly the domain of Atmel's engineers but I'll take a stab at it and say that many more functions could be put on the chip than there is space for physical pins on the package. Since pin count is at a premium, functions have to be doubled up on the same pins; you get to choose what you need. SPI, PWM, or I/O on DIP B2&3; Reset and I/O on C6; Timer-counter 1 input, I/O, & PWM on D5, for a few examples. Nearly every pin has several possible uses (power and grounds being the notable exceptions). For my uses, I dedicate the Crystal, Reset, and UART pins to those functions, but I could imagine systems that might need to reassign any of them.

then what is PIND used for in this case? what does 253 represent, why using PINB instead gives me the correct output of all being 1's and PORTD isn't.

Also i'm not Writing a logic one to PINxn anywhere, i'm just reading it

Quick question, why is Arduino port mapping to Atmel chip not a direct map. For example, on PORTB, 6 & 7map to the crystal pins and are not usable, why is that? what If I wanted to use them?

The Serial port is at pin 0 and 1.
PORTD is for pin 0,1,2,3,4,5,6,7. That's the problem, you mess with the pins of the Serial port.
Note: When a crystal/resonator/clock is used, those pins are disconnected from PORTB. That means you may use PORTB and read and write 8 bits to it, the crystal will keep on running.

So basically I shouldn't use PORTD for inputs to be safe?

Quick question, why is Arduino port mapping to Atmel chip not a direct map. For example, on PORTB, 16 & 7map to the crystal pins and are not usable`, why is that? what If I wanted to use them?

After calling Serial.begin don't change any of those two bits in the registers. You can use the other six bits. The functionality of each pin is fixed. When using a crystal, you can no longer use those same pins for something else, since they are connected to the crystal. I'm not sure if I understand your question.

question is, atmega328p has 8 bits in port B. but Arduino has 6 (2 port are reserved for something else), why is that?

Portb.6 and Portb.7 are pins for the crystal. When no crystal is used, they can be normal digital pins. The atmega chip can not assign a function to an other pin. The serial port, the crystal, the i2c bus, the analog inputs, everything is fixed to certain pins. A single pin can however act as a number of different things.

byte valueB = PINB; // reads the value of portB, D14-D19, into the variable valueB

If you then
Serial.print (valueB,BIN);

you will see the value of D19 to D14 in binary, or 0s & 1s. I don't think leading zero's are shown, so that can be a little confusing.
Serial.print (valueB);

will show the same value in decimal.
253 = 0b11111101   0b indicates base 2 (binary) format.  0x is used fof hexidecimal format (0x00 to 0xFF for 0 to 255).
If you are using the IDE and have not changed the fuses from the Uno/Nano board type, the IDE is expecting a crystal or resonator on PB7 & PB6, so reading them will return a nonsense result, so you might as well mask them off before printing.
valueB = valueB & 0b00111111;

If the other pins do not have their internal pullup resistors turned on, or external pullup or pulldown resistors are not used, the pins are 'floating' and their low input current means that any external charge can easily change their reading - so valueB = PINB; will have erratic results.
If a port has been set to outputs, then all pins can be written to at once:
PORTB = 0b0011111111;  // set D19 to D14 high for example


text:
Can I use a camera sensor from a not functioning smartphone in Arduino or Raspberry pi?
I want to use the OmniVision_OV16860 camera sensor from a not functioning Moto G4 plus phone to capture pictures using Arduino or Raspberry Pi.
Is it possible to do that? If yes, explain the whole process.

For your RPi questions, there is a RPi stackexchange website.

remove the camera from the phone .... 2) obtain the data sheet for the camera .... 3) build a connector adapter so that you can plug the camera into a breadboard .... 4) write necessary software to "talk" to the camera

no, no arduino supports MIPI interfaces, so you have no way to hook it up, and even if you could, there's nowhere near enough ram on an ardunio to store a single image, and there's no way to chuck image data from the camera, so it's simply impossible.

Is it possible to ... use the OmniVision_OV16860 camera sensor (on an)
  Arduino?

It is doubtful as bare image sensors usually require specialized software drivers to be of any use. Also, a common Arduino does not have the power to do image processing.  Only the few Arduino's built with unusually powerful processors could handle image processing.  But, at this level, expect little support as most do not do image processing on the Arduino platform.

Thanks for the answer :) Can you suggest some idea to use this camera  sensor  because the phone is not functioning and i am searching for some cheap and working method to use that camera except of using the sensor in other phone

If only the cell radio portion of the phone does not work, the easiest way to use the camera is to use it in the Android device.  Here is a RPi stackexchange question / answer where this is discussed.  I have several dead phones and have opted to purchase the cameras specifically intended for the RPi. Again, the powerful features needed to transfer images are not available on common Arduino platforms.


text:
GPS Logger problem
I have some problems with my GPS Logger. U use Arduino Uno, NEO - 6M, SD card.
Problem is in function void loop. I enter inside, but stuck on the "while loop", don't even get inside this loop. Here is code I use:
#include <SoftwareSerial.h>
#include <TinyGPS.h>
#include <SPI.h>
#include <SD.h>

#define SD_CS 4
#define FILE_BASE_NAME "Trac"

TinyGPS gps;
SoftwareSerial serial(10, 11);

File myFile;

const uint8_t BASE_NAME_SIZE = sizeof(FILE_BASE_NAME) - 1;
char fileName[] = FILE_BASE_NAME "00.csv";

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

  Serial.println("SD card initialization...");
  if(!SD.begin(SD_CS))
  {
    Serial.println("Failed! Check card");
    //while(1);
  }
  Serial.println("Initialization done");

  while (SD.exists(fileName)){
    if (fileName[BASE_NAME_SIZE + 1] != '9')
    {
      fileName[BASE_NAME_SIZE + 1]++;
    }
    else if (fileName[BASE_NAME_SIZE] != '9')
    {
      fileName[BASE_NAME_SIZE + 1] = '0';
      fileName[BASE_NAME_SIZE]++;
    }
    else{
      Serial.println("Can't create file name");
      //return;
    }
  }

  myFile = SD.open(fileName, FILE_WRITE);
  if (!myFile) {
    Serial.println("open failed");
    //return;
  }
  Serial.print("opened: ");
  Serial.println(fileName);
}

void loop(){
  while (serial.available())
  {
    int c = serial.read();
    if (gps.encode(c))
    {
      long lat, lon;
      unsigned long fix_age;
      gps.get_position(&lat, &lon, &fix_age);
      Serial.print("Latitude:");Serial.println(lat);
      Serial.print("Longitude:");Serial.println(lon);
      myFile = SD.open(fileName, FILE_WRITE);
      myFile.print(lat);
      myFile.print(", ");
      myFile.print(lon);
      myFile.println("");
      myFile.close();
    }
  }
}

If I use this code, it gives me the lat ad lon:
#include <SoftwareSerial.h>
#include <TinyGPS.h>

TinyGPS gps;
SoftwareSerial nss(10, 11);

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

void loop()
{
  while (nss.available())
  {
    int c = nss.read();
    if (gps.encode(c))
    {
      long lat, lon;
      unsigned long fix_age;
      gps.get_position(&lat, &lon, &fix_age);

      Serial.print("Szerokosc:");Serial.println(lat);
      Serial.print("Dlugosc:");Serial.println(lon);

    }
  }
}

you need to describe the observed results .... you made no mention if anything actually prints in the serial monitor

Yes sorry, the observed results:
-code with GPS only is print location on serial monitor, so GPS works fine
-code with GPS and SD card only show inforation about file create and stop

SD uses SPI. On the Uno, SPI is on pins 10-13. You are also using pins 10 and 11 for software serial. That won't work. You need to use pins other than 10 and 11 for software serial.

Owww that was so simple, and stupid mistake for me. You saved my life! Thanks so much.
First I changed the pins of serial to 8 and 9, it's not work, but when I change to 5 and 6 it works perfectly. Once again thanks! :)


text:
Install Arduino IDE in Raspberry Pi 3 model B
I am trying to install Arduino IDE in my Raspberry Pi model 3 but it is unable to locate file path.
I use the following steps
sudo apt-get update && sudo apt-get install arduino

and in result I found this
pi@raspberrypi:~ $ sudo apt-get update && sudo apt-get install arduino
Hit:1 http://archive.raspberrypi.org/debian stretch InRelease
Ign:2 http://repository.pi4j.com wheezy InRelease
Hit:3 http://repository.pi4j.com wheezy Release
Reading package lists... Done
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package arduino

I am searching for a solution but not able to understand what's the problem here.
Any ideas to make it work will be helpful.

Have you tried grabbing the Linux ARM build directly from https://www.arduino.cc/en/Main/Software and installing it? Have you tried searching for the package name? apt-cache search arduino

Downloading the latest version from the arduino.cc is much better idea. If there is Arduino IDE available in the repository, it's usually super obsolete. For example version in Ubuntu repositories is 1.0.5.

Visit https://www.arduino.cc/en/Main/Software in your browser, and click the Linux ARM link under ‘Download the IDE’.
cd Downloads/
tar -xf arduino-1.8.3-linuxarm.tar.xz

Extract the file to your /opt directory, then open a Terminal and run the install.sh script to install.
sudo mv arduino-1.8.3 /opt
sudo /opt/arduino-1.8.3/install.sh

You will find Arduino IDE under Menu > Programming. Open the app to start programming your Arduino board.
Hope this helps.

worked for me! In the Arduino website you'll find two versions (32-bits and 64-bits). In my case (and it seems in the case of this example) the 32-bits worked fine. I'm using a Raspberry Pi 3B with an Arm v7.


text:
How to connect an Elegoo Nano to a Raspberry Pi and program it?
I own an several Elegoo Nanos and a Raspberry Pi. I would like to connect an Elegoo Nano to the Pi and upload nanpy onto the board and control it's GPIO pins.
I have plugged the nano into the Pi and it is not recognised by the pi. I believe it is something to do with the drivers required for the nano to work. I feel this is similar to this post Arduino Nano not visible in Serial Ports (Mac OS) as I have tried and failed at connecting it to my Mac.
Any help at getting the Elegoo Nano read by the Arduino IDE on my Raspberry Pi so I can program onto it would be greatly appreciated.

Have you gone through the basic Linux troubleshooting steps?

Assuming you are familiar with the Linux OS:  Try "lsusb" or "sudo lsusb" before and after you plug in the USB device.  Note the difference and the user and manufacture ID values.  Google them to see if you have an FTDI chip or something else.  Also, see if the OS mounted your USB device in the device directory. Type "ls /dev/" before and after you plug in your USB device.  Another thought, check the permissions and group of the new device entry if there is one. It's unlikely the RPi distro of Linux is setup incorrectly, but make sure you have permissions to read/write the device.

BTW, a modern MAC is also a Unix (like) computer (the Linux OS on a RPi can be though of as a derivative of Unix).  You can open a MAC console and type the same commands as you type into the RPi above.  However, I'm not sure where the MAC's device directory (the "ls /dev" command above) is.

I think you need to install the Nano USB driver first.

The Elegoo website has a downloads page which contains the drivers.

Using the Raspberry Pi, download the zip file containing the drivers.
Unzip the contents to a location of your choice. (Also see here)
Change to the directory containing the Linux driver source files (ie CH341SER_LINUX).
In the terminal type make. Let it compile the driver.
In the terminal type make load.

Done

thanks for that link. I seem to have some problems installing the drivers.
With the following stack trace
pi@raspberrypi:~/Downloads/Elegoo CH340 Driver 2018.6.19/CH341SER_LINUX $ make
make -C /lib/modules/4.14.30-v7+/build  M=/home/pi/Downloads/Elegoo CH340 Driver 2018.6.19/CH341SER_LINUX
make[1]: *** /lib/modules/4.14.30-v7+/build: No such file or directory.  Stop.
Makefile:5: recipe for target 'default' failed
make: *** [default] Error 2

@apollowebdesigns For that error It can't find the /lib/modules/4.14.30-v7+/build directory specified in the Makefile. You may have to unzip the files to a specific location in your file system and compile them there. I think this is a question best asked on the [raspberrypi.se] or [unix.se] sites. If you get an answer, let us know and I'll update the answer.

Does this help? https://askubuntu.com/q/554624 although the build name will be different. You will need to type something like sudo apt-get install linux-headers-`uname -r`

thanks for your help. For raspberry pi, I did a fresh install of the OS and now it can detect it all and for the Mac I used brew. Thanks for your help. I'll give you the point!


text:
Using Modbus TCP server on Arduino
I have a scd30 sensor wired to an Arduino Uno. The scd30 works on the I2C protocol. I am able to read data live on the serial monitor on the Arduino IDE. I have an ethernet shield on my Arduino. I would like the Arduino to communicate with a field agent which will upload the data to the internet.
I have tried numerous modbus TCP libraries and dont seem to be getting anywhere. I can connect my arduino to the field agent but whenever it sends data I get a 0x02 exception code - Illegal data address. This is the library I'm using https://github.com/andresarmento/modbus-arduino/tree/master/libraries/ModbusIP/examples
I believe the right way to go about it is through holding registers but im not sure how to do this when using I2C. The connection is fine, the problem is the format. Any help is appreciated thanks.
/*
  Reading CO2, humidity and temperature from the SCD30
  This example prints the current CO2 level, relative humidity, and temperature in C.
*/
#include <SPI.h>
#include <Ethernet.h>
#include <Modbus.h>
#include <ModbusIP.h>
#include <Wire.h>
#include <Streaming.h>
#include "SparkFun_SCD30_Arduino_Library.h"

SCD30 airSensor;
//Modbus Registers Offsets (0-9999)
const int SENSOR_ISTS = 100;
//ModbusIP object
ModbusIP mb;
long ts;

void setup()
{
  Wire.begin();
  Serial.begin(9600);
  Serial.println("SCD30 Example");

 // The media access control (ethernet hardware) address for the shield
    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
    // The IP address for the shield
    byte ip[] = { 000 , 00,0, 00  };
    byte gateway[] = { 0, 0, 0, 0 };
    byte subnet[] = { 255, 255, 255, 0 };
    //Config Modbus IP
    mb.config(mac, ip,gateway,subnet);
    // Add SWITCH_ISTS register - Use addIsts() for digital inputs
    mb.addHreg(SENSOR_ISTS);
  airSensor.begin(); //This will cause readings to occur every two seconds

}

void loop()
{

mb.task();
   mb.Hreg(SENSOR_ISTS, digitalRead(airSensor.getTemperature()));

}

Don't cross post. You already asked this on SO.

The ModbusIP library expects from you that you supply the value of the register. The AirSensor library gives you that value.
Set the register value to Hreg:
mb.Hreg(SENSOR_ISTS, airSensor.getTemperature());

I tested your sketch without the sensor library and it is working. Client was my java test client I use to test access to Modbus TCP registers of my photovoltaic system.
Make sure that the client calls "0x03 - Read Holding Registers" and test address 100 and 101 because some modbus clients offsets are 1-based.

It doesnt seem to work. The code compiles well but I dont think it actually stores them. Do you know of any other libraries that can store in registers to modbus tcp?

and how do you reed it? what is your Modbus TCP client?

Its a field agent that does this. The field agent reads the registers of the arduino or should read it if the arduino is configured properly

what software is used by field agent? some modbus clients offsets are 1-based, so a register configured as 100 in library should be 101 in this software.https://github.com/andresarmento/modbus-arduino/blob/master/README.md

its a modbus slave. dont know the exact software. Tried changing it to 101 and still get the same error. ILLEGAL DATA ADDRESS

and it is configured to call "0x03 - Read Holding Registers"?

im not sure how to do this

You could try "0x04 - Read Input Registers" with Ireg.