text:
Connecting E-paper display (GD) to Arduino?
I'm still learning how to use Arduino and electrical components, but I will try my best to understand any answers!
So I just bought an e-paper display off a website, not from the manufacturer itself (http://www.good-display.com/products_detail/productId=305.html). The product is a 1.54 inch E-paper display 200x200 partial update GDEP015OC1.

I was a bit puzzled by how to connect the display to the Arduino Uno. Turns out that to connect the display to a board, it needs a breakout board (is this the correct term?). I could buy it online from the manufacturer, however, it will take me at least a month and the shipping cost is too high.
I was wondering if it is possible for me to make my own breakout board? Is there any 'general' breakout board for an e-paper display, or does it have any special from the manufacturer? If it is possible, how difficult would it be for a beginner who has almost no knowledge on circuit building/electrical components?
The aim is just to display an image onto the e-ink display.
Thanks!
edit: I bought the mentioned display because of the size. I was afraid of not knowing how to connect the mention display (which is where I am now), so I bought this e-ink display also: https://www.smart-prototyping.com/E-ink-E-paper-Display-module-3.3V-2.04-inch-177x72.html I was thinking to take the 60mmx30mm display off the board and try connecting the 30mmx30mm display to the 'breakout board' if I am unable to build my own board. Both seemed to have the same pin number (need to confirm later).

Hi and welcom to the Arduino SE community. This question is not directly about Arduino. Please take the tour and read the on topic and don't ask help pages.

This is the E-Ink / Paper display device integrated by the image display technology of Microencapsulated Electrophoretic Display (MED). This device has an approach to create a tiny spheres in which the charge color pigments are suspending the transparent electrode. Wiring to your microcontroller Follow this link 1.52 Inch Epaper Wiring E-Ink/E-Paper with Microcontroller

E-ink displays require high voltages to operate them. They are electrostatic devices and the pixels need charging up to a high voltage (high compared to what an Arduino runs at) to attract the pigment powder (basically the same as laser printer toner) to create an image.
While it is possible to make your own board it's not something that is simple and straight forward. Designing boost converters requires a certain base level of knowledge and expertise to get it right. Not something I would recommend a beginner attempting.
Even though a display may have the same pin number as another it doesn't follow that the pins are in the same order on the connector. There is no standard and each display from different manufacturers (and even different displays from the same manufacturer) will have a different pin-out. You will need to compare the datasheets for the two displays to see if the pin-out is the same and if it isn't you would have to somehow map from one to the other on the driver board.
The simplest option is to just order the correct driver board for that display.
(Note: in this context it is called a driver board not a breakout board. A breakout board is typically a passive circuit board that converts from one hard-to-use connector or footprint to a simpler, say 0.1", header. A driver board contains active electronics, in this case a boost converter, to drive the device it is connected to.)


text:
Adding an LCD to Uno but not enough pins left
I am an absolute beginner and wanted to build a simple home automation system using DTMF module using this guide. My problem is out of 12 pins most of them are getting used in DTMF module(5) and the relay module(4). So how do i add an LCD display to it?

What DTMF module? What relay? What you want to control? Lights? Heaters? How do you want to interact with your project? Keypad? Android app?

Use an I2C LCD adapter. Requires only I2C pins (A4 and A5).

Congrats! But it's better to start with simpler projects to develop your skills and test the components for your final project. For example, you need to know the difference between electromechanical relays and SSR, because what works in theory not always works in practice.

Get a bigger board with more IO...?

I was going to say use an I2C backpack, but since @MikaelPatel got there before me I'll go with use an I2C GPIO Expander like a MCP23017 which will give you an 16 GPIO ports.

Do you know you can use the Analog pins as Digital pins, so there are another 6 there?

You are using 8 GPIO pins for your existing modules. That leaves 12 left for an LCD (assuming you aren't using the serial port).
An LCD can work from as few as 6 pins (4 data, E and RS) - WR can be tied LOW and RESET can be tied HIGH, and the remaining 4 data pins left floating (or tied low).
That still leaves you 6 pins to do other things. Or 4 if you (advisedly) steer clear of using pins 0/1 for anything.

I suggest you first try every component separately (or if you are new to Arduino, try first simpler components like LEDs, switches etc),
As told by others the following components are easier to use:

Use a matrix keypad, see for example keypad. To reduce the number of pins you can use a multiplexer, such as 74HC165. 74HC165 are very cheap, although they need some additional programming and are slower than using direct pins (although for a keypad you will not notice).
Use a display like 1602 or 2004. See example at 1602 Display. Make sure you order one that has an I2C adapter attached to it (or solder it yourself if you feel comfortable).
After you tested all components separately (make different sketches and save them in case you need them later), you can combine them.

You can use arduino mega rather than uno or nano .... Or can use **I2C adapter to control your LCD display, I2C adapter only needs two pins to communicate with arduino and is easy to use ......
**

You have chosen a mighty task as your first project. I suggest that you run through as many of the example programs as possible before undertaking your project.
Firstly, I would recommend a matrix keypad instead of the DTMF keypad as it is much easier to use with an Arduino. This will also allow you to use a multiplexer which would use fewer pins.

I2C allows you to communicate to the LCD with only 2 pins. Here is such a I2C LCD (with buttons) sold by Adafruit.

As well as the tutorial over at Adafruit, there is a tutorial on such a topic over at ArduinoInfo.
Alternatively, you could upgrade to a Arduino Mega which has 54 IO pins as apposed to 14 on the Arduino Uno.

If some of the pins aren't used at the same time there are ways to reuse them.
Otherwise use a serial shifter or o.o expanders to drive the LCD. 2 to 3 pins max. Even 1 pin is possible if you tolerate lower speed of update.

source: Stack Exchange

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

sort: votes


text:
Purpose of extra pin slots on Pololu DRV8835
I have a Pololu DRV8835 motor controller. I managed to properly solder and connect it and it actually works, however I've been wondering about the purpose of the extra pin slots - especially the ones without pins headers soldered to them on the right side of the picture below, but also the ones marked A and B (I assume these ones are an alternative way to connect to motors, though). I wasn't able to find anything about them, so I assumed that it may be obvious to someone who is not a complete beginner (like me). What, if anything, could I use them for if I soldered pin headers there?

A and B are the same as the A and B screw terminals.
The pins on the right, if you use your eyes and follow the traces, are the same as the pins that plug into the Arduino. I guess they are intended to be used to isolate the existing pin assignments (cut tracks on the underside between adjacent holes with a knife) and solder wires to other pins so you aren't limited to just using the pins they have assigned.

Thanks! What about the five pins next to the five you explained (the ones separated by white lines)?

They are all the same. Turn the board over and look at the traces. You can see they are joined. You can cut those traces that join them if you want to wire it to other pins on the Arduino instead, then when you want to undo it you can solder a wire between the holes to replace the track you cut.

The A and B through-holes are intended to let you connect the two motor channels together in parallel (M1A to M2A and M1B and M2B) to drive a single higher-current motor. See the section "Configuring the board for single-channel mode (parallel outputs)" on the product page (https://www.pololu.com/product/2511); there is a lot of other usage information there too.

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


text:
Solution for simple multi-Arduino communication network (or alternative?)
I know similar question has already been discussed here but I could not get clear answer.
Here is the thing: I have one master device - Mega2560, and multiple (about 9 but could be expandedin future) I2C perfiferals - displays, that can have one of two possible I2C IDs - limitation by the manufacturer. As I can't connect and talk to them from a single I2C bus I chose to attach each two of them to a Mini-Pro's I2C pins and connect the 5 Mini-Pros to the master. The question is am I going to the right direction, and which connection would do the trick? I2C is obviously out of question, so the remaining are UART and SPI. UART would require some external hardware to cope with multiple outputs from the slaves, SPI would require additional pins from the master for chip select signal.
Data rates are not high - min 10-20 kbps.
I think the SPI offers better solution, but I'm no expert, what do you think?
Cheers!
Stefan

What distances are you wanting to communicate over?

very short - the modules are within 40cm of each other, actually they will be combined in a common box with single front panel.

SPI afaik is not good over bigger distances (> 1 meter). If you need many CS signals you always can use a multiplexer (like 74HC595N). I am not sure if it is 'normal' to have many SPI devices connected to one Arduino though.
Other solutions: I2C, but I don't have much experience with them. I heard about I2C expanders (MCP23017) that maybe are useful.
Also RF might be a possibility, also depending on the distance and most important speed (and latency).
In case for the Mega, it has 4 UARTs so that could maybe be used to spread the load.

I2C is not better over long distances. It is not designed even really to go through wires but be just between chips on a PCB.

@Majenko ... I removed the part about distance, thanks.

I would use i2c to drive them but unfortunately the OLED displays have hardcoded duplicated IDs I cannot connect them to a common i2c bus.

Thanks all for your answers.
I did some more research with the new info you provided and found my perfect solution: TCA9548A. That's a 1-to-8 port i2c multiplexer that will allow the master MEGA2560 to control up to 8 independent i2c buses, where I can connect my displays. The chip is dirt cheap here - 2 euro only, and it is available in the store.
Thanks again guys!

Please add this as comment or update to your question. Since it is not an answer, I had to flag it like that.

@MichelKeijzers For the distances involved I was going to suggest an I2C switch as one possible solution. This answer is an answer to the question - and there is nothing wrong with a user answering their own question.

@Majenko ... true ... I see it adds more than only a thank you. I retracted my flag (even upvoted it).

I would suggest using 485 communication though it will increase the hardware but you will be able to add upto 32 devices and also have greater communication distance.
You can use MAX485 IC or you can directly use TTL to 485 Module


text:
ESP8266 - UDP send interruptions
I'm trying to transfer data from ESP8266(NodeMCU ESP12E) to my laptop. I'm coding ESP using Arduino IDE. I am able to receive correct packets (each containing 400 bytes) on a visual basic console program. However, to see whether the transmission is continuous or not, I have toggled an output pin whenever UDP.endpacket() returns 1. I observed waveforms on DSO. I found that UDP.endpacket() does NOT return 1 many times and the there is no transmission from ESP for a significant amount of time (milliseconds). Refer attached waveforms.
Why does UDP.endpacket() return 0 for such long time? Why is UDP transmission getting interrupted? How can I solve this? Please feel free to ask for more details if necessary.
Code :
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>

const char* ssid = "Connectify-me33";
const char* password = "donfour276";

WiFiUDP Udp;
unsigned int localUdpPort = 65000;

unsigned int dest_port = 11000;

unsigned char clientBuf[400];
int clientBuf_len=0;

#define test_pin 5

int return_udp_fcn = 0;

void setup()
{

  WiFi.begin(ssid, password);
  delay(5000);

  Udp.begin(localUdpPort);

  pinMode(test_pin, OUTPUT);
  digitalWrite(test_pin, HIGH);

  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);
  delay(1000);
  digitalWrite(LED_BUILTIN, HIGH);
  delay(1000);
  digitalWrite(LED_BUILTIN, LOW);
  delay(1000);
  digitalWrite(LED_BUILTIN, HIGH);
  delay(1000);

}

void loop()
{
        digitalWrite(test_pin, HIGH);

        //filling up buffer
        for(clientBuf_len = 0; clientBuf_len<=399; clientBuf_len++)
        {
            clientBuf[clientBuf_len] = 0x7E;
        }

        //UDP transmit
        Udp.beginPacket("172.22.0.1", dest_port);
        Udp.write((const uint8_t *)clientBuf, 400);
        return_udp_fcn = 0;
        return_udp_fcn = Udp.endPacket();
        if(return_udp_fcn){
          digitalWrite(test_pin, LOW);
        }
        delayMicroseconds(100);

}

I think you need a delay(1); after your call to write().
There is/was a bug where the underlying buffer files up and can't get time to clear.  It looks like it will require a change to the ESP8266 firmware from the manufacturers before it will get fixed properly.
See what you think:
https://github.com/esp8266/Arduino/issues/1696
https://github.com/esp8266/Arduino/issues/2285

Thank you for your quick response. I tried again with a delay after write. I got the same results. I also tried with multiple delays after each line in the code. The problem still persists.


text:
arduino send logged data over wifi
I am working on air quality measuring project. it should be able to record gps and air quality data into a SD card and then when wifi is available it should send it to a server. Please help me decide the required hardware for this.
Can i use ESP8266 module to send this data

You need:

SD card + reader
GPS module
Air sensor
WIFI ESP 8266 should be ok
Arduino Uno or Mega, depending on if everything fits and calculations to be performed

Start with finding each component, read examples how to use them, than combine them.
Looks like a big project to start with if you are new to Arduino.

will i be able to send the data when ever a wifi is detected and while the data is being logged ?

@Yomal If you program it to do that, sure.


text:
Pin 9 and 10 with different duty cycles
I want to control the contrast and backlight of an HD44780 LCD display with two PWM signals. I would like to use PB1 and PB2 (Pin 9 and Pin 10) for this.
As far as my research goes, timer1 is responsible for the two pins.
OCR1A and OCR1B are responsible for the pulse length.
With the code below I get a frequency of 7.823 kHz and a duty cycle of 88%. But it works only on PB1. PB2 is still constant 0V. I am using the AtmelStudio, therefore I don't have access to functions like pinMode(10, Output)
How can I have different duty cycles on pin 9 and 10?
#define F_CPU 16000000UL
#include <avr/io.h>

int main(void)
{
    DDRB |= (1 << DDB1) | (1 << DDB2);
    OCR1A = 900;
    OCR1B = 400;
    TCCR1A |= (1 << COM1A1);
    TCCR1A |= (1 << WGM11) | (1 << WGM10);
    TCCR1B = (TCCR1B & 0b11111000) | (1 << CS10);

}

You can't control the contrast with PWM unless you filter it properly to provide the correct voltage. Personally I use a digipot for contrast.

I want to use PB1 for backlight and PB2 for contrast. analogWrite() is not inside AtmelStudio.

Maybe you should use the Arduino IDE with your Arduino. Or copy and paste the Arduino source code into your project.

As far as I have been able to test it. It will work. I might add a circuit to filter it but that's down the line.

Without a filter you will get flicker as it switches rapidly between full contrast and zero contrast.

Thanks for the info. I will add one once I get the source code working.

Start by examining the Arduino source code. That works, so why not use it as a basis?

After trying  a lot of things i got it working.
And even the contrast is working directly on the pwm signal.
#define F_CPU 16000000UL
#include <avr/io.h>
void main(void){
    DDRB = 0x06;
    OCR1A = 200; //Duty cycle for PB1 ~80%
    OCR1B = 100; //Duty cycle for PB2 ~40%
    TCCR1A = 0; //Set TCCR1A to zero. We will configure it manually
    TCCR1A |= (1 << COM1A1) | (0 << COM1A0) | ( 0 << COM1B0) | (1 << COM1B1);
    TCCR1A |= (0 << WGM12) | (0 << WGM11) | (1 << WGM10);
    TCCR1B = 0; //Set TCCR1B to zero. We will configure it manually
    TCCR1B |= (0 << CS12) | (0 << CS11) | (1 << CS10);
    while(1){

    }
}


text:
Gate opener code help - should be working
Can anyone see any errors in my code that would affect the opening command? Upon first power up the open command (remoteA) works fine.
After that the opening command does what its supposed to except it only momentarily fires "digitalWrite (power, LOW)" command.  It should be set LOW for the same amount of time as "digitalWrite (openGate, LOW)", but it doesnt.
Strange thing is, the close command code is almost identical and it always works as it should, no problems.
Any suggestions? (hopefully the code pastes in here ok, its acting weird)
/*
 *  Swing Gate Opener with 2Ch remote, gate lock, motor, buzzer, amp monitor
and two independent limit switches
 *
 *  By Darren Clarke
 *
 */
int current = A0;  // monitor motor current
int buzzer = 3;  // operation buzzer
int power = 5;  // 24v power on/off
int remoteOpen = 6;  // remote button A to digital pin 6
int remoteClose = 7;  // remote button B to digital pin 7
int openGate = 8;  // open gate to motor on digital pin 8
int closeGate = 9;  // close gate to motor on digital pin 9
int gateLock = 10;  // gate lock connected to digital pin 10

// variables
int openRelay = 0;  // variable to store the motor direction
int closeRelay = 0;  // variable for previous motor direction
int remoteA = 0;  // variable for remote A condition
int remoteB = 0;  // variable for remote B condition
int lock = 0;  // varialbe for gate lock
int mA = 0;  // variable for motor current
unsigned long previousMillisA = 0;
unsigned long previousMillisB = 0;
unsigned long currentMillisA = 0;
unsigned long currentMillisB = 0;

void setup() {
    // put your setup code here, to run once:
    pinMode(buzzer, OUTPUT);   // sets the digital pin 4 as output
    pinMode(power, OUTPUT);   // sets the digital pin 5 as output
    pinMode(remoteOpen, INPUT);   // sets the digital pin 6 as input
    pinMode(remoteClose, INPUT);   // sets the digital pin 7 as input
    pinMode(openGate, OUTPUT);   // sets the digital pin 8 as output
    pinMode(closeGate, OUTPUT);   // sets the digital pin 9 as output
    pinMode(gateLock, OUTPUT);   // sets the digital pin 10 as output
    digitalWrite(closeGate, HIGH);   // sets relay to open
    digitalWrite(openGate, HIGH);   // sets relay to open
    digitalWrite(power, HIGH);   // sets relay to open
    digitalWrite(gateLock, HIGH);   // sets relay to open
    analogWrite(buzzer, 0);   // sets buzzer off
    Serial.begin(9600);
}

void loop() {
    // put your main code here, to run repeatedly:
    remoteA = digitalRead(remoteOpen);   // read remote A input
    remoteB = digitalRead(remoteClose);   // read remote B input
    openRelay = digitalRead(openGate);   // read state of openGate
    closeRelay = digitalRead(closeGate);   // read state of closeGate
    lock = digitalRead(gateLock);   // read state of gate lock
    mA = analogRead(current);   // read value of motor current
    currentMillisA = millis();
    currentMillisB = millis();
    Serial.print("aIn ");
    Serial.print(remoteA);
    Serial.print(", bIn ");
    Serial.print(remoteB);
    Serial.print(", Open ");
    Serial.print(openRelay);
    Serial.print(", Close ");
    Serial.print(closeRelay);
    Serial.print(", Lock ");
    Serial.print(lock);
    Serial.print(", mA ");
    Serial.print(mA);
    Serial.print(", cur ");
    Serial.print(currentMillisA);
    Serial.print(", prev ");
    Serial.print(previousMillisA);
    Serial.println(" ");

// to open the gate
    if ((remoteA == HIGH) && (remoteB == LOW)) {
        delay(500);   // time for gate direction reversal
        digitalWrite(power, HIGH);   // stops previous movement
        digitalWrite(closeGate, HIGH);   // Stop gate open command
        analogWrite(buzzer, 100);   // starts buzzer
        digitalWrite(gateLock, LOW);   // energize lock open (unlock state)
        delay(500);   // time for lock to open
        digitalWrite(openGate, LOW);   // actuate gate open
        digitalWrite(power, LOW);   //  supplies 24v power
        previousMillisA = millis();  // set time references
        currentMillisA = millis();  // set time references
    }

// to stop open command
    if ((closeRelay == HIGH) && (currentMillisA - previousMillisA) >= 6000) {
        digitalWrite(gateLock, HIGH);   // denergize lock (locked state)
        digitalWrite(openGate, HIGH);   // stop open relay to motor after open
        digitalWrite(power, HIGH);   // remove 24v power
        analogWrite(buzzer, 0);
    }

// to close the gate
    if ((remoteB == HIGH) && (remoteA == LOW)) {
        delay(500);   // time for gate direction reversal
        digitalWrite(power, HIGH);   // stops previous movement
        digitalWrite(gateLock, HIGH);   // de-energize lock on quick reverse
        digitalWrite(openGate, HIGH);   // Stop gate close command
        analogWrite(buzzer, 100);   // starts buzzer
        digitalWrite(closeGate, LOW);   // actuate gate close
        digitalWrite(power, LOW);   // supplies 24v power
        previousMillisB = millis();  // set time references
        currentMillisB = millis();  // set time references
    }

// to stop close command
    if ((openRelay == HIGH) && (currentMillisB - previousMillisB) >= 6000) {
        digitalWrite(closeGate, HIGH);   // stop close relay to motor
        digitalWrite(power, HIGH);   // remove 24v power
        analogWrite(buzzer, 0);
    }

    delay(100);
}

Ok, i figured it out.
Thanks all for your help.
It only happens on the A channel because its first in the series of the code.  The turn off command after the timer isnt specific enough.  The if conditions are met on the B channel so it keeps turning the power off immediately.
I just need be more specific in my if command or make another tweek.
Thanks guys,  your suggestions caused me to do much more digging and code adjustments.
Its working like a peach now.
Thanks.

Accept your answer to close the question.


text:
Arduino Mega PWM doesn't work in C Code
Why such horrible Arduino's Mega PWM doesn't work??
Below is my code.
I try to set Fast PWM 8-bit to dim and light up a LED connected to OCR1A Pin. I try to do it in C language, completelly without Arduino's lbraries and it doesn't work at all.
I'm working with documentation and the code seems me to be correct. Almost the same code worked on ATmega8 and ATmega16 (obviously, with special setting for those special ATmegas) but this one doesn't.
The comments in this code point out, that I tried to use few other flags to  check if it work with some of another settings.
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>

//Anode of LED connected to OCR1A (digital pin 11)
#define LED (1<<PB5)

int main()
{
  DDRB |= (1 << LED);

  //FAST PWM 8-bit, set OCR1A at the Bottom
  TCCR1A = (1 << COM1A1) | (1 << WGM10);    // | (1<<WGM11) | (1<<COM1A0)
  //Prescaler :1024
  TCCR1B = (1 << CS12) | (1 << WGM12);     //| (1<<WGM13); //Presc :1024  (1<<CS10) |
  //Enable to interrupt Compare Match A
  TIMSK1 = (1 << OCIE1A);

  uint8_t i;

  sei();

  while (1)
  {
    for (i = 0; i < 255; i++)
    {
      OCR1A = i;
      // _delay_ms(5);
    }

    for (i = 255; i > 0; i--)
    {
      OCR1A = i;
      //_delay_ms(5);
    }
  }
}

}

In what way does it "not work"?

The program has been compiled and send to Arduino board (via Arduino IDE) but the LED, which should be  dimmed and lighted up doesn't work.

I'm not sure this is right:
#define LED (1<<PB5)

Since later on you use:
DDRB |= (1<<LED);

That would expand out to:
DDRB |= (1<<(1<<PB5));

That would equate to:
DDRB |= (1<<(1<<5));

Take it a step further:
DDRB |= (1 << 32)

Shifting 1 to the left 32 times on an 8 bit register results in:
DDRB |= 0;

Which of course does nothing.
I can't comment on the rest of the code, other than to say "without delays in your loops you won't get much sense out of it".

My oversight.... Obviously, You're right. Now the LED is active. It means that it lights. But lights constantly without any charges in brightness. So, I tried to add small delays (several ms) within "for" loops but it doesn't influence the LED brightness changes. Changing in delays just causes that the LED lights darkly or brightly, but still constantly.

Majenko showed you one of your mistakes.
Then you wrote:
//Enable to interrupt Compare Match A
TIMSK1 = (1<<OCIE1A);

And this is your other mistake. You should not enable an interrupt
unless you have defined an ISR for it. Otherwise your program will
restart every time the interrupt fires.

My advice. Stay simple. Try to get your code to output a duty cycle first. From there try to get your code to vary the duty cycle.
Once you do that the issues with your code will be clear.


text:
How to receive and process a long string sent over serial?
I want to receive about 5kb of data in Base64 format. The following code does not work. Only a few characters are received, sometimes CPU crashes.
String content = "";
char character;

while (Serial.available()) {
       character = Serial.read();
       content.concat(character);
}

I do not care about ram usage since on ESP32 there is plenty.
How can I get all the data? Example input: https://pastebin.com/wYG5AhHK

You need to signal the end of data by sending a code or a data length. Serial.available() may be receiving data by chunks, so it can be false at some moments.

I can see no logical cause, other than maybe you want to yield() within your while loop. You can also pre-allocate the space in your string to reduce heap mangling. content.reserve(6000); Better would be to not use String at all but use a large statically allocated character array.

I had to read until delimiter :D
String receive() {
        String content = "";
        content = Serial.readStringUntil('\r');
        return content;
    }

Now it is fine. I will also change String to large char array.


text:
is using two UARTs wiser compared to I2C and UART with Arduino + Xbee + BNO055 Sensor
Hardware

Arduino Nano
XBee Pro S1 (802.15.4) Modules
Adafruit BNO055 Absolute Orientation Sensor

Purpose
I want to send the Euler angles and Linear Acceleration angles to the a central XBee Coordinator (can be connected to a Computer or a Single Board Computer) every 100 ms
Since the BNO055 has SDA and SCL pins for I2C how will the performance of the Nano matter when sensor data is acquired from the BNO sensor and send to XBee module which will be connected to the Hardware Serial UART Port?
An interesting observation was that if one:

Shorts the PS1 pin to 3.3V for the BNO055, the SDA and SCL will function as RX and TX pins for UART.
  source

In terms of interfacing, I can think of the Xbee now connected to the Hardware Serial Port and perhaps the BNO sensor will can be connected to the Nano via SoftwareSerial port. But will that serve any better purpose in terms of performance and data acquisition i.e. using two Asynchronous Serial Ports compared to one?

All software serial solutions are much less efficient than HardwareSerial (i.e., Serial).  SoftwareSerial is particularly bad, because it disables interrupts for long periods of time.  95% of the MCU time can be spent twiddling its thumbs, waiting for each bit to come in.
Using the I2C interface for the BNO055 means that the Arduino hardware will independently and concurrently handle each byte of data from the BNO055 and from Serial (i.e., the XBee).  Your sketch can continue to do other things while each byte arrives.  This is most efficient.
Software serial port libraries handle each bit of data, sometimes to the exclusion of all other activity.

So even though I2C being a synchronous serial protocol and UART being asynchronous; results might tend to be good in status quo than 2 asynch. modes on the Arduino.

@Shan-Desai, the processor load is much less with I2C+UART.  Sync/asynch does not matter, because the peripherals (I2C controller and USART) operate independently from the CPU.  It's like hardware-accelerated graphics vs. software rendering.


text:
Weird arduino bug, using microphone and relay
I made a clap light switch to control my room lights and ground LEDs, and it works perfectly but when ever I have both the LEDs and the lights on it kinda stops working.
I use two claps for the lights and three for the LEDs.
Does anyone know what could be wrong? here is my code.
/* DEFINE PINS */
const int buzzer = 2;
const int micPin = 0;
const int relayLED = 9;
const int relayLights = 8;

const int sampleWindow = 50;
const int N = 50;

unsigned int sample;

boolean lights = false; //lighs on or off
boolean leds = false; //leds on or off

double soundArray[N]; //array to check claps

int i = 0;
int clapsCount = 0;

void setup() {
  pinMode(relayLED, OUTPUT);
  pinMode(relayLights, OUTPUT);
  digitalWrite(relayLED, HIGH);
  digitalWrite(relayLights, HIGH);
}

void loop() {
  /* gets 50 constant sound sample and resets */
  if (i<N) {
    soundArray[i] = getVolts();
    i++;
  } else {
    i = 0;
  }
  if (i == N-1) {
    clapsCount = clapCount(soundArray);
  }

  /* if 2 claps detected do this */
  if (clapsCount == 2) {
    if (lights == false) {
      turnOnLights();
      lights = true;
    } else {
      turnOffLights();
      lights = false;
    }
    playSound();
    clapsCount = 0;
  }

  /* if 3 claps detected do this */
  if (clapsCount == 3) {
    if (leds == false) {
      turnOnLeds();
      leds = true;
    } else {
      turnOffLeds();
      leds = false;
    }
    playSound();
    clapsCount = 0;
  }
}

int clapCount(double soundArray[]) {
  int claps = 0;
  for (int j=0; j<N; j++) {
    if (soundArray[j] > 3.0 && soundArray[j] < 3.5) {
      claps++;
    }
  }
  return claps;
}

void turnOnLights() {
  digitalWrite(relayLights, LOW);
}

void turnOffLights() {
  digitalWrite(relayLights, HIGH);
}

void turnOnLeds() {
  digitalWrite(relayLED, LOW);
}

void turnOffLeds() {
  digitalWrite(relayLED, HIGH);
}

/* gets mic volts */
double getVolts() {
  unsigned long startMillis= millis();  // Start of sample window
  unsigned int peakToPeak = 0;   // peak-to-peak level
  unsigned int signalMax = 0;
  unsigned int signalMin = 1024;
  // collect data for 50 mS
  while (millis() - startMillis < sampleWindow)
  {
    sample = analogRead(micPin);
    if (sample < 1024) {
       if (sample > signalMax) {
          signalMax = sample;  // save just the max levels
       }
       else if (sample < signalMin) {
          signalMin = sample;  // save just the min levels
       }
    }
  }
  peakToPeak = signalMax - signalMin;  // max - min = peak-peak amplitude
  double volts = (peakToPeak * 5.0) / 1024;  // convert to volts
  return volts;
}

void playSound() {
  tone(buzzer, 1000);
  delay(100);
  tone(buzzer, 500);
  delay(100);
  noTone(buzzer);
}

Edit:
When I do both two claps and three claps, both lights turn on and no matter how many times I clap none of them turn back off.
Edit 2:
Components I am using are, a simple buzzer, and microphone called MAX4466 and a 5v relay with two outputs.

Please edit your question to explain exactly what you mean by "kinda stops working".

@per1234 edited now, sorry about that.

We need to know what these devices are and how they are connected. The code listing has some issues, but we can't do a good answer without the hardware info. Like, are you using an actual microphone, condenser, piezo, what? I suspect your method of identifying a clap isn't working how you think it is.

I read your code and looks well written at first sight. Not having the hardware, I can elaborate on the physical aspects of your problems. It can be how your are sampling or counting. Put some Serial.print in getVolts and clapCount to test that they detect and count correctly. You can also use an hand filled soundArray to check the logic.

Apologies again, I edited it one more time with the other information.

This scheme of clap counting does not seem sufficiently though through to work at all - first, you evaluate in a buffer and then throw everything away, so you'd have to luck out and get all your claps in a buffer, and not some in an old one that gets throw away and the rest in the next.  But more importantly, you don't seem to ever implement anything that looks for a sharp sound and then a gap.  You basically need to start over with a plausible algorithm - you need to count sounds with intervening gaps, and then act only when theres been a long enough gap to mean no more will follow.

I've looked through your code and can't see anything obvious that is causing the problem, so I have refactored it a bit in the hope that the problem becomes more obvious.
/* DEFINE PINS */
const int PinBuzzer = 2;
const int PinMic = 0;
const int PinRelayLED = 9;
const int PinRelayLights = 8;

const int sampleWindow = 50;
const int MaxSamples = 50;

// Simple enumeration to clarify which state is on and off.
enum EOnOff { Off, On };
EOnOff lights = Off; //lights on or off
EOnOff leds = Off; //leds on or off

double soundArray[MaxSamples]; //array to check claps

void setup()
{
    pinMode(PinRelayLED, OUTPUT);
    pinMode(PinRelayLights, OUTPUT);
    digitalWrite(PinRelayLED, ConvertOnOff(leds));
    digitalWrite(PinRelayLights, ConvertOnOff(lights));
}

void loop()
{
    for (int sample = 0; sample < MaxSamples; ++sample)
    {   // Get the samples
        soundArray[sample] = getVolts();
    }
    switch (clapCount())
    {   // Analyse the samples
    case 2:
        lights = ChangeRelay(lights, PinRelayLights);
        playSound();
        break;
    case 3:
        leds = ChangeRelay(leds, PinRelayLEDs);
        playSound();
        break;
    }
}

/// Count the number of 'claps' in the sample data
int clapCount(/*clap array is global*/)
{
    int claps = 0;
    for (int sample = 0; sample < MaxSample; ++sample)
    {
        if (soundArray[sample] > 3.0 && soundArray[sample] < 3.5) /* Why 3.5?? */
        {
            ++claps;
        }
    }
    return claps;
}

/// Convert an EOnOff value to a HIGH or LOW value.
// OFF = HIGH
int ConvertOnOff(const EOnOff& state)
{
    return state == Off ? HIGH : LOW;
}

/// Change a relay to the given state.
/// Return the new state.
EOnOff ControlRelay(const EOnOff& state, const int& relayPin)
{
    EOnOff result = state == On ? Off : On;
    digitalWrite(relayPin, ConvertOnOff (result));
    return result;
}

/* gets mic volts */
double getVolts()
{
    const unsigned long startMillis = millis();  // Start of sample window
    unsigned int signalMax = 0;
    unsigned int signalMin = 1024;

    unsigned int sample;
    // collect data for 50 mS
    while (millis() - startMillis < sampleWindow)
    {
        sample = analogRead(PinMic);
        if (sample < 1024)                  // ?? Should this be 1024 or signalMin?
        {
            if (sample > signalMax)
            {
                signalMax = sample;  // save just the max levels
            }
            else if (sample < signalMin)
            {
                signalMin = sample;  // save just the min levels
            }
        }
    }
    const unsigned int peakToPeak = signalMax - signalMin;  // max - min = peak-peak amplitude
    const double volts = (peakToPeak * 5.0) / 1024.0;       // convert to volts
    return volts;
}

void playSound()
{
    tone(buzzer, 1000);
    delay(100);
    tone(buzzer, 500);
    delay(100);
    noTone(buzzer);
}

What I have tried to do is to reduce the number of lines of code.  If there are less lines then there should be less bugs :)
You used a bool to record the on off state, I changed that to an enumeration because that adds a bit of clarity, and when working with mains voltages I like things being clear.
I changed your while loop into a for loop, I think it looks cleaner.  This was also the reason I changed your if statements into a switch statement.
The guts of the if statements have been removed and placed in a function ChangeRelay(), it returns the new state of leds or lights.  I could have gone with a reference to make state an in out parameter, but decided a return was simpler.
ClapCount() and GetVolts() are relatively unchanged apart from a bit of const'ing of variables to make things easier to read.  Also you might have noticed I, j and N have all been removed, because single letter variable names are my nemesis, who knows what q means and why r and t are being added to it to make z?
ControlRelay lets you route all you relay switching through one function, if there was a copy and paste bug in your code (which I don't think there was) then they will either all work or not work now.
There is a big difference between "my" code and yours, you won't be able to switch both on at the same time because the switch statement won't let you.  So in a way you problem is solved.  If you really wanted to you could add:
case 5:
    lights = ChangeRelay(lights, PinRelayLights);
    leds = ChangeRelay(leds, PinRelayLEDs);
    playSound();
    break;

Thank you for making the code better!
I tried it and it works just like mine, but the bug still happens, I am not sure if  it is a limitation of the relay, if both lights are on it does not turn off no matter what.
And yeah I know the single letter variables are bad, I normally use only single variables like i, j, k for the for loops, but since I was just testing I got some weird ones with single letter too.

I tried using the serial read to type 2 or 3 as simulation of the claps and it works perfectly fine, got both on, turn off each at a time all perfect, but when ever it is claps it doesnt seem to work, maybe my algorithm to get the claps is bad.

@Matthew - In getVolts the else if should be just an if.  Otherwise you need two samples to adjust the max and min to the correct values.


text:
Atmega2560V, trying to burn bootloaders of MegaCore
I am trying to burn MegaCore bootloaders to it, I have setup my custom PCB  with Atmega2560V-8AU and 8Mhz Crystal + Load Caps all assembled on using PCBA process.
I am trying to burn MegaCore bootlaoders to it, I am using Arduino UNO as ISP Programmer. My connections are all correct, It shows different Device Signatures (see below) whenever I hit Burn Bootloaders....

0x0000ff
  0x00003f
  0x0000ff
  0x00ff00
  0x001000
  0xff0000
  0xfc0000
  0x00fe00

This is complete output with different Device Signatures

Arduino: 1.8.3 (Windows 10), Board: "ATmega2560, Arduino MEGA pinout,
  2.7v, Disabled (default), 8 MHz external"
C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude
  -CC:\Users\mudas\OneDrive\Documents\Arduino\hardware\MegaCore-avr-100-pin\avr/avrdude.conf
  -v -patmega2560 -cstk500v1 -PCOM4 -b19200 -e -Ulock:w:0x3f:m -Uefuse:w:0xfd:m -Uhfuse:w:0xd6:m -Ulfuse:w:0xf7:m
avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
           Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
           Copyright (c) 2007-2014 Joerg Wunsch
     System wide configuration file is "C:\Users\mudas\OneDrive\Documents\Arduino\hardware\MegaCore-avr-100-pin\avr/avrdude.conf"

     Using Port                    : COM4
     Using Programmer              : stk500v1
     Overriding Baud Rate          : 19200
     AVR Part                      : ATmega2560
     Chip Erase delay              : 9000 us
     PAGEL                         : PD7
     BS2                           : PA0
     RESET disposition             : dedicated
     RETRY pulse                   : SCK
     serial program mode           : yes
     parallel program mode         : yes
     Timeout                       : 200
     StabDelay                     : 100
     CmdexeDelay                   : 25
     SyncLoops                     : 32
     ByteDelay                     : 0
     PollIndex                     : 3
     PollValue                     : 0x53
     Memory Detail                 :

                              Block Poll               Page                       Polled
       Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
       ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
       eeprom        65    10     8    0 no       4096    8      0  9000  9000 0x00 0x00
       flash         65    10   256    0 yes    262144  256   1024  4500  4500 0x00 0x00
       lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
       signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

     Programmer Type : STK500
     Description     : Atmel STK500 Version 1.x firmware
     Hardware Version: 2
     Firmware Version: 1.18
     Topcard         : Unknown
     Vtarget         : 0.0 V
     Varef           : 0.0 V
     Oscillator      : Off
     SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions
Error while burning bootloader. Reading |

  ############################################ | 100% 0.02s

  avrdude: Device signature = 0x00fe00 avrdude: Expected signature for
  ATmega2560 is 1E 98 01
           Double check chip, or use -F to override this check.
avrdude done.  Thank you.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.
What should be the problem.??? How to solve this.?

Also posted at:https://github.com/MCUdude/MegaCore/issues/63 and http://forum.arduino.cc/index.php?topic=494076

Yes and also at http://www.avrfreaks.net/forum/atmega2560v-trying-burn-bootloaders-megacore

Now that the problem has been solved, would you mind taking the time to answer your question so that it might help others? From the GitHub issue report, I know that once you were able to start reading a consistent (though incorrect) device signature the final step was to use the -F AVRDUDE option to override the signature check but it's not clear what the change was that you made to get from the inconsistent device signature readings to the consistent readings. I believe it was a hardware change?

I removed 8Mhz from board and followed this instructions LINK, and burnt bootloaders using -F override check, then i returned 8Mhz oscillator to Atmega2560V and see device signature and it's automatically appears 0x1e9801 rather than 0x1e9803

Is this an answer or comment?

This is an answer.

Please, accept your own answer to close this question.


text:
Arduino digitalWrite not working
I am trying to control this OWI Robotic Arm using the Arduino's digital outputs (I am using pins 12 & 13).
If I wire up the wires to ground and 5V it goes one way, if I switch the wires, it goes the other way. However when I have the pins wired up to the digital pins, it does not work, but the on-board LED does blink.
The code:
int a = 12;
int b = 13;

void setup() {
  // put your setup code here, to run once:
  pinMode(a, OUTPUT);
  pinMode(b, OUTPUT);
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  //up
  digitalWrite(a, LOW);
  digitalWrite(b, HIGH);
  digitalWrite(LED_BUILTIN, HIGH);
  delay(500);
  //down
  digitalWrite(b, LOW);
  digitalWrite(a, HIGH);
  digitalWrite(LED_BUILTIN, LOW);
  delay(500);
}

Why do you think that the pins can supply anywhere near what current the arm requires?

Honestly, I have no idea what I am doing, but I assume the pins can be as powerful as the 5V pin on the Arduino, and that was enough to drive the motor.

Do the datasheet and specifications back up your assumptions?

Assumption IS the mother of all screw ups.  In this business you NEVER assume.  You read and check and find out.  You may have burned up your Arduino by now.

The problem you are seeing here is that the Arduino can provide nowhere near as much current through I/O pins as it can power. Quoting from the Arduino website:

DC Current per I/O Pin: 40 mA

This means that each pin can power maybe a couple of LEDs, and that's it. Additionally, motors provide "back-EMF": When opening (cutting power) an inductive load (e.g. a motor), the current wants to keep going. This will damage whatever just opened unless protection is used. So, I wouldn't be surprised if you damaged your Arduino by attempting to drive a motor with it.
So, what can you do? Use an H-Bridge. This circuit will allow you to easily control a motor & its direction. Many circuits can be found online, but an easy solution is a cheap L298N module, which can be as cheap as $3 a piece. This will safely & easily control the arm. Connecting your Arduino with the following circuit & using your existing sketch will make it work.

simulate this circuit – Schematic created using CircuitLab


text:
using references to SFRs in gcc inline assembler
I want to write a driver that can use either timer0 or timer2, based on a choice made at compile time.
So I want all references to timer registers to be abstracted, e.g. OCRA for OCR0A/OCR2A, etc.
I could do it with plain macros, like so:
#define _CONCAT3(a,b,c)   a##b##c
#define CONCAT3(a,b)   _CONCAT3(a,b,c)

// set timer number globally
#define MY_TIMER 2

// define an alias for each control register
#define OCRA CONCAT3(OCR, MY_TIMER, A)

but for some reason I don't want to use macros there.
So I came up with this scheme:
typedef volatile uint8_t& tRegister;

constexpr volatile uint8_t& timer_register (volatile uint8_t& a, volatile uint8_t& b)
{ return MY_TIMER==0 ? a : b; }

tRegister OCRA = timer_register (OCR0A, OCR2A);

It works pretty well for all its awkwardness, but when I try to use this definition in an inline assembly directive, I get strange results:
asm volatile("lds r24, %0" : : "i"(&OCRA));

will get an error: impossible constraint in 'asm'
Now this:
asm volatile("lds r24, %0" : : "i"(&timer_register (OCR0A , OCR2A )));

will compile (and produce lds r24, 0x00B3 as it should).
By definition a reference to a static variable is a constant address, known at compile time, so I can't see why it can't be used in this context.
So my questions are:

what is going on there?
how to alias these registers (without macros) to please the inline assembler?

You could use pointers instead of references. With pointers, you have
the separate notions of “constant pointer” and “pointer to constant”. A
reference is a kind of pointer coated with syntactic sugar. However,
whereas you can have a “constant reference” (equivalent to pointer to
constant), I do not know how to declare a “reference with constant
address” (which would be the equivalent of a constant pointer). And
this is your issue: the "i" constraint in the asm statement requires
a constant.
Here is my take with pointers:
typedef volatile uint8_t * tRegister;

constexpr tRegister timer_register(tRegister a, tRegister b)
{ return MY_TIMER==0 ? a : b; }

// The `const' below is essential.
const tRegister OCRA = timer_register(&OCR0A, &OCR2A);

asm volatile("lds r24, %0" : : "i"(OCRA));

Of course, you then have to change all your OCRA = ...; statements
with *OCRA = ...;, which is awkward. But note that the avr-libc
defines the SFRs with macros equivalent to
#define OCR0A (*address_of_OCR0A)

If you want this convenience, you may have to resort to using similar
macros yourself.

Well thanks, but that's a workaround. I actually did something similar, but limited to the asm directives, so that I could at least use my reference aliases in the C++ code. I guess this fine docrine point about the difference between a reference and a constant pointer is just another small hole in the atrociously convoluted specs of C++ the poor guys who implemented the inline assembler fell into :D.


text:
Attiny85 - Method to discard glitched ADC values?
I have a problem i need to solve so i will simply it as much as possible.
Basically there is a system with a micro-controller where it reads 2 sensors. These 2 sensors are of variable resistance type, aka their measuring value is output as different resistance. For example one is a pressure sensor where at 0psi the sensor has a value of 20ohms to ground, and for 100psi it has a value of 120ohms. The sensor is connected between ground and a fixed value resistor so the output acts like a voltage divider.
The micro-controller seems to be multiplexing by switching pull up between each 2 sensors (probably because using a single ADC), at random times (as the microcontroller performs other functions) but approx. every 80ms for each sensor, and about 40ms between each sensor. So at 0ms it reads one sensor, at 40ms the other sensor, and at 80ms back at the first sensor and so on. I have no idea why they haven't used a fixed pull-up, but the pull-up is only done when the controller wants to read the sensor for only about 120us.
I wanted to read these sensors to input to an ECU, without affecting the original device. Thus the easiest solution i could think off as the pull-up isn't always high to perform a read, was to add another microcontroller (in my case a Digispark based on the ATtiny85 running at 16.5MHZ). Alternatively i could open up the device and modify it to use a fixed pull-up but let's say i want to avoid this route. The digispark essentially reads both sensor outputs and when it sees a voltage above ground it outputs it to the ECU. I have since then updated the program to check the ADC values it reads so that it is between the nominal range of the sensor. And while this works there are times where the ADC will read a wrong value and output it to the ECU which looks as random spikes and dips in the data.
Look at my following code:
  const int oil_in = 0; //P5
  const int temp_in = 1; //P2
  const int oil_out = 1; //P1
  const int temp_out = 4; //P4
  int oil_value = 0;
  int oil_value_good = 0;
  int temp_value = 0;
  int temp_value_good = 0;

// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(oil_out, OUTPUT);
  pinMode(temp_out, OUTPUT);
}

// the loop routine runs over and over again forever:
void loop() {
  oil_value = analogRead(oil_in);
  if (oil_value > 106 && oil_value < 466)
  {
    oil_value_good=oil_value;
    analogWrite (oil_out, oil_value_good/4);
  }

    temp_value = analogRead(temp_in);
  if (temp_value > 113 && temp_value < 920)
 {
    temp_value_good=temp_value;
    analogWrite (temp_out, temp_value_good/4);
  }
}

Each ADC pin has a range of acceptable values. These correspond to the MIN AND MAX nominal values for each sensor. However there are times where the ADC will read at the wrong time and it will output either a MIN or a MAX value depending on the condition. I can replicate this on the breadboard by having the input to the ADC reading a nominal value, and by shorting it to either ground or VCC (5V) i can sometimes trick the ADC to read a MIN or MAX value. And since the next measurement will be done after some time, the output will produce these spikes. Since there is no sync between the readings these error data can be sometimes be outputed for 1-1.5s.
I've tried thinking hard about this problem, but i am not sure for a certain solution that will eliminate this problem. ADC interrupts, changing ADC pre-scaler, filtering of data, problem the reading window is really small (100-120us).
Also nominal ADC input values for each sensors are between 0.56V-2.33V for one sensor, and 0.6V-4.68V for the other sensor. Not sure if the interrupt can even be activated at such low voltage.
How do you think i should proceed?
Kind regards

i can sometimes trick the ADC to read a MIN or MAX value - if you short it to Gnd or Vcc, don't you expect this?

Well yes and no, the problem is that the ADC sometimes reads on the falling or rising edge of the signal which might be in the acceptable range, therefore been passed as a "good" value.

I have no idea why they haven't used a fixed pull-up, but the pull-up
  is only done when the controller wants to read the sensor for only
  about 120us.

If you want to get a good resolution in the resistance measurement, the
resistance of your pull-up should be in the same range as the resistance
of your sensor. If your sensors have low resistance, this means the
voltage divider will draw significant current. In order to save energy,
it makes sense to power the voltage divider only while you are doing the
measurement.

the reading window is really small (100-120us).

That's short indeed. If you analogRead() a single channel in a tight
loop, you will get one reading every 108.6 µs (128×14 CPU
cycles ÷ 16.5 MHz), and you have a small risk of missing the
window. If you are reading two channels, then you have about 50% risk of
missing the window.
Here is what I would do:

Set the ADC prescaler to 64 instead of 128. This way you will get one
reading roughly every 54 µs, and at least one sample (but more
often two) during the reading window.
Read a single channel in a tight loop, until you get a value above
your minimum. Then take one more reading and use the largest of the
two as your “good” value.
Switch to the other channel and go back to step 2.

This assumes that outside the reading window your ADC input reads close
to zero, as it is grounded through the sensor, with no pull-up. You then
have, on each channel, a train of positive pulses, and you want to
measure the height of those pulses. There is a small risk of you
sampling the rising edge of a pulse, which could give a wrong value
which is nevertheless above your minimum. If this happens, then the next
sample will be near the center of the pulse. That's why I recommend
taking one extra sample and using the largest of the two.

I've already set the prescaler to 16 actually since depending on the bootloader version i have 16.5Mhz is only when running it through usb, otherwise the cpu runs @16mhz, giving an effective prescaler of 1Mhz which is in the acceptable range in the Atmel datasheet. It didn't affect much to be honest in bench testing (of which i cannot actually replicate exactly 100% the conditions), but last night i've integrated the MovingAverage lib which performs exponential moving average filtering with very good results, although i will do more testing and report back. Will consider the other recs as well

@TnF: 1 MHz is kind of borderline for the ADC frequency: it should work, but expect degraded accuracy. An exponential moving average is very good at filtering out Gaussian white noise, but is far from optimal against sporadic glitches. A median filter would be way better.


text:
Bluetooth Low Energy dropping data at 115200 baud?
I'm transmitting serial data from a sensor on my Arduino simultaneously to my laptop via USB and to a terminal app on my phone via a genuine HM-10 BLE module (onboard a Linksprite BLE Shield).
At 9600 baud, the BLE module was transmitting all of my data to the phone's terminal app without issue. I just figured out how to increase the HM-10 module's baud rate to 115200 (for reference, by sending it an AT+BAUD4 command at 9600 baud from the Arduino IDE console via USB, and then uploading a new sketch to the Arduino with both the USB serial and BLE serial baud rates set to 115200). The data is being received via USB serial flawlessly, but the data received by the terminal app on my phone via BLE appears to be missing chunks of data - and I have to try to connect to it 30+ times to get it to properly connect.
Is 115200 baud too fast to transmit data via BLE? Is there any way to make sure all of the data is properly sent via BLE without slowing the program down too much? 9600 baud is too slow for my application, unfortunately.
I should add that I am using an Arduino M0 pro and the BLE is connected via hardware serial (Serial1) and not SoftwareSerial as would need to be done on the Uno, if that makes a difference.

Well, I did some tests and was not able to reliably receive data at over 9600 baud, even with hardware flow control activated via the AT+FLOW1 command. And even then, if either the BLE module or the phone was moving, data was consistentlydropped.
I ended up implementing an SD data logger instead.

How quickly are you reading the data from the buffer?


text:
Differences between Arduino Uno SMD and Uno DIP
I just bought an Arduino Uno (SMD version) from W11Stop and want to know whether there is any other difference between Arduino UNO DIP and Arduino UNO SMD besides knowing that the SMD version doesn't have a DIP chip which can be replaced?
I am just a beginner so please help me if I am wrong!

Afaik, the SMD version actually has two extra analog pins. But they may not be accessible on your Arduino board (ADC6 & ADC7). The PDIP has 28pins TQFP has 32 pins (check the datasheet). But the internals should be the same by design.

As far as I know there is no real difference, at least not directly related to the SMD.
There are many clones which sometimes have slightly different behavior or protection.
But for the SMD the only disadvantage is it cannot (easily) be replaced.
I have one original one (with DIP) and several clones and so far I did not found any difference, except for having mini USB instead of normal USB.

mini USB instead of USB-B is just a chinese version of it. Many clones of Arduino bought from china have either MINI, MICRO or B-type usb port, you can actually choose. But none original(UNO) has ever had a mini USB on it.

Actually, there are no different on the functionality. But you may can't go through some features, because the ATmega can be remove it manually without any special tools. One of the useful case as ArduinoISP for burning bootloader to another ATmega328p AVR.
For personal suggestion, you just needed one piece of PDIP/DIP version UNO, others boards you can consider the lower cost, such as Nano, Pro Mini(Without USB-to-TTL), UNO(SMD).
For the USB-to-TTL, there are many options in the market, watch this video to explain what are they different.

alright... at least as a starter we could keep continuing the dev under any arduino ....

There's no actual difference, but just the "look". Neither version of it should bother you at anything, but there are 2 things, worth mentioning.

The IC can fall out of DIP socket: I've been told a few times this already, but never had experienced such behaviour or been at occasion, where that happened.
So here's a disadvantage for DIP cases.
DIP has also possibility of changing waaaaaaaaaay easier the microprocessor in case of failure. You simply grab it off (even might with a help of a screwdriver) and you're ready to put in a new one. So this is an advantage nr. 1.
I also like to use an Arduino in projects, but not the whole board. I just take the IC (atmega328) and use 2 ceramic caps with 16MHz quartz and I've got my own arduino on other PCB - in this case, you can use Arduino UNO board as a programmer. This is how to avoid installing FTDI or CH340 chip on other boards.
Advantage nr. 2.


text:
Connecting esp8266 using Arduino
I am trying to connect to esp8266 using Arduino UNO. There are various things on the internet having mixed information and hence I am seeking some clarity.
I followed these instructions, but could not get to connect to ESP8266 using AT command. http://cordobo.com/2300-flash-esp8266-01-with-arduino-uno/
I have following questions:

Can I connect ESP8266 directly to Tx/Rx without voltage divider or level shifter? I also suspect that the voltage divider connections are wrong. As per my understanding, the Tx from Arduino should be divided, and the divider output should be connected to ESP8266.
When I connected the shield as described, the shield gets hot. Is there any way to conclude if the shield is damaged or not?
When I connect the device using voltage divider the blue LED on the shield also lights up. Without divider, it does not light up. What is the significance of the blue LED?

Hardware
ESP8266-01 pinout

Circuit using voltage divider

Circuit without voltage divider

Which connection method did you use? There are several in the page you referenced. Better, post your schematic.

I tried both the methods. The one without voltage divider (section 3.2) and the one with voltage divider (Section 3.1). I could not get the AT commands work with either method. When I connect using voltage divider the blue LED was turned on. When connecting without voltage divider the blue LED did not light.

There are a number of issues with the tutorial you've listed there.
Firstly, a voltage divider is very highly recommended as the ESP8266 cannot handle more than 3.3V, however, the connections for the voltage divider in the tutorial you linked to are the wrong way round (as you suspected).
Secondly, you cannot power the ESP8266 directly from the Arduino, as the power requirements are higher than the Arduino's on board 3.3V regulator. A separate power supply or regulator is recommended. This might be cause of it getting hot (the onboard regulator maybe - but I can't be sure as there is not enough information from your initial post as to exactly what is getting hot).
There are 2 LED's on the ESP8266 shield (the one used in the tutorial you've linked to) one is power and the blue one is wifi communication.
The other potential issue with the tutorial you've linked to is that they have used Arduino pins 0 and 1 to connect to the ESP8266 - while this will work, the problem is that the Arduino uses pins 0 and 1 to communicate over USB with a computer, which means that in in that configuration you cannot use Serial monitor to send/receive data.

Thanks for the confirmation about the voltage divider. I did try with Arduino 3.3V output and surprisingly it was shiled that was getting hot and not Arduino.

If you don't use Arduino 0 and 1 then you can use SoftwareSerial, but that can not support high data rates.  9600 is usually OK, I don't know about higher.

Arduino Tx — resistor (1/3) — tap to ESP-01 Rx — resistor (2/3) – GND

@holmez Do I need to do same for Rx pin well?

@ManishSapariya You only need to do it for the Arduino Tx, because you're changing the transmission voltage from 5V to 3.3V. The ESP8266 will transmit at 3.3V, which the Arduino is happy with.

Some ESP boards are 5v tolerant on the digital pins, some aren't. So it depends on what board you have, I don't think the one in the tutorial is.
If you are using serial to communicate the a resistor divider will not work.  You need a proper level shifter, which you should be able to get for less than a $1.  Remember you will probably need to down shift the Tx from the Arduino and Up Shift the RX to the Arduino.

A resistor divider will work as long as the resistors are low enough, but not too low, resistance. I found 1K + 2K worked, but 10K + 20K didn't.

what do you mean by "some are, some aren't" 5v tolerant? Which ones are which? where did you find such information?

@dandavis - The ESP8266 chip data sheet says that the GPIO pins only accept 3.3v max (http://download.arduino.org/products/UNOWIFI/0A-ESP8266-Datasheet-EN-v4.3.pdf), but I know the Node Lua and Wemos D1 are 5v tolerant (well they didn't burn).  I don't have a definitive list, in fact I would even stake a donut on the fact that all Wemos D1s are 5v tolerant, because there are so many different designs of the "same thing"

looking at the D1's schematic,  the GPIOs are almost all wired straight-through to the 12F module, which would imply all 12Fs share the property. I believe it comes down to quality/die luck: the only one (of dozens) i've had that was noticeably finicky w/ 5v components was one that also froze when "overclocked" to 160. The main issues likely stem from too much heat, and a D1 probably dissipates heat better than an ESP01, commanding more volume in an enclosure if nothing else...

I agree, I suspect they should all be 3.3, but sometimes you get away with it :)

I'm working with ESP-12S which use ESP8266 recently.
My main goal is to use UART-WIFI passthrough mode, so I only need VCC, RX, TX, GND.
These are the steps I take:

Use USB to TTL converter to link WIFI module to PC for WIFI configuration. (two USB converter were used for power issue)

On PC I used minicom to open the USB serial. Use AT commands(espressif.com/sites/default/files/documentation/4a-esp8266_at_instruction_set_en.pdf) to config WIFI module:
AT+RESTORE              // restores the factory default settings
AT+GMR                  // checks version information
AT+RST                  // restarts the module
AT+CWMODE_DEF=1         // set station mode
AT+CWJAP_DEF="APname","password"    // connect to AP
AT+CWDHCP_DEF=1,1       // set station mode with DHCP
AT+CWAUTOCONN=1         // auto connect
AT+CIFSR                // show local IP
AT+PING="10.0.1.1"      // ping network gate
AT+CIPSTART="TCP","10.0.1.116",2048 // setup TCP to server
AT+CIPMODE=1            // set UART-WIFI passthrough mode
AT+CIPSEND              // enter UART-WIFI passthrough mode
AT+SAVETRANSLINK=1,"10.0.1.116",2048,"TCP" // save configuration in WIFI module
After configuration, hook WIFI module to Arduino (actully I'm using stm32, but it's the same) UART pins. When power on, the WIFI module will automatically connet to AP and setup TCP link to server and enter UART-WIFI passthrough mode.

If you want to exit UART-WIFI passthrough mode, send '+++' on UART end, without '\r\n' and '+++' must be sent continuously (type '+++' in minicom won't work).

as for your questions,

Voltage divider is used, but pay attention to RXD TXD link problem. (RXD to TXD, TXD to RXD)
My WIFI module also gets hot, but working properly.
I don't know the blue LED's function, but I did remember reading about it some where, maybe in the documentation.


text:
Is it safe to short two pins together for conditioning a sketch?
I want to make a sketch which behaves differently, i.e.:
pinMode(pin1, OUTPUT);
digitalWrite(pin1, HIGH);

pinMode(pin2, OUTPUT);
digitalWrite(pin2, LOW);

pinMode(pin3, INPUT);
// And a user decides to short pin3 with pin1 or pin2

if (digitalRead(pin3) == HIGH) {
  // behavior 1
} else {
  // behavior 2
}

But, I wonder whether shorting two pins with/without a resistor safe or not. If it is dangerous, what is an alternative way to do such a thing?

You are connecting 5V to ground, with a near zero Ohms wire. Calculate the current.

I would pinMode(pin3, INPUT_PULLUP);, this way you condition the sketch on the pin being either grounded or not. You can then connect a switch between pin 3 and GND to have the switch control the behavior.

Firstly, why would you?
All you are doing is connecting the input pin 3 to either VCC or GND, since that is what setting a GPIO to HIGH or LOW gives you - why would you waste two GPIO pins for that purpose?
"shorting" an input pin with VCC or GND is what you do with a button or switch anyway. The resistor in that case is used to hold the pin in the opposite direction when the button isn't being pressed. The same effect can be created using a two-way switch connecting the pin to either VCC or GND with no resistor required.
So yes, you can "short" the input pin with an output pin safely - as long as that input pin never becomes an output pin at any time (hint: never use pin 13 on an Uno for this - it becomes an output to flash the LED during the bootloader over which you have no control. The same goes for the TX pin.)


text:
how to set the delay on for 7 hours?
For my application I need to simulate the sunlight including the rising and setting of the sun.
I have a program that will light up some LEDs slowly over a period of time but I need to know what to type in the (delay on) to keep the lights on for 7 hours?
Will it work if I just replace delay(1000) with delay(25200000UL) ?
I don't want to run anything else at the same time and don't want to use or understand millis().
Thanks for any help.

Do you want  "light up slowly over time" and then wait for 7 hours?

Hi, I already have it lighting up slowly over time just need to stay on for 7 hours then slowly turn off.

This is the kind of problem that you can resolve with a single test. Make a sketch, put the delay and see what happen.

It does upload but with an error but still compiles, tried again and no error...seems to be working.

Very new to this, it seems to be working now. Thankyou very much for your responce.

Please add the answer to this page by clicking on the answer your own question button at the end of the page. This will then help others that have the same problem.

Yes, absolutely, it should work. But your code will be easier to read if
you use some constants, like:
const unsigned long SECOND = 1000;
const unsigned long HOUR = 3600*SECOND;

delay(7*HOUR);

Yes you can write delay(25200000UL) and it will delay for 7 hours.
How it works
delay(x) will delay for x number of milliseconds.
1 second = 1000 milliseconds
1 minute = 60 seconds
1 hour = 60 minutes
7 hours = 1000 * 60 * 60 * 7 =  25,200,000
This number is quite large but is well within the scope of an unsigned long: 32 bits = (2^32)-1 = 4,294,967,295. Doing the sums, this will last for 49 days and 17 hours.
Delaying for >49 days
If for some reason you needed to go longer than 49 days, you can do so by placing the delay inside a for loop.
const unsigned long ONE_DAY = 24UL*3600*1000;
const unsigned int numOfDays = 51;
int i;
int j;

for( i=0; i<numOfDays; i++ )
{
    delay(ONE_DAY);
}

You wrote: 1000*3600*24UL. This will overflow. You mean 1000UL*3600*24: multiplication is left-to-right associative in C++. You also wrote i<7 while you probably meant i<numOfDays.

It's an old one but I give an answer.
I think someone needs help like you.
I trying to make a fish meal machine with the Arduino Uno.
In the first.
I counted seconds over a minute.
It works well.
But when I try over an hour it does not work.
After all.
I got to know another way to count a long time
In the second.
I used the SimpleTimer.h.
The link is here.
Arduino SimpleTimer
It's an easy way to makes a circular moving but it has the same problem.
SimpleTime can't make a count over time.
I think it's 30 seconds.
Now I referenced StackExchange Arduino.
Here is my code.
#include <SimpleTimer.h>
#include <Servo.h>

#define FIVE_SEC 5000UL
#define ONE_MIN 60000UL
#define FIVE_MIN 300000UL
#define TEN_MIN 3000000UL
#define ONE_HR 3600000UL
#define EIGHT_HRS 28800000UL
#define TWELVE_HRS 43200000UL

SimpleTimer timer;
Servo servo;
int servoPin  = 9;
int servoReadyAngle = 180;
int servoMoveAngle = 170;
int servoMoveCnt = 0;
int servoJobCycle = 35000;

unsigned long startTime;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  servo.attach(servoPin);

  startTime = millis();
}

void loop() {

  if(millis()- startTime > TEN_MIN) {
    startTime = millis();
    giveAFishMeal();
  } else {
    Serial.print("ping ");
    Serial.println(millis());
  }

}

void giveAFishMeal() {

  int servoAngle;
  if(servoReadyAngle > servoMoveAngle) {
    servoAngle = servoReadyAngle - servoMoveAngle;
  } else {
    servoAngle = servoReadyAngle + servoMoveAngle;
  }

    Serial.println("I give a meal to your fish");

    delay(500);
    servo.write(servoReadyAngle);
    delay(500);
    servo.write(servoAngle);
    delay(500);

}

delay(1000) is a delay in ms.
So for a 7 hour delay you need 7 hours * 60 minutes * 60 seconds * 1000 = 52,200,000
Adding UL is good, to show it's long and unsigned.
Also it fits in an unsigned long which has a max value of 2^32-1 = 4,294,967,295.
If you really want to test it you can wait 7 hours, or use a smaller number (like dividing by 60 * 60, thus 7,000 which should be 7 seconds, or make it 70.000 and check it is 70 seconds.
If you would want to make it explicitly how 52,200,000 is calculated or want to make your program more flexible you can always create some defines (or constants):
static const uint32_t DELAY_1_S      = 1000UL;
static const uint32_t DELAY_1_MINUTE = DELAY_1S * 60UL;
static const uint32_t DELAY_1_HOUR   = DELAY_1MINUTE * 60UL;

than you can use
delay(7UL * DELAY_1_HOUR); // Delay 7 hours

For my application I need to simulate the sunlight including the rising and setting of the sun.

if you have to simulate that long of a delay, you are doing something seriously wrong.
but if you do want to go down that path, something like this may work
#define delay_1hr()  delay(1000ul * 60 * 60)  //delay a hour

//delay a day
void delay_hr(uint8_t hr) {
  while (hr--) delay_1hr();
}

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


text:
How to use ESP8266 Pin D3 / GPIO 0 and D8 / GPIO 15 properly
I am using WeMos D1 Mini Pro to control multiple relays. I found out that during start up the relay connected to pin D3 and D8 would switch between on and off a couple times in a very short interval. I found out that the two pins are related to boot loader configuration.
Question is: Is there any way to prevent the relay from "blinking"? Is there a way to disable the relay output until boot loader finish it's stuff? Because this behavior only occur once every boot up.

GPIO0 comes in HIGH, so keep it HIGH in setup() and after to avoid state changes (use NC if needed). GPIO15 should not get to full HIGH voltage during boot, so connecting the relay via diode or resistor, or using a high-value shunt resistor to divide the current, or using a cap to suck up that "inrush" should be enough to allow switching while preventing boot state toggling.

A 74HC244 can be used to buffer up to 8 outputs and isolate them at will from the ESP8266. It can also be used for inputs as well if you connect gates the other way around. One additional IO line is required to control it.

Thank you for the input. That might work but I am looking more toward a software solution if there is any =)

No, there is no software solution. Any software you install runs after the bootloader, and you can't do anything to the bootloader except select the boot source using the troublesome GPIO pins you have already identified.


text:
Powering via an I/O Line
I have an SPI 128x64 OLED display. Is it safe to power this display's VCC from a digital I/O pin? I would like to do this so I can connect it flush to my arduino's header, and so I can control the power going to the display for a "low power" sleep mode.
Thanks for any responses.

Unlikely. An IO pin can only provide 25mA sustained, and 40mA peak. A display is likely to require more than that. However check the datasheet for the display. If by chance it should not need more than 25mA maximum (all pixels white) then yes it may be possible.

Adafruit model. monochrome 1.3" 128x64 OLED display (similar to yours, I assume):

Display current draw is completely dependent on your usage: each OLED
  LED draws current when on so the more pixels you have lit, the more
  current is used. They tend to draw ~25mA or so in practice but for
  precise numbers you must measure the current in your usage circuit

To be safe, you can use one pin to control a power switch for the display.


text:
Using a separate power supply?
I'm new to the operation and applications of the arduino and have a question. I would like to run 6 x 4 bit seven segment displays from an arduino controller. How do I connect an external supply to the displays to ensure I don't overload the arduino please?
Regards

Here's a tutorial from Sparkfun that shows how to drive an LED using a transistor to switch the LED. Where the transistor is connected to +5v, that should be to your external 5v supply. The pin labeled "Control" is connected to one of your Arduino pins. Connect the external supply's ground to the Arduino's ground.
Done this way, the Arduino's pin driver only needs to supply enough current to switch the transistor; the current to power the LED is provided by your external power supply.


text:
Multimaster I2C with same address
I use the Wire Library and need to have multi-master setting. I see multi-master examples, where the masters have their own ID's -- which make sense.
Now I have just connected three devices on the bus with the same ID (for example 0x05) and they can communicate! Every node can listen to all traffic, which is not common but this was exactly what I want.
The question is: Will I have trouble in the future? Is my setup something like "multi-slave"?

If all the slaves do is listen that shouldn't be a problem. If you should ever want the slaves to talk back to the master then you will instantly get collisions and it will all fall apart.

actually this problem ist solved by a string-based protocol and any nodes sends only if it get requested. But didn't tested, what happends if they try to send in the same time. I use Wire.write and receiveEvent.

Andy, that is a problem. @Majenko, perhaps the Wire library accepts a wrong ack/nak at this moment, but that might change in the future. What about the clock pulse stretching for different slaves ? I see too many problems. When sending data to multiple slaves, you can use the broadcast. It is not enabled in the Wire library, but Nick Gammon shows how to enable it in the slaves: http://www.gammon.com.au/i2c Requesting data has to be done for each slave seperately. You have to stick to the standard rules. If you can make it work, it might fail in the future if the Wire libraries is improved.

I didn't knew about broadcasting, thanks. Your source seems to be very detailled

const byte MY_ADDRESS = x;  // where x is whatever unique address you like

byte RxByte[32]  //32 byte buffer

void setup() {
  //insert unique ddress
  Wire.begin(MY_ADDRESS);

// this line allows the arduino to listen for i2c broadcast at address 0

TWAR = (MY_ADDRESS << 1) | 1;
//set up a receive handler
 Wire.onReceive(receive_data);

then call
Wire.beginTransmission (0)  //transmit broadcast so all devices will receive

Wire.write( address of destination) // make the first byte the destination

Wire.endTransmission ();

then you need a receive handler

void receive_data() {
//use a buffer to temporarily store the data

for ( int d = 0; Wire.available() > 0 ;d++){

RxByte[d] = Wire.read();} // READ WIRE BUFFER UPTO 32BYTES, INTO AN ARRAY
datareceived = 1;

//then test if it was for this device
if (RxByte[0] == MYADDRESS){ do somthing with RxBytes[1-31];}
else {}

I use this extensively its very handy and works well I have a complex transmission table which has a 4 byte header and the rest of the bytes can be used as data send
destination, myaddress, a command, and how many data bytes to follow

Addendum to Original answer. below is a complete working example.
//so the basics of the tranmission table are the first 4 bytes (ie Rx or Tx byte 0-3 depending on if we are talking about the sender or recipient)
    //are used as a header 0= recipient (0 for broadcast. or address) 1= senders address 2= is the command (ie tells the recipient what to do)
    //and 4= the number of data bytes which follow in the packet
    //not all of these need to be specified at any time but its usefull to have a structure to follow at each end which never changes
    //copy and past this upload to 2 arduinos connected by i2c change the 2 addresses and it should work.
its a n example of how data can be moved around in a multi master situation
that should hopefully give you some ideas. it looks complicated but half of it is just generating some example data and triggering method and the transmit part is repeated 3 times to send out different data.. you should be able to create a more general purpose transmit block for your application
to send data just attach a button or wire to pin 2 directly to ground
watch the 2 serial windows
#include <Wire.h>
//device address  MAKE DIFFERENT FOR EACH

const byte MY_ADDRESS = 20;
const byte PARTNER_DEVICE = 25;

// transmission table stuff
byte RxByte[32]; //setup a receive buffer to hold data
byte TxByte[32]; //setup a transmit buffer to hold data
byte datareceived;

// stuff to generate some data
const int Sensor1 = A0;
byte SensorVal1 = 0;

//stuff to debounce pin 2
const byte digitalpin = 2;
byte pinstate = 0;
byte lastpinstate = 0;
unsigned long checktime = 0;
const byte debouncetime = 50;

// timer
unsigned long timing_loop = 5000;

void setup() {
  Wire.begin (MY_ADDRESS);
  TWAR = (MY_ADDRESS << 1) | 1;                                                      // ENABLE BROADCASTS TO BE RECEIVED
  Wire.onReceive(ReceiveData);     // INTERUPT ON I2C DATA RECEIVE
  Serial.begin(9600);
  pinMode (  digitalpin  , INPUT_PULLUP );// set the pin to input pullup so we can trigger the code by connecting directly to ground
  Serial.println( "READY" );
}

void loop() {
  // generate some random data

  GenRandData();
  //Serial.print(  pinstate);Serial.print( " " );Serial.println( lastpinstate );
  // debounces pin 2 so we can trigger a data broadcast
  pinstate = digitalRead (digitalpin);
  if ( pinstate != lastpinstate && millis() >= checktime) {
    if ( pinstate == 0 && lastpinstate == 1 ) {
      checktime = millis() + debouncetime;
      Serial.println( " button working" );
      REQUEST();
    }
    lastpinstate = pinstate ;
  }

  // this triggers the process data method after receive of data
  if (datareceived == 1  ) {
    datareceived = 0 ;
    ProcessData();
  }

  // 10 second timer triggers transmission of some data
  if ( millis() >= timing_loop ) {
    BROADCAST();
  }
}
void GenRandData() {
  // this just reads analog0 and maps it to a byte then sequentially shifts the transmit buffer
  SensorVal1 = random(255);
  TxByte[7] = TxByte[6];
  TxByte[6] = TxByte[5];
  TxByte[5] = TxByte[4];
  TxByte[4] = SensorVal1;
}

void ReceiveData() {
  // READ AVAILABLE BYTES INTO 32BYTE BUFFER (while data is available)
  for ( byte d = 0; Wire.available() > 0 ; d++) {
    RxByte[d] = Wire.read();
  }
  //set a trigger event
  datareceived = 1;
  Serial.println( "receive" );
}

void ProcessData() {
  Serial.println( "process" );
  // check what the data is an who its for then do something with it (RECEIVE TABLE)
  if (RxByte[0] == MY_ADDRESS) { // for this device
    switch (RxByte[2]) {
      case 1:       Serial.print("RECEIVED DATA FOR THIS DEVICE, = "); Serial.println( RxByte[4] ); break;
      case 255:       Serial.println("RECEIVED A REQUEST FOR DATA, SENDING READ FROM  > Sensor1"  ); ActAsMaster();              break;
      default:      Serial.print("D-Type byte = error"); Serial.println(RxByte[2]);                   break;
    }
  }

  else if (RxByte[0] == 0) {       //handle broardcast
    Serial.print( "RECEIVED BROADCAST FROM DEVICE = " ); Serial.println( RxByte[1] );
    Serial.print( "DATASIZE = " ); Serial.print( RxByte[3] ); Serial.println( " Bytes" );
    Serial.print( "DATABYTE 1 = " ); Serial.println( RxByte[4] );
    Serial.print( "DATABYTE 2 = " ); Serial.println( RxByte[5] );
    Serial.print( "DATABYTE 3 = " ); Serial.println( RxByte[6] );
    Serial.print( "DATABYTE 4 = " ); Serial.println( RxByte[7] );
    Serial.println( "DONE" );
  }
  Serial.println(  );
}

void BROADCAST() {
  // this is transmission table to send data to everyone
  Serial.println("Sending broadcast");
  byte count = 0;
  byte errorcode;
Tx:
  Wire.beginTransmission (0);                       // broadcast
  Wire.write(0);                                    // ADDRESS =0 BROARDCAST
  Wire.write(MY_ADDRESS);                           // SEND my address
  Wire.write(0);                                    // DATA TYPE CODE
  Wire.write(4);                                    //number of bytes being sent
  Wire.write(TxByte[4]);                            //data
  Wire.write(TxByte[5]);                            //data
  Wire.write(TxByte[6]);                            //data
  Wire.write(TxByte[7]);                            //data
  errorcode = Wire.endTransmission ();
  if (errorcode != 0 && count <= 2) {
    count++;
    Serial.println( "fail" );
    goto Tx;
  }
  //reset timer to run this again
  timing_loop = millis() + 10000 ;
  Serial.println(  );
}

void ActAsMaster() {
  //this is transmission table to send data to specific device OR return a result of a task
  Serial.println("Sending data");
  byte count = 0;
  byte errorcode;
Tx:
  Wire.beginTransmission (RxByte[1]);               //the return address
  Wire.write(RxByte[1]);                            //recipient address (return)
  Wire.write(MY_ADDRESS);                           // SEND MASTER ADDRESS
  Wire.write(1);                                  // DATA TYPE CODE
  Wire.write(1);
  Wire.write(SensorVal1);
  errorcode = Wire.endTransmission ();
  if (errorcode != 0 && count <= 2) {
    count++;  // if fail and not exceed count try again
    Serial.println( "fail" );
    goto Tx;
  }
  Serial.println(  );

}
void REQUEST() {
  //this is transmission table to send data request of partner device
  Serial.println("Sending request");
  byte count = 0;
  byte errorcode;
Tx:
  Wire.beginTransmission (PARTNER_DEVICE);               //the return address
  Wire.write(PARTNER_DEVICE);                            //recipient address (return)
  Wire.write(MY_ADDRESS);                           // SEND MASTER ADDRESS
  Wire.write(255);                                  // DATA TYPE CODE (MASTER ADDRESS)
  Wire.write(0);
  errorcode = Wire.endTransmission ();
  if (errorcode != 0 && count <= 2) {
    count++;  // if fail and not exceed count try again
    Serial.println( "fail" );
    goto Tx;
  }
  Serial.println(  );
}

i tried to keep it minimal but still show complete capability.. i guess im not very good at minimal.

//so the basics of the tranmission table  - are you writing code, or answering a question?

just trying to clearly explain whats going on.. this code is just a massively edited piece of a major project so it was significantly  easier to quickly assemble this than try to explain an answer..  after previous comment >>Please, post a minimal but complete sketch that compile OK. Your code is confusing for beginners, because it mix free text with code and have code not inside any function (like loop). – Look Alterno yesterday<<

thanks for detailled example. My code is the same like the first example code and works. I have to test the second example. But i dont see any software colision prevention. I would prefer to ignore collided and corupted frames just by a "software master", also there will be a changeable master, which will check communication and if there is collision than will try to fix it. Actually any software solution is better than a third line for me.

i havent done anything with collision detection and correcting in software as my hardware solution prevents it but this part >>errorcode = Wire.endTransmission ();
if (errorcode != 0 && count <= 2) {
count++;  // if fail and not exceed count try again
Serial.println( "fail" );
goto Tx;
} should at least try to make sure the packet is delivered as its probably unlikely for the collision to happen 3 times.

1 thing you could do here is use a couple mS delay if a collision occurs maybe using the address as means of making it different on each device(i use that for something else, works great) switching who is (official) master is easy just broadcast a specific message with the new master device address and have them all save that to memory for later use, or enable special functions


text:
Problem with uploading my sketch to my Arduino
I chose the correct COM port but it won't upload.
Arduino: 1.8.3 (Windows 10), Board: "Arduino Leonardo"
Sketch uses 5252 bytes (18%) of program storage space. Maximum is 28672 bytes.
Global variables use 228 bytes (8%) of dynamic memory, leaving 2332 bytes for local variables. Maximum is 2560 bytes.
processing.app.debug.RunnerException
    at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:160)
    at cc.arduino.UploaderUtils.upload(UploaderUtils.java:78)
    at processing.app.SketchController.upload(SketchController.java:713)
    at processing.app.SketchController.exportApplet(SketchController.java:686)
    at processing.app.Editor$DefaultExportHandler.run(Editor.java:2149)
    at java.lang.Thread.run(Thread.java:745)
Caused by: processing.app.SerialException: Error touching serial port 'COM4'.
    at processing.app.Serial.touchForCDCReset(Serial.java:99)
    at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:144)
    ... 5 more
Caused by: jssc.SerialPortException: Port name - COM4; Method name - openPort(); Exception type - Port busy.
    at jssc.SerialPort.openPort(SerialPort.java:164)
    at processing.app.Serial.touchForCDCReset(Serial.java:93)
    ... 6 more
An error occurred while uploading the sketch
Exception in thread "Thread-124" java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
    at java.util.ArrayList$Itr.next(ArrayList.java:851)
    at cc.arduino.contributions.libraries.LibrariesIndexer.rescanLibraries(LibrariesIndexer.java:123)
    at cc.arduino.contributions.libraries.LibrariesIndexer.setLibrariesFolders(LibrariesIndexer.java:106)
    at processing.app.BaseNoGui.onBoardOrPortChange(BaseNoGui.java:682)
    at processing.app.Base.onBoardOrPortChange(Base.java:1297)
    at processing.app.Editor$DefaultExportHandler.run(Editor.java:2179)
    at java.lang.Thread.run(Thread.java:745)

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

You tagged the question "Arduino-Nano" but said you have a Leonardo. Which is it?

did you find anything on this? i have a similar issue with an arduino nano 33 ble sense. it reccently rrived from pihut, but i can send it back if its the device. The drivers are uptodate. dont have another micro-usb cable that is used for data transfer, as most of the cables only support power. if anone found the solution, please update me !!

I had the same problem. try checking the crystal on your arduino

This is the relevant bit in your error output:
Caused by: jssc.SerialPortException: Port name - COM4; Method name - openPort(); Exception type - Port busy.

Is your Leonardo on COM4, or some other port? Does some other program have that port open?

Yes I now  it is a nono and not a Leonardo. I have trieyd with nono sketches and thers the same problem.

It doesn't really matter if it's a Leonardo or Nano -- the problem is that the Arduino application can't open COM4. Is the device you are programming on COM4? Is there any other application opening COM4?

I don't see any trivial solution from the error log, but you can try one or more of the following items:

Unplug and replug the USB cable (to check if the connection is ok)
Change your USB cable in another USB port from your computer
Restart computer
Change USB cable
Try another Arduino (if you have two megas, or change to Uno if possible), just to check for uploading
Reinstall Arduino

I install arduino on another device and same error happend. I haven't a other cabel or a arduino.

I found a new cabel ant it wont work. Weeks ago i have the same problem with an other nano. I think my  settings are incorect.

If you remove the Arduino, see you that COM4 is not in use anymore? And when you reconnect COM4 shows up again?

Yes. after remove com4 disappear. Plug in again an it shows me com 4

Than you can be sure the Arduino is on COM4. If your settings are incorrect, try to reinstall the IDE.


text:
Stopping motor DC with 2 limit switches
I try to build an automatic roof with rain sensor input, when it's rain the roof then closed pulled by DC motor on the tracks and activate a buzzer. When it reach the end (limit switch pressed) then the motor stopped and buzzer off. And when the rain stopped, motor will turning again to open the roof until the second limit switch pressed to stop the DC motor.
I have try to make my own program but it have an error, when it's has no rain detected the motor spin to close the roof and stop when limit switch pressed (LOW logic), but when rain detected the buzzer turned on but the motor doesn't spin at all. Here is my code, I'm using L293D for motor driver and using its enable pin.
void setup() {
  digitalWrite(enable_motor, HIGH);
  digitalWrite(motor_open, LOW);
  digitalWrite(motor_close, LOW);
  digitalWrite(alarm, LOW);
}

void loop() {
  if (analogRead(rainSensor) < 650){
    digitalWrite(alarm, HIGH);
    digitalWrite(motor_close, HIGH);
    digitalWrite(motor_open, LOW);
  }
  else if (digitalRead(stop_close) == LOW){
    digitalWrite(alarm, LOW);
    digitalWrite(enable_motor, LOW);
  }
  else if (analogRead(rainSensor) > 850){
    digitalWrite(alarm, LOW);
    digitalWrite(motor_close, LOW);
    digitalWrite(motor_open, HIGH);
  }
  else if (digitalRead(stop_open) == LOW){
    digitalWrite(alarm, LOW);
    digitalWrite(enable_motor, LOW);
  }
  else {
    digitalWrite(enable_motor, HIGH);
    digitalWrite(alarm, LOW);
  }
}

Can I use If-Else logic? Or I make a mistake?

Your logic is a bit off. For example, when it is raining and rainSensor < 650, only that part of the if gets executed and the else if parts never happen.
You could just wait for the roof to open/close in a loop. Also, you will find it helpful to break your code into smaller functions. (I'm not sure what the enable_motor pin is for, so that part may need fixing).
// This function determines the current status of the roof
enum {OPEN, CLOSED, OPENING, CLOSING, UNKNOWN};
byte get_roof_status()
{
    if (digitalRead(stop_close) == LOW) return CLOSED;
    else if (digitalRead(stop_open) == LOW) return OPEN; // Fixed typo
    else if (digitalRead(motor_open) == HIGH) return OPENING;
    else if (digitalRead(motor_close) == HIGH) return CLOSING;
    return UNKNOWN;
}

// Helper functions
void open_roof() {
    digitalWrite(alarm, HIGH);
    digitalWrite(enable_motor, HIGH);
    digitalWrite(motor_close, LOW);
    digitalWrite(motor_open, HIGH);
    // Loop until roof is open
    while (OPEN != get_roof_status()) /* NULL */;
    stop();
}
void close_roof() {
    digitalWrite(alarm, HIGH);
    digitalWrite(enable_motor, HIGH);
    digitalWrite(motor_open, LOW);
    digitalWrite(motor_close, HIGH);
    // Loop until roof is closed
    while (CLOSED != get_roof_status()) /* NULL */;
    stop();
}
void stop() {
    digitalWrite(alarm, LOW);
    digitalWrite(enable_motor, LOW);
    digitalWrite(motor_open, LOW);
    digitalWrite(motor_close, LOW);
}

void setup() {
  // Set the pinmodes
  pinMode(enable_motor, OUTPUT);
  pinMode(motor_open, OUTPUT);
  pinMode(motor_close, OUTPUT);
  pinMode(stop_close, INPUT_PULLUP);
  pinMode(stop_open, INPUT_PULLUP);
  pinMode(alarm, OUTPUT);

  digitalWrite(enable_motor, HIGH);
  digitalWrite(motor_open, LOW);
  digitalWrite(motor_close, LOW);
  digitalWrite(alarm, LOW);
}

void loop() {
  // This function is much simpler now
  if (analogRead(rainSensor) < 650) {
    close_roof();
  }
  else if (analogRead(rainSensor) > 850){
    open_roof();
  }
}

enable_motor is for enabling two input in L293D because I use its enable pin. I have try using your code structure, it works for opening the roof, but when motor start to spin for closing the roof and it hit the limit switch it suddenly reversing the motor spin and back to open the roof. Did I missed something?

There was a typo in get_roof_status() and the enable_motor logic was reversed. I've fixed these issues. I don't have any spare motors laying around but I do have some L293D chips. I simulated this (with LEDs and push buttons) and it seems to work.


text:
can we use Lm317 1.25 ref for ext. reference of arduino
I m trying to give ext ref. To Arduino using lm317 1.25 ref.
I  tried to do it. Iswt this voltage in programme too
But when I run it it was just displaying 1.25
And der was no variation as I varie the resistance of potentiometer which is connected to A0
So plz help me.....
My Arduino chip is Atmega 8A

Please post your code, and also your schematic. As it is your question doesn't make a lot of sense. See how to ask a good question.

yes but you have to use the analogReference(EXTERNAL); command otherwise it will short the default VCCref volatage with the external (i assume this will cause damage.. dunno never done that. yet...)
also if you use a 1.25v reference just remember that that will be the maximum voltage you can measure up to.
theres a couple of things you can do
1 use a voltage devider circuit to drop the max voltage out of your sensor(potentiometer) down to about 1.25v
2 put a series resistor betweent vcc and the positive terminal of your potentiometer (creating a voltage devider between the resistor and the full resistance of the potentiometer)
3 and probably the easiest connect the positive of the potentiometer to the lm317 /reference pin so that its output will be between Aref and GND this is the best option as it will be the most stable as its output will be in propotion to any fluctuation of the lm317
as in 3. the same can be done if using the internal Vref conect the pot to Aref (but remember that it has a limited current output so be carefull not to draw too much by using low resistance pots or many in parallel)

Kk i tried it. But the thing is I came to know my adc is not working means all the 6 pins.

The are always giving 1023 for any value . I tried also a basic programme of potentiometer but the thing is even there it was giving maximum value.....plz is there a solution for this. I also saw dat d aref pin is not shorted anywhere.

please post the relevant portion/s of your code for pot reading and void setup and variables. enough to compile please cheers