text:
Issues using HC-06 Bluetooth module with arduino
I recently ordered an HC-06 Bluetooth module for my Arduino Uno, and after watching this video, and many others, I still have been having many issues figuring out how to get it to work, and some questions for how the code receives and reads serial data from my phone.

I assume this wiring is correct, right?

Rx  > Tx
Tx  > Rx
Gnd > Gnd
Vcc > 3.3V

When I sent a command over the Bluetooth terminal app I have, the serial monitor displays that command over and over, I assume that is correct also?
How do I read the serial input? I've been using
if(Serial.available() > 0)
        phoneInput = (char) Serial.read();

and then displaying the value of phoneInput to the serial monitor, but for some reason I can't seem to have it control anything properly (in this case an LED)
What datatype is the Serial.read() returning to my variable before I cast char on to it?
I get errors uploading the code to the board (avrdude: stk500_recv(): programmer is not responding), until I remove the pin connected to the Rx on the arduino, is there a cleaner solution to uploading the board without unplugging wires?

I had follow this tutorial and problem fixed: Tutorial Configure HC-06 Bluetooth Module using AT Command

I assume this wiring is correct, right?
Rx > Tx
Tx > Rx
Gnd > Gnd
Vcc > 3.3V

Almost. The Arduino's TX should be reduced to 3.3V using a 10k/20k potential divider.

How do I read the serial input? I've been using
if(Serial.available() > 0)
       phoneInput = (char) Serial.read();

You should read and digest this.

What datatype is the Serial.read() returning to my variable before I cast char on to it?

An integer. It holds either 0-255 representing the ASCII code for a character, or -1 if there is nothing in the buffer to read.

I get errors uploading the code to the board (avrdude: stk500_recv(): programmer is not responding), until I remove the pin connected to the Rx on the arduino, is there a cleaner solution to uploading the board without unplugging wires?

That will be because you are using pins 0/1 to communicate with the bluetooth which you can't do because those are used to communicate with the PC.

I'm away from my computer so I can't test your answers, but thanks so much, your answers were super helpful, but I do have one question; If I shouldn't use pins 0 and 1 as Rx and Tx, what pins should I use?

Anything else - I assume you're using SoftwareSerial - that library is designed to use any pin except 0/1. You use Serial for pins 0/1. There seems to be a number of tutorials (videos?) around that show SoftwareSerial being incorrectly used with pins 0/1.


text:
Creating a library of C++ classes for Arduino; How to #include "Arduino.h", "WProgram.h"?
I've written 6 C++ classes on the CLion IDE to be used on Arduino. One of these classes uses a C++ library called "Adafruit_PWMServoDriver.cpp" provided by Adafruit to use the PWM driver they sell. I'm trying to test my code in a main.cpp, but upon building my code, I noticed that "Adafruit_PWMServoDriver.cpp" has the following code:
#if ARDUINO >= 100
 #include "Arduino.h"
#else
 #include "WProgram.h"
#endif

Naturally, I copied Arduino.h from the Arduino installation folder to my C++ project header directory. But for reasons I don't know, ARDUINO is apparently not greater than or equal to 100, so it attempts to include "WProgram.h." Because I cannot find this header file, I changed my code to only attempt to include Arduino.h.
#if ARDUINO >= 100
 #include "Arduino.h"
#else
 #include "Arduino.h"
#endif

However, Arduino.h itself includes several header files, and I am not sure where I can find all the find them, or if it is even necessary to try to do so. I need to get my test code running, so I don't want to directly test it in the Arduino IDE yet. What can I do to overcome #include Arduino.h and #include WProgram.h?

I guess that you are not using the Arduino build. Could you describe your IDE and compiler setup. Looks like you need to configure CLion with a path to the Arduino core files.

I am using CLion. Environment: MinGW-w64 (w64 5.0), CMake: 3.6.3, C++ compiler: C:\msys64\mingw64\bin\g++.exe. I've actually managed to find all the header files from the avr library and placed them in my project directory. However, now I am running into compatibility issues in the avr library files. As of now, the compiler can find all 3 avr header files that I've placed in my \include directory, which is correctly imported in my CMake. However, in my io.h file, there is a long list of #if defined (AVR<various_names>_).

I assume this is to identify the type of device I am using, and it only expects different types of Arduino. However, I am currently working in CLion; therefore, it reaches the end of this list and the following code executes: #else
if !defined(COMPILING_AVR_LIBC)
warning "device type not defined"
endif
#endif
How can I make my coding environment compatible with the Arduino setup? Or can I avoid all this and somehow create C++ classes independently?

You need to set the correct MCU define. Please see the Arduino-Makefile for an example. Or run the Arduino IDE and look at the compiler parameters.

The libraries from Adafruit and elsewhere assume you are using the Arduino IDE. If you choose not to use that you will have difficulties compiling your own code. The header files you ask about are in the IDE download. You can always grab a copy of that and put the appropriate .h files into your "include" search path.

However, in my io.h file, there is a long list of #if defined (AVR_various_names).

Well, do a test compile using the Arduino IDE, using "verbose compiling" and see what defines are generated for your particular board (which you haven't mentioned). There won't be that many of them. Then you can put that on the build commands for your IDE.

Or can I avoid all this and somehow create C++ classes independently?

You can create C++ classes inside the Arduino IDE. I don't see how this relates to your other issues.

The Arduino IDE basically generates build commands for avr-g++ - it isn't some horrible beast you should avoid using.

The #if defined (AVR_<various_names>) you see here have nothing to do
with Arduino: this is the avr-libc trying to import the IO register
definitions for the AVR chip you are using. Whenever you compile an AVR
program, you pass the option -mmcu=<mcu-name> to avr-gcc, and it
automatically defines the proper macro. For example, the Arduino Uno is
built around an ATmega328P. Programs for the Uno must then be compiled
with -mmcu=atmega328p, which makes the compiler define
__AVR_ATmega328P__, which directs the avr-libc to
#include <avr/iom328p.h>, which contains all the IO register
definitions for that chip.
As for the ARDUINO macro, this one is defined by the Arduino IDE to be
the version of you Arduino installation, without the dots. For example,
if you downloaded the core files from Arduino 1.8.2, then you should
compile with -DARDUINO=182.
Also, you should avoid copying all the library headers to your project,
and instead use the proper -I options. And don't forget to tell the
compiler your clock frequency with -DF_CPU=..., as it is needed by
some avr-libc and Arduino stuff.
In the end, you will see you need quite a lot of compiler options to
properly compile Arduino code. The easiest way to do it is definitely to
use the Arduino IDE, as it handles all this for you. If you don't like
the IDE (understandable...), you could try Arduino
Builder, which should be
entirely compatible. If you want to compile from just a Makefile, I
recommend you take a look at Sudar Muthu’s Arduino
Makefile.

source: Stack Exchange

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

sort: votes


text:
Why is my code only reading the change of the encoder's pin A?
I am writing code for reading in a quadrature encoder. I used attachInterrupt on pin 2 and 3, but by using the same ISR.
    int encAPin= 2;
    int encBPin= 3;
    volatile int encAValue= 0;
    volatile int encBValue= 0;
    volatile int encCount= 0;

    void setup() {
      // put your setup code here, to run once:
      pinMode(encAPin, INPUT);
      pinMode(encBPin, INPUT);
      attachInterrupt(digitalPinToInterrupt(encAPin),encUpdate, CHANGE);
      attachInterrupt(digitalPinToInterrupt(encBPin),encUpdate, CHANGE);
      Serial.begin(9600);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      Serial.println(encCount);
    }

    void encUpdate() {
      if(digitalRead(encAPin)==RISING){
        if(digitalRead(encBPin)==LOW){
          encCount++;
        }else if(digitalRead(encBPin)==HIGH){
          encCount--;
        }
      }
      if(digitalRead(encAPin)==HIGH){
        if(digitalRead(encBPin)==RISING){
          encCount++;
        }else if(digitalRead(encBPin)==FALLING){
          encCount--;
        }
      }
      if(digitalRead(encAPin)==FALLING){
        if(digitalRead(encBPin)==HIGH){
          encCount++;
        }else if(digitalRead(encBPin)==LOW){
          encCount--;
        }
      }
      if(digitalRead(encAPin)==LOW){
        if(digitalRead(encBPin)==FALLING){
          encCount++;
        }else if(digitalRead(encBPin)==RISING){
          encCount--;
        }
      }
    }

When I tried Serial.print to check whether or not the pin A's and B's inputs were changing, I noticed that only pin A's (pin 2) input was changing. I made sure that the circuit and the wiring were all correct. Is there something about my code that is not reading pin B's input properly?

What's this? if(digitalRead(encAPin)==RISING) - that doesn't make any sense. It is either HIGH or LOW.

I apologize. I was merely following my notes, and it indicated that there are 8 cases for the input graphs of pin A and B. Thank you.

I think you have mixed up interrupts and pin reading.  A digital pin will only ever he HIGH or LOW, The attachInteruppt() function takes a wider variety of states (I don't know if CHANGE and RISING are valid).

There are only 4 states that a pair of pins can be in. That is, 2² - 2 states (HIGH and LOW), and ² pins.

You're confusing interrupt events and pin states here.
A pin can be either HIGH or LOW. Never anything else.
An interrupt can trigger on one of four events:

The pin transitions from HIGH to LOW (FALLING)
The pin transitions from LOW to HIGH (RISING)
The pin transitions from one state to another (CHANGE)
The pin remains low (LOW)

Your code should be (as you have done) attaching the interrupt to the pins using CHANGE so you can see any change in the state of the pins.
Your interrupt code should then examine the two pins to see their current state.
But there is one bit missing from your code, and that is what was the state before this interrupt triggered? - i.e., from what did the pins change from to get to this state?
The simplest way of coding this kind of thing is to think of each pin as a bit in a 2-bit binary number. Join the two pins together to form a number between 0 and 3:
uint8_t pinVal = (digitalRead(encBPin) << 1) | digitalRead(encAPin);

The truth table for that would be:
B | A | B<<1 | pinVal
0 | 0 |  00  |   00 (0)
0 | 1 |  00  |   01 (1)
1 | 0 |  10  |   10 (2)
1 | 1 |  10  |   11 (3)

There you have 4 states. And if you remember that state from one interrupt call to the next, you can compare the current value to the previous value. And that is where you get your 8 states from.  Encoders use Gray Code so the sequence of numbers you would get as you rotate the encoder would be:
0, 1, 3, 2, 0, 1, 3, 2 ...

Or the other way:
2, 3, 1, 0, 2, 3, 1, 0 ...

And it's the transition between those values that tells you what the encoder is doing:
0 <-> 1 <-> 3 <-> 2 <-> 0 ...

Each of those transitions can go two ways, and if you count the arrows (< and >) there are 8 of them there, which are the 8 states you were thinking of before.
So if the previous value is stored in oldVal from the last time the interrupt triggered, and the new value is in newVal, your 8 states are:

oldVal == 0 && newVal == 1
oldVal == 1 && newVal == 3
oldVal == 3 && newVal == 2
oldVal == 2 && newVal == 0
oldVal == 0 && newVal == 2
oldVal == 2 && newVal == 3
oldVal == 3 && newVal == 1
oldVal == 1 && newVal == 0

The first four are progressing in one direction, the last four in the other - one set is clockwise, one is anti-clockwise.
So you could have an (untested) interrupt handler that looks something like this:
void encUpdate() {
    static uint8_t oldVal = 0; // Static variable to remember the last state
    uint8_t newVal = (digitalRead(encBPin)) << 1 | digitalRead(encAPin);

    if (
        (oldVal == 0 && newVal == 1) ||
        (oldVal == 1 && newVal == 3) ||
        (oldVal == 3 && newVal == 2) ||
        (oldVal == 2 && newVal == 0)) {
            encCount++;
    } else {
        encCount--;
    }
    oldVal = newVal;
}

You notice I've only implemented the comparison for the first four states and not the last four. Since there are only 8 states, and those states cause one of only two things to happen, if it's not one of the first four states, which would increase your count, it must then be one of the last four states which decrease your count. No point in checking for them since it can't be anything else.  If you turned it clockwise then increase the value. Otherwise you must have turned it anti-clockwise since there is no other direction you can possibly turn it in, so decrease the count.
This is precisely why Gray Code is used - only one pin ever changes at a time, so there is no ambiguity in what has happened - either you turned it one code-point in one direction or you turned it one code-point in the other. Even if there is lots of bounce it will just bounce between two neighbouring code-points and settle on the final new code point (as long as the interrupt can react fast enough to catch all the bounces).

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


text:
What kind of control method in my code will allow me to control multiple servos with phase shifts
I am building a quadruped robot, and I need to keep all four legs moving continuously and out of phase with respect to each other to produce a smooth gait and to prevent falling over. I wish to achieve this with 4 sets of 2 motors. Each set will move in the same way but not in sync. I have an Adafruit 16-Channel 12-bit PWM/Servo Driver - I2C interface - PCA9685 for this application. I have considered several implementations; delay () would be a poor choice because of the obvious delay between the current and next step in the gait cycle. I am also considering using ISR that will trigger when a certain time period passes, an estimated time to reach the desired position for example, but the interrupt method would not be much better than delay (). Another idea I have is to create a class that will receive the next position to move to for each leg and will continuously send the signal to the PWM driver. However, timing this would require some trial and error. Is there a conmon well-known method to send control signals with phase shifts?

One way could be to use PID controllers and a state machine.


text:
Trying to explain strange behavior when attempting to do a digitalWrite to A7 on a pro mini?
I found out the hard way today that pins A6 and A7 can't be used as digital outputs, but what actually happens when you try to read/write them?
Some backstory: I soldered some headers onto a pro mini and I wanted to test all the pins to make sure they worked.  I wrote a test program that looped through all the digital pins once a second and toggled their state by doing digitalWrite(pin, !digitalRead(pin);.  I then added a second loop that went through pins A0 through A7 and toggled them using the same method.  After adding this loop the built in LED on pin 13 no longer toggled on and off every second.  Instead, it would just flicker on very briefly.  At first I assumed there was something wrong with my loops (like an off by one) that was causing the strange issue, so I completely rewrote things to use a single loop that iterated over all the pins.  The resulting code should have been effectively equivalent to the original code, but now pin 13's LED was toggling properly again.
After much experimenting, I was able to whittle it down to the following test program to demonstrate the strangeness:
#define WORKS_CORRECTLY 1

int pins[] = {13, A7};
#define SIZE (sizeof(pins) / sizeof(int))

void setup()
{
#if WORKS_CORRECTLY
    for(int i = 0; i < SIZE; i++)
        pinMode(pins[i], OUTPUT);
#else
        pinMode(pins[0], OUTPUT);
        pinMode(pins[1], OUTPUT);
#endif
}

void loop()
{
    for(int i = 0; i < SIZE; i++)
    {
        int pin = pins[i];
        int pinVal = digitalRead(pin);
        digitalWrite(pin, !pinVal);
    }

    delay(1000);
}

With WORKS_CORRECTLY defined as 1 the LED on pin 13 toggles state every second like one would expect.  With it defined as 0, however, it just flickers on very briefly every second.  This is very perplexing.
Ultimately the answer is to not try to do a digitalWrite to A7 (or A6), but I'd like to understand why the behavior changes based on seemingly irrelevant differences.

You are calling digitalWrite and digitalRead with argument A7.
According to the file pins_arduino.h, A7 is defined as 21.
Now, the two functions are defined in file wiring_digital.c, and the most important part is that both of them use this code to understand which register and bit to use:
uint8_t bit = digitalPinToBitMask(pin);
uint8_t port = digitalPinToPort(pin);

Those two are not functions, but macros defined in the Arduino.h file:
#define digitalPinToPort(P) ( pgm_read_byte( digital_pin_to_port_PGM + (P) ) )
#define digitalPinToBitMask(P) ( pgm_read_byte( digital_pin_to_bit_mask_PGM + (P) ) )

This means that the positions are stored into two arrays, and each pin data is an offset from the beginning of the array itself. This means that the pin 0 is located on register digital_pin_to_port_PGM[0] (i.e. port D) and is in position digital_pin_to_bit_mask_PGM[0] (so bit 0).
Now, what about pin A7? It is in index 21. But look at the file pins_arduino.h:
const uint8_t PROGMEM digital_pin_to_port_PGM[] = {
    PD, /* 0 */
    PD,
    PD,
    PD,
    PD,
    PD,
    PD,
    PD,
    PB, /* 8 */
    PB,
    PB,
    PB,
    PB,
    PB,
    PC, /* 14 */
    PC,
    PC,
    PC,
    PC,
    PC,
};

The array has only 20 entries! This means that A6 and A7 are NOT mapped. When you call the function with A7, you are going beyond the array limits.
This means that this leads to an unexpected behavior. In THIS particular case you are getting
PORT: _BV(1) = 2 which is equal to PB in Arduino.h
BIT: NOT_ON_TIMER = 0

So when you read from bit A7 you will check for
*portInputRegister(port) & bit
*portInputRegister(PB) & 0 => 0 for every value

so it always reads a LOW.
When you write any value to it, you will apply this code:
if (val == LOW) {
    *out &= ~bit;
} else {
    *out |= bit;
}

bit is always 0, so if you write a LOW value you will write a HIGH on ALL bits connected to port B, otherwise you will write a LOW on all of them.
Different is the access to A6: the port will be mapped to 0, which is translated to NOT_A_PORT when detecting the register. This will try to read and write from/to register #0, which I admit I do not know what means. According to the ATMEGA328P register map it is reserved, so better not to use it.
Short answer: never try to use values which are not supposed to be used, otherwise you will incur in strange behaviors

Somehow it didn't occur to me to go digging through the arduino source code.  Thanks for the very quick and detailed answer and apologies for the delay in accepting it.

@Pak Well, you accepted it so.. thank you to take the time to come back and accept it ;)

pins A6 and A7 can't be used as digital outputs.

that shows the importance of reading the datasheet (and the schematic): there is no port / pins associated ADC6/A6 and ADC7/A7 on the chip. Absolutely no way of writing to / reading from those pins digitally.
None whatsoever.


text:
What are devices in this picture?
I don't know the name of those. Please advise me.
Thanks very much.

Post a link to the video you took the screenshot from.

The things on the right are just terminal blocks.

Wires? Pins? Connectors? What has this to do with Arduinos?

The left item looks like some Arduino clone with custom connectors. The right hand item looks like a scale model of a J Class Freighter.

oh, thanks all.
@Mark Smith: it's terminal blocks :D

Item all the way to the right are these Excellway ET25 2/3/5 Pins Spring Terminal Block Electric Cable Wire Connectors

It's a Seeeduino Lotus (or a clone of it).


text:
Problem with PWM interference
I have a following code
  #include <Servo.h> //library for servo drive
  int MotorAPinA = 9;   //pin number for DC drive
  int MotorAPinB = 10;  //pin number for DC drive
  Servo myservo; //create object myservo, class servo from Servo library

void setup() {
  // put your setup code here, to run once:
  pinMode(MotorAPinA, OUTPUT);
  pinMode(MotorAPinB, OUTPUT);
  //myservo.attach(6); //pin number for servo output
  myservo.write(65);
}

void loop() {
  analogWrite(MotorAPinA, 240);
}

This very code works only partly.
If I comment line
myservo.attach(6)

then I got my DC drive working.
If I uncomment this line, my Servo goings crazy (effect looks like myservo.write(0) constantly), until I comment line
analogWrite(MotorAPinA, 240);

and then I got my servo working properly.
While myservo.attach(6) is uncommented, DC drive doesn't work (with uncommented analogWrite).
So, basically, I can have or PWM or Servo working simultaneously, but not both
Any ideas? Arduino Uno R3, Arduino 1.8.1.

Well, your PWM outputs are both on 16b Timer/Counter 1 and the servo is attached to the 8b Timer/Counter 0. So my guess is that 8bit counter has too low resolution for driving the servo and it uses Timer/Counter 1 in full 16b mode for better precision instead (PWM uses just 8bits from 16). Also Timer/Counter 0 is used for counting millis, so its settings can't be changed anyway.
For the confirmation you can either:

use pins 5 and 6 (TC0) or/and pins 3 and 11 (TC2) and for the servo use pin 9 or 10
You can read the values of TC1 configuration registers and according to the datasheet you can figure out what mode is currently used.

EDIT:
So on the Uno board is used Timer/Counter 1 for timing purposes:
  if(timer == _timer1) {
    TCCR1A = 0;             // normal counting mode
    TCCR1B = _BV(CS11);     // set prescaler of 8
    TCNT1 = 0;              // clear the timer count
    TIFR |= _BV(OCF1A);      // clear any pending interrupts;
    TIMSK |=  _BV(OCIE1A) ;  // enable the output compare interrupt
    timerAttach(TIMER1OUTCOMPAREA_INT, Timer1Service);
  }

So no PWM on the OC1A nor OC1B in normal mode and the channel A is taken by Servo.

`
#include <Servo.h> //library for servo drive
int MotorAPinA = 6;   //pin number for DC drive
int MotorAPinB = 5;  //pin number for DC drive
Servo myservo; //create object myservo, class servo from Servo library
void setup() {
// put your setup code here, to run once:
pinMode(MotorAPinA, OUTPUT);
pinMode(MotorAPinB, OUTPUT);
myservo.attach(9); //pin number for servo output
myservo.write(65);
}
void loop() {
analogWrite(MotorAPinA, 240);
//analogWrite(MotorAPinB, 0);
}
`
somehow `` doesn't code code

Now it works. Servo on Timer/Counter1 16 bit (10 and 9 pins), PWMs on Timer/Counter0 0 bit (6 and 5 pins), and there are still free 11 and 3 pins of Timer/Counter2


text:
How to communicate from Python to Arduino Softserial
That is driving me nuts so I need your help.
Master : PC with Ubuntu, a USB to serial converter (chipset CP2102), connected to Arduino Uno Pin 10, 11 and GND. The Arduino Uno is plugged in the same PC.
Port for the converter is /dev/ttyUSB1
Port for the Arduino is /dev/ACM0
I tried to communicate by Serial through the converter (I do not want to use ACM0 as it is buggy and sometimes suddenly change to ACM1, messing up my big testing program).
On Arduino side :
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11);
int inByte = 0;         // incoming serial byte

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

void loop() {
  if (mySerial.available()) {
    char inByte = mySerial.read();
    mySerial.println(inByte);
    Serial.println(inByte);
  }
  delay(10);
}

The Python script (simple one to debug)
import serial
arduino = serial.Serial('/dev/ttyUSB1', 9600)
arduino.timeout=0.5
arduino.bytesize=8
arduino.stopbits=1
code=49 #ASCII Code for 1
arduino.write(chr(code).encode('utf-8'))
print(chr(code))
print(chr(code).encode('utf-8'))
print(arduino.readline())
print("done")
arduino.close()

When I run it, I have on Arduino Serial monitor a g
and Python script output
1
b'1'
b'Ly\x00'
done

By the way, the very same code over /dev/ttyACM0 and standard serial rather than Softwareserial works perfectly (as long as the port remains ACM0 of course)

That is all me, look for an answer for ages, finally post a question, to end up finding the answer in the following hour...
this is because Arduino takes TTL as input and not RS-232...
similar here :
https://electronics.stackexchange.com/questions/42584/arduino-uno-weird-characters-sent-to-com-softwareserial


text:
Can anyone recommend a breadboard for the new Arduino 101?
I just got an Arduino 101 board. I was told that it's practically the same as the UNO. But have no experience using the UNO and I've only done super simple things on the 101 board without using a bread board.
What I want to do is have 2 servos connect to the board. I've only connected one servo without using a breadboard. I've looked on Instructables.com and other places that connect at least 2 to up most 12 servos. They all use different breadboards without specify if the brand, model, or if size even matters. I don't know how breadboards work and which holes I plug the wires into. Furthermore, I haven't found any videos on people working on the 101 board.
Next, I'm not sure if the servos will share the same volt port. There's only 3V and 5V on my Arduino 101 board. If they all need 5V, I'm not sure how to make both servos share. I don't know how they will share the same ground port as well. I know for sure, they will have their own analog port.
A list of recommendations would be nice. Thanks.

Although you will find tutorials which unwisely do so, you really should not power servos from any sort of Arduino.  Servos are nasty motor loads, which should have their own supply that is not an Arduino or the computer that is connected to.  They they need a common ground with the Arduino and signal from it.

I personally prefer the big breadboards that have two sets of terminals for power at the top. The tiny boards tend to get claustrophobic for me. Should have bought one big to begin with instead of the ones that are supercompact. Good for tiny (chinese) fingers though ... I just unravelled a mystery.

@user400344 however (probably) unintentional Good for tiny (chinese) fingers though sounds a little racist (depending on how you view it).

@junerockwell Sparkfun has a pretty neat tutorial on breadboards (https://learn.sparkfun.com/tutorials/how-to-use-a-breadboard). But as Chris Stratton suggest, it's highly advised to separate power lines from control lines.

It's only a matter of personal preference. I am quite happy with the standard 830-point layout, but there are many larger and nicer models.

A breadboard is nothing but a way to attach multiple wires to the same pins. There are many different kinds as can be seen in these images. There's no right or wrong when it comes to breadboards, as long as you have enough pins to prototype you should be good to go.

I agree to "A breadboard is nothing but a way to attach multiple wires to the same pins.", but just one recommendation for the breadboard. Don't buy the ones without the rails for voltage and ground, they are useful.

authors: Кузьма Феськов


text:
From Arduino to a miniaturized circuit
I have a project made with Arduino, and I want to replace it by a miniaturized circuit with just a microcontroller. Is there any tutorial that can guide me in doing this? Any reference is wellcome. Thank you!

This can be a useful exercise, though unless you need to incorporate other components it may be worth considering a cheap premade miniature Arduino clone PCB rather than a DIY effort.

I found that the Arduino Pro Mini might actually be smaller than a ATMega328P DIP (with external reset button, LED's, power circuit and cyrstal). Look how tiny it is :D https://i.ytimg.com/vi/SV32k9gCvik/maxresdefault.jpg

You can use an Arduino on a breadboard to get you going. From the breadboard, you can then develop a circuit on a pre-made PCB like this:

Then to a custom PCB, if you so desire.

you can also your m328p-less uno as a serial programmer, if you don't use the hardware serial already

The main question is: Which features do you want to have on your board?
You can start off with the design files of the Arduino board you are using: update what you need (and don't need).
Then, for the manufacturing itself, several approaches will work:

veroboard & through hole components. Not very practical, not small, but easy;
DIY manufacturing: toner transfer method, or if you have a CNC, isolation milling;
Boardhouse (e.g. PCB manufacturer) to whom you send your finished design to have it manufactured.

An alternative would be to use a smaller board, like an Arduino nano: it all depends on what your constraints/goals are.


text:
Timer with ajustable time delay
I have a led strip, and each led should be turned on sequentially, such as this one:
[http://1.bp.blogspot.com/-CTT6yvYtdos/VihhhBItwjI/AAAAAAAAAvM/q1jbUylMMdM/s400/ezgif.com-video-to-gif.gif][1]
The time delay between 2 consecutive leds is ts, and that time should be adjusted externally through a pushbutton switch. Each time the button is pressed, the time period shoud increment in a fixed amount.
I've already used the timerOne library, but it just works with a fixed time delay ts. How can I solve this issue with VARIABLE time delay?
I prefer to use interruptions rather than polling, since this system will be more complex (other buttons and variables will be involved).
Thanks!
Fernando

Re “the timerOne library [...] just works with a fixed time delay”: what makes you believe that?

https://github.com/PaulStoffregen/TimerOne/blob/master/TimerOne.h#L55
Defines the function in TimerOne called SetPeriod(). That will change the period.

I've found the solution, through the function
attachInterrupt(function,period);
inside loop()
In other words, I wrote
loop(){
Timer1.attachInterrupt(function,period);
// rest of the code
}
where period changes inside the ISR called when the external button is pressed.
Thanks a lot @jose can u c!!

I've found the solution, through the function
attachInterrupt(function,period);

inside
loop()

In other words, I wrote
loop(){
Timer1.attachInterrupt(function,period);
// rest of the code
}

where "period" changes inside the ISR called when the external button is pressed.
Thanks a lot @jose can u c!!

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


text:
Why does Arduino IDE take so long to open?
I have Arduino IDE, version 1.8.10 (Windows 10 x64, 8GB RAM, i5-7200 @2.5GHz) on a network drive mapped to D:, on a 100Mbit wired network and fast file server.
If I navigate to the network shared folder and launch 'arduino.exe', it takes at least 2 minutes for the IDE to appear.
This seems totally unreasonable considering the entire arduino.exe file is only 395kB. Seems more likely the IDE is waiting for something until a timeout occurs, before finally loading up the IDE.
What can be causing this and how can I diagnose it?
As an aside, it seems the compilation process takes longer than it should too, even for programs that use no external libraries and are very short.

dowload sysinternals process monitor and run it ... it will log everything ... see what the Arduino IDE is doing ... https://docs.microsoft.com/en-us/sysinternals/downloads/sysinternals-suite

The libraries and applications used and called sum up to considerable sizes. As @jsotola said, use Sysinternal's process monitor or the task manager to watch these sizes.

arduino.exe is only a launcher. it starts the Java Virtual Machine. Arduino IDE is written in Java. antivirus program can slow down the compilation, because of many process and files opened

Did you try installing everything on a local drive? (including all libraries) ?

and the Java used is bundle with IDE installation so on the network drive too

The simple answer is "libraries".
Every time you start the application, all files inside your library folder are parsed.
And this is not done over your OS, but over the Java-Virtual Machine.
So it is not just slow, it is ultra-slow! Since your antivirus will probably also check each file.
Once, all files was read (maybe 1/2 of the time spent by your Arduino start), all your sketch folders are parsed.
At the end Windows devices and Arduino specific libraries are loaded.
On my Arduino IDE (is installed locally), on each starts, the Arduino IDE checks about 300.000 files. I need up to 20 seconds to load everything, before I can use the IDE.
What can you do?
Base

do not waste the library folder with unused libraries
NEVER put some documentation or non-Arduino files in your sketch folder, as they are all parsed by the IDE
disable the Antivirus for the folders:

Arduino
libraries
sketch

Advanced
If you open always the same project, you can for example edit the "preferences.txt" file.
If you remove some parameters from the preferences.txt, you will be able to lauch your IDE much faster. I created an application that statrs your Arduino IDE with personalized settings:
https://github.com/Adrianotiger/ArduinoIDE_Launcher
This application can remove some preferences like:

boardsmanager
last.* settings
recent sketches

when the Arduino starts, so it will be launched faster. But if you set the preference sketchbook.path, you can start your Arduino IDE 3-4 times faster. Just place the folder with your project libraries and you can start the IDE much faster.

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


text:
Different behavior than in simulator: 5V pin works instead of GND. Why is that?
I use this simulator to check if what I want to do works. This is how it looks like:

I've recently realised that I've connected my RGB LED to 5V pin instead of GND like on schema. It worked perfectly that way (led worked and chanaged colors). When I connected it back to GND pin, it didn't worked.
When I went back to simulator and changed things to those that worked physically (using 5V pin) it didn't worked, but GND did.
Why do you think there are some differences? Can I use 5V pin instead of GND if it works?
My Arduino: Arduino Leonardo.

Maybe you hooked the leds up backwards?

The RGB LED's are available with common cathode and common anode.  That determines whether you connect the common pin to ground or to +5.
In your schematic you likely mismatched the selected part to what you actually have.  If you have the opposite type of LED as planned, just reverse the connection as you did.  You are not alone in this type of mistake.  see similar whot? here
A digital multimeter with a diode test mode would be very useful here.  The DMM would quickly measure the polarity of the diode tell you which lead connects to positive and which to ground.
But did it really work correctly?  Don't you also see that you have to write LOW to the digital output to make the LED light up?

Big thanks for answer. Can you recommend me some sources to learn more about those pins in arduino? Especially what are differences between 5V and GND? And why do I have to write LOW to digital output? Doesn't it mean: "stop the current"?

LOW takes the pin to GROUND level; in particular, it does not disconnect the pin. A HIGH pin can source current; a LOW pin can sink current. A LOW pin only appears to stop current flow if the circuit it is connected to is also at ground level. If the were at HIGH, or +5v level, the LOW pin would enable current flow by sinking it, which is probably what you saw with your LED.


text:
How to get response of issued AT command for ES266 on Arduino programatically?
I'm successfully running AT commands via the Serial Monitor. But now I'm issuing AT commands via Arduino code and facing problems getting the correct response.
Goal: After issuing AT commands programatically, knowing whether these run successfully or not.
Microcontroller: Arduino Uno
#include<string.h>
#include<SoftwareSerial.h>

#define OK "OK"
#define SERVER_PORT 1234
#define RX_PIN 2
#define TX_PIN 3

SoftwareSerial ESP(RX_PIN, TX_PIN);

void setup() {
  Serial.begin(115200);
  Serial.println("First serial");
  while(!Serial);
  ESP.begin(115200);
  Serial.println("Second serial");
  while(!ESP);
  //Enabling multiple connections
  ESP.println("AT+CIPMUX=1\r\n");
  while (!ESP.available());
  String muxResponse = ESP.readString();
  Serial.print("muxR:");
  Serial.println(muxResponse);
}

void loop() {
  if (ESP.available()) {
    String val = ESP.readString();
    Serial.println(val);
  }
}

After running the above code I get the response in the Serial Monitor like:
muxR:AT+CIPMUX=1

busy p../

OK

I'm getting special characters too.

You could try lowering the baud rate to see if the problem goes away:  ESP.begin(9600);  then increase in increments. I guess you are using some sort of level shifting between the Uno and the ESP8266 device.

Ok. I'm just using arduino uno R2, ESP8266 and breadboard, nothing else.

@6v6gt I changed the baud rate of ESP8266 to 9600 by AT+CIOBAUD=9600. Baud successfully changed but getting same response. Getting this busy p.. :(

busy p../ error not going even after factory reset (AT+RESTORE).

Maybe you find something here. I's a similar case: http://arduino.stackexchange.com/questions/18575/send-at-commands-to-esp8266-from-arduino-uno-via-a-softwareserial-port

I recently found out that ESP pins are probably tolerant to 6V, BUT I would still use a level shifter.  Also there is some issue when using SoftwareSerial to communicate between an Uno and ESP where something doesn't work at high baud rates, normally 9600 does work.  Personally I would put a delay(50); and the end of loop() but I have no evidence that it makes a difference :)

I believe busy is a response you should expect and it literally means the ESP is still busy doing the last command.

There is a nice library that hides the AT commands behind standard Arduino networking API: WiFiEsp

change
AT+CIPMUX=1\r\n

to
AT+CIPMUX=1


text:
What causes a "blip" in LED brightness with sequence of 254, 255, 0, 1 brightness values?
I am seeing a "blip" in LED brightness when trying to fade a red LED on an Arduino UNO.
This code demonstrates the "blip" seen in brightness right after a 254, 255, 0 sequence.  When the brightness is then set to 1, the actual brightness is much higher for a short period of time.  The blip is not seen during the entire delay interval, just at the beginning.
I see the blip every time except for the very first cycle, before the 255 to 0 transition has ever happened.
My best guess is that there is a PWM "accumulation" that is not seen when the brightness is set to zero, but it is used when the brightness is set to a non-zero value.
/*
 FadeBlip
 Derived from Fade.ino.
 */

int led = 9;
int brightness = 0;
int fadeAmount = 1;
int skipBegin = 5;
int skipEnd = 254;

// If you try a shorter delay, you must make the skip range smaller
// to pick out the blip.  If you try a longer delay, the blip is not
// as bright.
int delayms = 1000;

void setup()  {
  pinMode(led, OUTPUT);
  Serial.begin(9600);
  delay(1000);  // give us time to bring up serial monitor
}

void loop()  {
  Serial.println(brightness);
  analogWrite(led, brightness);

  brightness = brightness + fadeAmount;

  // skip the boring middle values
  if (skipBegin < brightness && brightness < skipEnd)
    brightness = skipEnd;

  if (brightness > 255)
    brightness = 0;

  delay(delayms);
}

Also see  Why does an LED sometimes flash when increasing brightness?,

The Why does an LED sometimes flash when increasing brightness? question does exactly describe my problem (except for the substitution of pin 11 for pin 9).  That question refers to this post at forum.arduino.cc which gives the beginnings of an answer.
The problem is caused by the fact that analogWrite(led, 0) does not use PWM, it just sets the pin to LOW.  So when you call analogWrite(led, 0), the value in the Output Compare Register (OCR) is left at 255.  When you call analogWrite(led, 1), the OCR value is changed to 1, but due to double-buffering this doesn't take effect until the next timer cycle begins.  So for a fraction of the current timer cycle the output pin is left at HIGH.
The solution is to either avoid calling analogWrite(led, 0) or to explicitly set the OCR value to 0 when analogWrite(led, 0) is called.  This will only work if another call to analogWrite() is not made in the current timer cycle.  Given that the default timer cycle takes 32 microseconds, this is unlikely to happen.  32 microseconds = 256 (ticks per timer cycle) / 16MHz (clock ticks per second) * 2 (default timer prescale factor).
For pin 9, the solution was to add these lines immediately after the analogWrite() call:
if (brightness == 0) {
    OCR1A = 0;
}

For other pins, use the correct Output Compare Register.  For the Arduino UNO they are:
+-------------+----------+-------+
| Arduino Pin | Chip Pin | OCR   |
+-------------+----------+-------+
|           3 |        5 | OCR2B |
|           5 |       11 | OCR0B |
|           6 |       12 | OCR0A |
|           9 |       15 | OCR1A |
|          10 |       16 | OCR1B |
|          11 |       17 | OCR2A |
+-------------+----------+-------+

Of course this solution will need to be modified if you have changed anything related to timers such as the PWM mode.
The solution given by the forum.arduino.cc post indicated that the Timer/Counter Control Register (TCCR) needed to be modified in addition to setting the OCR value.  This modification was to configure the PWM mode, but the PWM mode would have already been correctly configured by any previous call to analogWrite() for that pin.
Others have suggested that calling analogWrite(led, 1) before analogWrite(led, 0) would be a simpler solution, but that still results in a flash, albeit shorter.
Resources:

LED fade malfunction (random flash) (forum.arduino.cc/index.php?topic=360468.msg2486781)
hardware/arduino/cores/avr/arduino/wiring_analog.c
Secrets of Arduino PWM (www.righto.com/2009/07/secrets-of-arduino-pwm.html).  There is a more recent copy of this article at arduino.cc (www.arduino.cc/en/Tutorial/SecretsOfArduinoPWM), but that copy has the useful graphics stripped out.
Arduino Timers and Interrupts (arduino-info.wikispaces.com/Timers-Arduino)


text:
Options for measuring position of garage door
I'd like to be able to measure the position of my garage door. Determining if the garage door is fully open or fully closed should be fairly simple with some magnetic reed switches but I'd like to know the position of the door when it's partially open/closed.

Well, if it's not open and not closed, it's inbetween ;) you'll neer two sensors though to be able to distantiate beteren these states.

If you really want some amount of precision inbetween, you could mount a "ultrasonic sensor" or "ir ranging" sensor to the door and measure the distance to the ground. However, I don't see why it would be neccesary. Most garage doors would shut down when blocked, but ask your manufacturer.

I would suggest an Ultrasonic Range Finder. There is an example in the Arduino Tutorials and they are available cheaply on ebay.

Can you add a link to the tutorial? Or at least describe the general idea?

A couple of possibilities occur to me. One would be to mount a rotary encoder on a rotating part of the door. Another would be to attach a reed switch to the track and a series of magnets to the door. I suppose you could do something with a proximity sensor as well.
How much precision do you need in the position of the door? What do you know that is deterministic? For example is the door transit time predictable? Is it a positive drive? Do you get to know when the door starts moving? That might be enough right there.
If you can say more about what you're trying to do it would make it easier to provide suggestions and insight.

As for precision, within a couple of inches or so would be fine. It's mostly for informational/educational purposes.

Seems like a reed switch and magnets might be one of the simpler ways to go about it. Or if you control the motor and the door drive is positive you could just time it.

Timing it wouldn't help if the door gets stuck (how would you know where it got stuck) and would probably be less precise than I want if the door doesn't travel at a constant rate.  Magnetic reed switches would work but would require a lot of them and hooking them up would take some fancy electronics or a lot of pins.  Plus there would be some uncertainty if the door stopped inbetween the switches.  So far a rotary encoder tracking the movement of the chain sounds like the best bet.

The way I would do it with a reed switch (or maybe two or three) is to use one switch and many magnets – at most you would use three pins. You would keep track of the door position by counting switch closures. You could make it a bit more positive if you also used a switch or possibly two for "open" and "closed" – you could reset your count when the open or closed switch was tripped which might make it easier to keep track of your position. One thing to keep in mind is how you will deal with different failure modes. The rotary encoder will give you the wrong answer if the chain breaks.

A linear encoder (usually comprising an LED, a photodetector, and an encoder strip with black lines on it) would work, but a long encoder strip is expensive and probably not reliable a garage environment.  You could use a radial encoder attached to the motor, but that is probably too expensive too and overkill for your application.
Ranging devices are often difficult to use with something narrow and dirty like the bottom edge of a garage door.  Placing devices on the door itself is probably not the most reliable and inexpensive way to do this either.
A Solution for Any Large Spring Loaded Position Sensing
One way that can be very reliable and is inexpensive is to use two strain gauges.  In spite of the low cost, this approach is used in many industrial and laboratory arrangements.  You could use an IN114 or a similar 8-pin dip instrument amplifier to convert the differential strain gauge resistance to a Voltage within the range of the Arduino analog input.
I'd guess a cost around $100 with shipping for the IN114, the rest of the circuit, strain gauges, emery cloth, bonding cement, temperature sensor (optional), power supply, jacks, solder, circuit housing, PCB breadboard, and cabling.
You will need to use a Wheatstone bridge at the + and - input of the instrument amp. There are plenty of example circuits.  Search for, "instrument amp wheatstone bridge strain gauges," to get some schematic diagrams.
An adjacent two of the four legs of the Wheatstone bridge are the two strain gauges.  One of the other two legs would be a potentiometer in series with a fixed resistor to give you offset adjustment.  Another potentiometer adjusts gain.  The IN114 spec sheet shows how to set the gain and how to power the chip.
Mechanically, the strain gauges would go on opposite sides of the exact same point on the spring, near where it attaches to the stationary frame to which the tracks are mounted.  One strain gauge must be bonded to the inside of the spring.  The other to the outside, directly opposite the inside one through the thickness of the spring wire.  This will allow the Voltage you measure to indicate the strain on the spring which is related to the position of the door.
(The image at http://recordtek.com/sites/default/files/Gauge-spring.png shows a strain gauge bonded to the outside of the spring.  The inside complement would go directly underneath it on the inside.)
I'd recommend an Arduino Due to read the output voltage of the IN114, setting the gain and offset to stay within the 1.55 to 2.75 V range of the analog inputs of the Due for all garage door positions.  That will take some trial and error with a Voltmeter before you connect the Due.
To calibrate the system, the analogRead() values for ten somewhat equally spaced garage door positions are placed in an array of integers.  Another same size array of doubles receives the corresponding door positions in whatever units you want.  These can be static arrays that are initialized in your Arduino code.
You would get the position from the analogRead() at any point in time by interpolating the data in the table represented by the two corresponding arrays.  That is easier than it sounds.  There are articles explaining how and libraries providing linear interpolation in C, some of which may be usable without modification in an Arduino sketch.
Bonding the Strain Gauges
There are many articles available on using strain gauges and how to rigorously clean the surface and position and orient the gauges before bonding them to the metal of the spring.  That's critical.  They have to point in a particular direction, and the bond will come apart if you don't clean the metal well enough, which would not be good.
Going High End
If you wanted high accuracy, you could enhance your design to possibly get three or more significant figures as you reach expert level.

Read and factor in temperature when doing the interpolation
Take more than 10 calibration samples and use larger arrays to match
Use a quadratic or cubic interpolation instead of linear
Write a calibration algorithm to fill the two arrays with new values
automatically every time the door goes from one extreme position to
the other


text:
HC-SR505 PIR Sensor only outputting HIGH
I recently bought an HC-SR505 Mini PIR sensor. I connected its positive to my Arduino UNO's 5v, output to digital pin 2, and ground to ground. I used Adafruit's code to test it, but all the serial monitor displayed was "Motion detected", which meant the PIR was always on a HIGH state. I then also tried powering it using 3V3 but the PIR kept on cycling on a HIGH and LOW state. Any help on getting my sensor to actually work would be greatly appreciated.

The PIR sensor has delay of 8 seconds. So when you turn on arduino, take care that no movement is on the PIR, and then after 8 seconds it should detect no movement. And it has always this delay,every time when detects movement.

It depends, don't generalize (<-however you write that word).

Depends on what?

The PIR sensor has delay of 8 seconds is not a fact that affects all PIRs.

I'm talking about Hc sr505

I was struggling on the same issue. Here's the specs also: https://www.elecrow.com/wiki/index.php?title=HC-SR505_Mini_PIR_Motion_Sensor
Thanks for clarrifying it up. To sum it up. The 8 seconds start by the time it last sensed a movement.

I have similar problem with the HC-SR505 sensor. First few seconds it holds 0 on the output pin, and then always 1.
I think it was bad batch of sensors. Bad batch in chinese manufacturing means thousands (or hundreds of thousands) bad modules flooded the market.
Meanwhile I decided to choose one of options:

Stick with HC-SR501 sensor. It's bigger but works more or less.
Buy expensive ($5.90) PIR sensor from seeed.
Build my own PIR module by my required dimensions and function (in progress).

Update:
From 5 sensors received 2 do the job. Supply voltage must be 5V or higher. First 20-60 seconds the output is not reliable and should be ignored. Then it works OK (if it works at all). Since the module has 3.3V LDO onboard the output signal is 3.3V.

Switch to use 5v for Vcc, the sensor will work correctly. I have the same trouble if I use 3.3v for Vcc. The output still 3.3v even your Vcc is higher than 5v.

While using 3.3v does sound problematic, if you read the question again you will see that the asker started their experiments with the 5v supply, and found that not to work.  So the actual problem must be something else.

I tried with another power source, not from the board. In my case I'm using an ESP8266 and to get 5v I need another power source.

You may be using an ESP8266, but the asker is using an Arduino Uno.

Let the asker try 5v from another power source, not from Uno. Does it make sense?

Even though this may not help the OP, this was my problem and I am thankful for having found this answer.

I'm a noob. I had the same problem.
I connected the signal to pin 7 so I listened to gpio7 which always gave 1. But pin 7 is gpio4... Listening to gpio4 fixed the issue :)

The PIR works at 5V but you need to tweak the amount of sensibility and the signal length.
Usually when a motion is detected, the PIR keeps sending HIGH until x seconds defined by a potentiometer on the board, when it goes down, the sensor is ready to capture another motion.

Thanks for the explanation. Just want to point out that the HC-SR505 doesn't have a pot on it. Also, do you know if the output voltage is 5v or 3V3?


text:
Cannot disable interrupts
I am new to arduino.
Why does this not work the way it's supposed to?
Shouldn't it block all interrupts for 3secs after it received one from digi pin 2?
How would I accomplish this:
Running a method whenever the value on this pin changes, execute it and then listen for more interrupts from that pin?
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  attachInterrupt(digitalPinToInterrupt(2), test, CHANGE);
}

int i = 0;

void loop(){}

void test(){
  noInterrupts();
  Serial.println("Interrupt registered - waiting " + i);
  delay(3000);
  Serial.println("done waiting!" + i);
  i++;
  interrupts();
}

What is it doing that it isn't supposed to? I think delay and Serial depend on interrupts being active, you should never disable them globally for an appreciable amount of time. Handlers need to run fast. Also running an interrupt and then continuing to trigger future interrupts is the default behavior.

You could achieve that by this simple rewrite:
void setup() {
  Serial.begin(9600);
  attachInterrupt(digitalPinToInterrupt(2), test, CHANGE);
}

volatile bool changed = false;
int i = 0;

void loop() {
  if (!changed) return;
  Serial.print(F("Interrupt registered - waiting "));
  Serial.println(i);
  delay(3000);
  Serial.print(F("done waiting "));
  Serial.println(i);
  i += 1;
  changed = false;
  clearInterrupt(digitalPinToInterrupt(2));
  attachInterrupt(digitalPinToInterrupt(2), test, CHANGE);
}

void test() {
  changed = true;
  detachInterrupt(digitalPinToInterrupt(2));
}

The interrupt service routine (ISR), test(), is really short and does not call functions that actually need interrupts to work (e.g. delay(), Serial). Please see Nick Gammon's comment below on clearInterrupt(), i.e. EIFR = bit (INTF0);
An alternative rewrite is to use the BlinkWithDelay-pattern and a somewhat more complex state-machine:
volatile bool changed = false;
bool waiting = false;

const unsigned long waitIntervalMillis = 3000UL;
unsigned long waitStartMillis = 0L;

int i = 0;

void setup() {
  Serial.begin(9600);
  attachInterrupt(digitalPinToInterrupt(2), test, CHANGE);
}

void loop() {

  // Check for change
  if (!changed) return;

  // Check for change before wait interval
  if (!waiting) {
    Serial.print(F("Interrupt registered - waiting "));
    Serial.println(i);
    waiting = true;
    waitStartMillis = millis();
  }

  // Check if wait interval has expired
  else {
    unsigned long currentMillis = millis();
    if ((currentMillis - waitStartMillis) >= waitIntervalMillis) {
      Serial.print(F("done waiting "));
      Serial.println(i);
      i += 1;
      changed = false;
      waiting = false;
    }
  }
}

void test() {
  changed = true;
}

A third rewrite is possible. Assuming that the pin is connected to a push button, the interrupt handler can be replaced by simply reading the pin with a low frequency (for debouncing).
Cheers!

If the switch bounces it will probably register (queue) another interrupt during your delay. I suggest doing EIFR = bit (INTF0); before attaching the interrupt again. See: Interrupts.

This is one of those disturbing things. There was a pull request to fix that nearly two years ago; https://github.com/matthijskooijman/Arduino/commit/c82e9aadd358127e4f272dc99bc2a6a4d70963c6. It must have broken something else as it was removed/not merged. They could at least added a clearInterrupt(pin) function just for the symmetry of things. Anyway, that is a very good catch!

Once people get used to behaviour (no matter how annoying it might be) it is hard to change it.

why do you need to disable and reenable interrupts at all?

The question is why use interrupts at all if the signal is generated from a button pushed? In any case, I do agree, it is possible to do yet anther rewrite without attach/detach interrupt.

Probably your biggest problem is that delay() cannot be used inside interrupt service routines (ISR's) and it doesn't work if interrupts are turned off because it uses interrupts to function.
ISR's should be as short as possible, because they stop normal operation of the device while they execute. A good ISR will set a few variables, and then return, while the main program loop checks the state of those variables and actually does stuff. Mikael Patel's answer shows how you can rewrite your sketch to do this.


text:
Different data showing in arduino serial and hyperterminal
I've connected to RS232 device with arduino. When showing data in arduino its showing as:
235
157
191
157
159
153
157
0

While in Hyperterminal it's showing as:
 101 102 103 104

How to get the same data as hyperterminal in arduino too?
My Arduino code:
   if (RS232.available()) {
    int incomingByte = RS232.read();

    Serial.println(incomingByte);

    //Sending to bluetooth
    BTserial.println(incomingByte);
  }

The Arduino serial monitor is incredibly crude and barely usable at the best of times. It may be to do with line endings, or something similar. Personally I would use putty or teraterm rather than hyperterminal, since that is a bit crude too (though not as crude as the arduino serial monitor).

@Majenko In my case, Hyperterminal is showing correct data as above. But serial should show similar data too. Is there any problem in my Arduino code?

Not in that little snippet, no. However the two serial programs do deal with line endings in a very different manner, which is probably where the difference in displays lies.

What results do you get if you change int incomingByte to char incomingByte or to byte incomingByte?

@JamesWaldby-jwpat7 on changing to "char incomingByte" special chars print, somewhat like square symbol. And on changing to "byte incomingByte" result remains the same.

Rahul Rastogi, by  “result remains the same” do you mean the same as for "char incomingByte", or like the “int incomingByte” output?


text:
Do motors need to have capacitor even if being used with motor shield
I'm using a 12V DC geared motor with an Adafruit motor shield which is connected to Arduino.
So, I want to know inspite of using the motor shield, do I need to add capacitors to the motor?

Post a schematic of how you think extra capacitors should be added, a description of what you think they'll do, and what you think the problem with what the shield documentation suggests (not necessarily in that order), and then we can comment.

lots of motor shields have that sort of thing (dioides too) built-in

If the motors have a lot of "brush noise" you need to add capacitors to the motor. It is written in the FAQ.
The noise must be suppressed at the source or the motor leads will act like antennae and broadcast it to the rest of the system link.


text:
Can i burn an Arduino sketch .hex directly using USBASP?
I am unable to upload sketches to my Arduino Uno board using the upload option in the IDE. I have done quite a few tests to find the reason but everything seems to be working fine when tested separately. I found that I can program the ATMega328 board when placed on a breadboard using an USBASP progammer and avrdude. So will it work if I burn the .hex generated in Arduino IDE using avrdude and USBASP by placing the ATMega on a breadboard? I would then want to replace the IC on the UNO board back for my application. Thanks for your time and help in advance.

Is there a reason why you don't want to use the serial bootloader?

What do you mean by 'serial' bootloader? Actually the problem is that I have ATMega328 instead of 328P for an UNO board. I have tried burning the bootloader fot both 328 and 328P on my 328 but I cant get either of them to program via USB somehow. USB connection is fine as loopback test is running fine.

Sure you can - but you don't even need to remove the chip from the Uno.
The 6 pin header at the end of the board (used for SPI) is also the ISP header for the main chip. Just plug your USBASP into there (you can get adaptors for it for $0.99 off eBay) and program it direct.
I think there's even an option in the IDE's menu to select the USBASP as the programmer (or there used to be on earlier versions).


text:
Will the Arduino's low clock speed limit wireless transmission frequencies that are higher than the clock speed of the Arduino?
I've recently used 2.4GHz and 433MHz wireless communication modules, and I was wondering if the Arduino can only process at 16MHz(Arduino UNO's clock speed), then won't the communication modules also be limited to a maximum 16MHz?

The frequency of a (wireless) radio is its carrier frequency. The data stream is carried on it by modulating that carrier wave in some way: by frequency-shifting, for example. A given processor could not provide data at a rate faster than its clock frequency (at least as a steady-state rate), but a packet of data, once supplied to and buffered in the radio, could then be streamed out at a speed unrelated to the physical specs of the supplier (the MCU). If the MCU had to drive the transmitter, bit-by-bit, then that would indeed limit the transmission speed.

You need like 22kHz for "telephone quality" transfer of speech, but you can hardly articulate more than 4-5 syllables per second. The first is the carrier frequency, the other is data transfer speed. (And you usually need some time to think about what you want to say).
The wireless frequency is modulated by the transmitted signal, which must be lower than the frequency itself, to be able modulate it successfully and then be separated from it. There is also some overhead like headers stating who is transmitting, to who, how much, control sum and so. A lot of it is managed in hardware, without direct processor control. (You also do not generate the frequencies and tone in you head as values of sinus wave, you just send the modulation - talk - and the body makes its parts vibrate so fast with your breath).


text:
DFROBOT I2C 16x2 Arduino LCD Display Module I2C communication interface
What is the proper connection to the I2C communication interface (e.g., JST Jumper 4 Wire Assembly) of the DFROBOT I2C 16x2 Arduino LCD Display Module (SKU:DFR0063)? I wish to connect 4 wires assembly directly to it.

Here is schema how to connect it and example how to use it, also link to needed library. Hope this helps.
https://www.dfrobot.com/wiki/index.php/I2C/TWI_LCD1602_Module_(SKU:_DFR0063)
Anyway - I2C is prettty standardized interface, so googling any I2C schema for your type of Arduino will work as for connection - just connect SDA (A4) to SDA, SCL (A5) to SCL, GND to GND and VCC to VCC as writen on the module interface.
There are also lots of correct results for googling the module name - just google SKU:DFR0063 and you get many of correct links. On first page every second link contains link for the library, those others just refers to the manufacturer in text.

While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference.  Link-only answers can become invalid if the linked page changes. - From Review

Esential part is connect I2C (connect the same name pins on module & Arduino), download library from manufacturer and use it usual way. The link ghoes to manufacturer wiki about the product, so it should not perish easy). Anyway I added this description to answer. Took me longer, then to google for the name of module and click the link for download library in every second google result.


text:
Run two stepper at same time
I am trying to run two stepper motor at same time with different RPM.
I decided to use two rotary encoder for change the RPM separately.
But,
I am in problem with driving stepper at same time due to the delay time of the step pulse.
How can I generate separate(different duty cycle) step pulses for stepper motors? It's the main problem that I faced.
I have used some Arduino libraries and all of that library has same system for step pulse generation. But, I couldn't understand those well.
void AH_EasyDriver::setSpeedRPM(long RPM)
{
   float DIV = RPM*this->MOTOR_RESOLUTION;
    this->STEP_DELAY =  60000000.0L/DIV;
 }

This function calculate the step time for given specific RPM
void AH_EasyDriver::move(int NUMBER_OF_STEPS)
{
   while(STEPS > 0) {
    if (micros() - this->LAST_STEP_TIME >= this->STEP_DELAY) {
      this->LAST_STEP_TIME = micros();
      STEPS--;
      stepMotor();
}
}

}

This function rotate the motor the motor in STEP_DELAY using stepMotor() function.
void AH_EasyDriver::stepMotor()
{
  digitalWrite(this->STEP_pin, HIGH);
  delayMicroseconds(100);
  digitalWrite(this->STEP_pin, LOW);
  delayMicroseconds(100);
}

This function makes CONSTANT step pulses.
I removed some lines in the function. This is the link for original .cpp file.
All of stepper controlling libraries has this functions.
I couldn't understand how this functions can change the RPM. Can someone explain this?

This is a complex task; if you want to see an example of multi-motor coordinated movement, look at an open-source Arduino based 3d printer or light duty CNC machine firmware.

When using a normal stepper driver, you say the driver to do one step, by sending him one pulse. The length of these pulses does not have a meaning. they are constructed, so that the driver can sense them. The driver does not make smaller steps than 1 full step, if you don't tell him on extra pins (The library you use can utilize those pins too). So the stepMotor() function is correct. You can drive the motors with different speeds by doing a step for each motor in different intervals (different number of steps per time).
Your move() function blocks the execution of other code, until the motion is completed. You are doing this with the while( STEPS > 0 ) loop. You need to modify your code to be non-blocking. This is normally done in the way, that is shown by the BlinkWithoutDelay example of the Arduino IDE. You are using it too: You have to use the millis() or micros() function, to check if it is time to do a step.
Replace the while with an ´if´-statement:
if( STEPS > 0 )

and make the STEPS variable a member variable of the class instance. Then make sure you execute the function often enough, so that it will not miss the time to do a step. Do the same with the second motor. For example something that looks like this:
void setup(){
  ...
  stepper1.doSteps(100);
  stepper2.doSteps(200);
}

void loop(){
  stepper1.move();
  stepper2.move();
}

Here in the setup function the steppers are told to move 100 and 200 steps. (You would have to write the function doSteps(int number_of_steps) yourself). The motion is then done by the move() functions, when it is time to do so. Since these two functions are looped very fast, they shouldn't miss the time for a step.
This is also the way the AccelStepper library works, which is also a common stepper library.

While the width of a step pulse might not matter within limits, the time between pulses is extremely important, and not trivial to achieve for multiple motors.  You don't seem to be explaining a viable mechanism for accomplishing that.

I'm not sure how you mean this. In my understanding the driver goes one step, when it counts one pulse. You do pulses in a slow or faster series, depending on how fast the stepper should run. Surely it this not a method for high speed/high precision, but a way you can go, if the circumstances aren't too tough. Maybe I have misunderstood something how the driver works. Please correct me. I can then edit or remove my answer if it is wrong

In the real world it is often necessary to make coordinated moves between two motors, for example imagine a circle in X and Y axis.

For doing such a motion you would have to modulate the speed of the motors (essentially making the time between the pulses depending on a function). But the OP used it in a more simple way. I think the more complex functionality of drawing circles or anything else is out of the scope of this question.

Though it can also be done with my method by varying the speed of the motors during the motion. But the used function of this library are not good for this, I think

The method to produce simultaneous pulses is simple, but requires a different approach similar to Direct Digital Synthesis (DDS).

Keep one counter variable per motor
Increment each counter variable by a set amount in a fixed time loop
When a counter variable reaches a threshold value, generate a very short step pulse
When a threshold is met, subtract the threshold value from the corresponding counter

The amount that each counter variable is incremented sets the generated pulse rate, reaching the threshold faster or slower, therefore setting the motor speed. A value of 0 stops the motor, a value equal to the threshold generates a step pulse for each iteration of the loop, reaching the highest speed. An arbitrary number of motors may be controlled simultaneously as long as the code can run within the fixed loop time. Since a step can only occur at fixed intervals, the rate of the timed loop should be several times the fastest step rate you intend to use to minimize timing jitter.
This style of control is often implemented using a timed interrupt service routine (ISR) which is a short function set to repeat at a several kHz frequency, interleaving with the rest of the program. This allows a slower loop to run a control algorithm simultaneous to the step generation.
If not using a timed interrupt function, the step generation loop must busy-wait until a set time has elapsed before repeating again. This means you cannot do much else than drive the motors until you stop and break out of the loop.


text:
How to use strtok() and strstr() with arduino?
Can anyone explain how things like strtok() and strstr() can be used to provide a numeric value for a substring location position within the mainstring array.
I've tried to understand from the C++ examples, but their 'position' locations of the substring within the mainstring (which I need) are returned in C++ as %d variables, whereas all I can get returned by the arduino 'char * pointer=' is the actual substring chars if they exist, rather than a number for their start position locations within the mainstring.
The C++ examples show that it is possible to discover the position values from %d,  but how can I get that equivalent position value in arduino?
I want to be able to parse a char header[30] array for occurances of things like "s=123" and "d=789" in order to extract and assign the specified values to any appropriate variables (source or destination etc).

If you have a pointer to a substring (of a null terminate C string, not a C++ String) stored literally within the original, you can determine the offset by subtracting the pointers.  Pointer math is a key C concept, but it can also be a tricky one, with many pitfalls for the unwary.

So is there an effective way of parsing things out from char arrays?  (perhaps that's the question I should have asked)

It sounds like sscanf() is way more appropriate for what you want to do than any str*() functions.

You have to define a format for the header you will be parsing and stick to that format. Say this is a sample header terminated by null:
s=123 d=789 e=463

A common property of each assignment in the string is the '=' symbol. You can use that to locate each variable and the value assigned to it. strchr is the function to use to locate a single character. Once you locate the = character, you move back and then forward along the array to obtain the variable and its value.
I will make some assumptions here: that your variable names will be single character, that numbers assigned will be no bigger than ints, and a space character is used to separate assignments.
char header[] = "s=123 d=789 e=463";

int d, s, e;   //your variables to be assigned to
char * ptr = header;
char * eq = NULL; //locate assmts
int * num = NULL; //just for starters
while (1){
  eq = strchr(ptr, '=');
  ptr = eq; // update the pointer
  if (ptr == NULL) // found no = chars
    break;
  switch (*(ptr - 1)){
    case 'd':    //all the possible variables
      num = &d; break;
    case 's':
      num = &s; break;
    case 'e':
      num = &e; break;
    default:   //unknown variable
      num = NULL;
  }
  ptr++;
  if (num == NULL) //unrecognized var
    continue;   // locate next = char
  *num = 0;
  while (*ptr && (*ptr != ' ')){  // while space or end of string not yet reached
    *num *= 10;  // extract each int
    *num += *ptr - '0';
    ptr++;
  }
}

Serial.println(d);  //now contains the numbers in the header
Serial.println(s);
Serial.println(e);

Untested but it should work for the header sample I gave.

Your answer is excellent Mr T, thank you very much indeed.

@Electroguard You're welcome. I've seen your other question. You may have to get rid of strchr in the receiver code and do the searching yourself, if you want to implement checksums efficiently.


text:
Motor shield causing problems with interrupts?
I am making a controller for a model railway turntable and I need to control a single DC motor and read a hall effect sensor. I have the hall effect sensor connected to pin 2 on my Uno (since 2/3 are the only pins that support interrupts) but whenever I turn the motor on it triggers the interrupt on pin 2 despite the fact that the motor PWM pin is on pin 11 and I have disconnected alternate PWM pin 3. This is with the official Arduino motor shield and an Uno.
I'm at a loss here, any ideas? I know it's not the motor triggering the hall effect sensor because I connected a resistor in place of the motor and it still happened.

How much power does the DC motor require? It sounds like if it is a reasonably sized motor, it may be drawing too much power when it is on. It is always a good idea to have motors connected up to an external power supply e.g. battery pack.

Ah forget that, just properly read your last sentence.

The motor is not actually powered from the Arduino, it's powered from an external 13.8v power supply capable of delivering 19A. (That PSU runs other things too but I can assure you it's not at capacity) I bent the "Vin" pin out of the way on the motor shield so I wouldn't run 13.8v into the Arduino, could that be causing problems?

How does the hall sensor work? Is it passive? Is it detecting something and hence triggering the interrupt? But wait, you say that it happens when you connect a resistor in place of the motor, but you originally say that the interrupt happens when you turn the motor on? Where are you connecting the other end of the resistor to, the ground pin?

The motor is connected via the "B" screw terminals on the motor shield. The PSU is connected via the "Vin" and "GND" terminals on the motor shield. When I connect the resistor, I simply connect it between the two "B" terminals, right where the motor normally is. It connects to a ground pin, but not the ground pin on the Arduino headers, the one on the 13.8v external PSU. Link to motor shield

Hmm hard to diagnose without seeing the setup tbh, sorry. One thing I would say is that 13.8v sounds high for the Arduino - the max is 12v as stated in the documentation with 1A limit from what I have read. I would strongly suggest you try a lower powered PSU. You may damage your board if it is connected directly, and that could also cause the problem you've stated.

actually on the motor shield the max current is 4A with an external psu

I will try it in a little bit, but if that is the problem I misunderstand how current flow works. The motor itself has a max rated current of 1a, and I have run it on a 1a fuse before and never blown the fuse. If the motor doesn't draw over 1a, won't that not damage anything? I'll try a lower amperage PSU just the same, I'm just wondering.

The screw terminals have a higher limit, but according to the shield docs, you may need to cut the Vin connect jumper on the back of the board to feed in more power

You may well be right, not sure! Just a suggestion as I can't think of anything else. Check the docs: https://www.arduino.cc/en/Main/ArduinoMotorShieldR3

@bladepanthera,  re “13.8v sounds high for the Arduino - the max is 12v as stated in the documentation with 1A limit”, see ArduinoBoardUno at arduino.cc.  Max is 20 V, not 12.  The range 7 V to 12 V is recommended rather than required.  13.8 V to VIN or the power jack on an Uno  is ok as long as current draw on the Uno isn't too high. (High draw at high voltage can overheat the Uno's 5 V voltage regulator.)  If motors are wired correctly, motor board current isn't relevant to Uno current except for however many milliamps the L298 logic takes.

@jwpat7 That's what I was thinking, and since the Uno is connected via USB for data anyway I was powering the Uno and 5v stuff off USB and the motor off the 13.8v supply. I just bent the VIN pin off to the side so it didn't connect. Could this be the problem? Do I need to also bend GND pins?

@jwpat7 I stand corrected. :) I don't see why the GND pins should be making any difference if the Vin is not in use, but I'm happy to be corrected about that, too.

The motor, driver board, and Uno grounds should be star connected to a common point so no motor currents go through the wire to the Uno ground.   The  motor shield probably more or less does that.   If you have a DSO you should be able to get a picture of whatever transient voltage noise is causing the interrupt.  I'd try putting a 330 uF cap from 5V to GND on the shield in case the problem is due to high current switching on the shield, and a 10 to 100 nF cap from GND to pin 2 in case EM noise is the problem.   How fast does your interrupt need to respond?


text:
Any libraries exist for easy configuration via USB?
I have a device that would really benefit from a USB configuration tool. I'm envisioning "plug it into a PC, and it appears as a storage device with a YAML config file". Are there any ready-made libraries to do this, or some other established way of configuring an Arduino-based product with a PC?
I'm developing with PlatformIO on an STM32 Blackpill, if that matters.

there are examples of using a microcontroller to emulate a USB storage device available on the internet


text:
Is it possible to run the Teensy to the Arduino?
I'm already done copying/pasting the libraries that I know is needed to run the program, but I wonder why I always get this error every time I tried to run the code. What do you think would be the possible reason why I get this error:
  C:\Program Files (x86)\Arduino\libraries\I2Cdev\I2Cdev.cpp:64:14: warning:
  #warning Using current Arduino IDE with Wire library is functionally
  limiting.   [-Wcpp]

  #warning Using current Arduino IDE with Wire library is functionally limiting.

          ^

  C:\Program Files (x86)\Arduino\libraries\I2Cdev\I2Cdev.cpp:65:14: warning:
  #warning Arduino IDE v1.0.1+ with I2CDEV_BUILTIN_FASTWIRE implementation
  is recommended. [-Wcpp]

  #warning Arduino IDE v1.0.1+ with I2CDEV_BUILTIN_FASTWIRE implementation
  is recommended.

          ^

 C:\Program Files (x86)\Arduino\libraries\I2Cdev\I2Cdev.cpp:66:14: warning:
 #warning This I2Cdev implementation does not support: [-Wcpp]

 #warning This I2Cdev implementation does not support:

          ^

 C:\Program Files (x86)\Arduino\libraries\I2Cdev\I2Cdev.cpp:67:14: warning:
 #warning - Timeout detection (some Wire requests block forever) [-Wcpp]

 #warning - Timeout detection (some Wire requests block forever)

          ^

 In file included from C:\Program Files
 (x86)\Arduino\libraries\RTIMULib\RTIMUHal.cpp:27:0:

 C:\Program Files (x86)\Arduino\libraries\RTIMULib\RTIMUHal.cpp: In member
 function 'bool RTIMUHal::HALRead(unsigned char, unsigned char, unsigned
 char, unsigned char*, const char*)':

 C:\Program Files (x86)\Arduino\libraries\RTIMULib\RTIMUHal.h:59:37: error:
'class HardwareSerial' has no member named 'printf'

 #define HAL_ERROR1(m, x)     Serial.printf(m, x);

                                 ^

C:\Program Files (x86)\Arduino\libraries\RTIMULib\RTIMUHal.cpp:73:13: note:
in expansion of macro 'HAL_ERROR1'

         HAL_ERROR1("I2C read failed - %s\n", errorMsg);

         ^

  C:\Program Files (x86)\Arduino\libraries\RTIMULib\RTIMUHal.cpp: In member
  function 'bool RTIMUHal::HALWrite(unsigned char, unsigned char, unsigned
  char, const unsigned char*, const char*)':

  C:\Program Files (x86)\Arduino\libraries\RTIMULib\RTIMUHal.h:59:37: error:
  'class HardwareSerial' has no member named 'printf'

  #define HAL_ERROR1(m, x)     Serial.printf(m, x);

                                 ^

  C:\Program Files (x86)\Arduino\libraries\RTIMULib\RTIMUHal.cpp:96:13:
  note: in expansion of macro 'HAL_ERROR1'

         HAL_ERROR1("I2C write failed - %s\n", errorMsg);

         ^

   C:\Program Files (x86)\Arduino\libraries\RTIMULib\RTIMUHal.cpp: In member
   function 'bool RTIMUHal::HALWrite(unsigned char, unsigned char, unsigned
   char, const char*)':

   C:\Program Files (x86)\Arduino\libraries\RTIMULib\RTIMUHal.h:59:37:
   error: 'class HardwareSerial' has no member named 'printf'

   #define HAL_ERROR1(m, x)     Serial.printf(m, x);

                                 ^

  C:\Program Files (x86)\Arduino\libraries\RTIMULib\RTIMUHal.cpp:119:13:
  note: in expansion of macro 'HAL_ERROR1'

         HAL_ERROR1("I2C write failed - %s\n", errorMsg);

         ^

  exit status 1
  Error compiling.

Please add some information about the Arduino/Teensy IDE version, board, libraries used, etc. The compiler (and the source code) is trying to tell you that you have a severe configuration issue.

Many of your problems seem to be that you are trying to use Linux software on an Arduino. That's never going to work.

It just seems he's missing the right print function. It's worth a shot just  replacing the "printf" with "print". @Thomas, have you tried it (go to libraries folder, RTIMULib and open RTIMUHal in notepad and change line 59 "printf" to "print", keep everything else the same)?

Replacing "printf" with "print" will only lead to the "dark side" - even more compiler warnings. It might be the wrong version of the RTIMULib library.

Hi guys thank you so much for your responds :)

@Mikael Patel https://github.com/richards-tech/RTIMULib2-Teensy here is the link .

@Majenko, so you mean there's no chance to work it ?

@Avamander, i'll try it .

@MikaelPatel, yes i  used the teensy library because this is the latest,  a need to add the runtime calibration which is not present in this library. https://github.com/richards-tech/RTIMULib-Arduino


text:
Can RX and TX be temporarily transposed on demand?
Only 2 arduinos can normally be linked via serial port because TX and RX need to be cross-linked, and connecting multiple TXs together would cause conflict.
RS485 allows multiple nodes connected in parallel on a 2 wire differential 'bus', using a TX ENABLE pin to allow one master to transmit while all other slaves listen.
I suspect it should be possible to similarly connect multiple serial RXs together to give a common listening bus, and be able to use TX ENABLE on any one node at a time to transpose its RX and TX to allow its TX to transmit to the other RXs. This might be physically done using a changeover relay swapping RX with TX, but is it possible to somehow temporarily switch the TX and RX assignments on demand by software?
I doubt the actual pin assignments can be changed in-situ, but perhaps the same results are achievable with some programming wizards sleight-of-hand trickery?

What about SPI? That's designed for single-master multi-slave. Perhaps you could explain what you're trying to achieve in greater detail.

I am trying to create a text-based arduino clustering system for circumventing arduino resource limitations, which I try to explain in this link...
http://arduino.stackexchange.com/questions/19608/arduino-cluster-functionality-feasibility-advice-for-arduinos-to-communicate-u

How much do you know about network protocols? What it seems that you need answers an age-old situation of multiple nodes with interlinked communication. This is answered todaywith Ethernet as the 'default' machine to machine link, but there have been several iterations of network communications/protocols/topology. Start with ALOHA, and then maybe Token Ring. Working through the timeline of network comms I'm sure you'll find something that balances your needs versus advantages/disadvantages.

TX and RX pins are fixed to the hardware, so you can't swap assignments (Assuming Arduino Uno here). You could try softwareSerial, if you want a software only solution. Or do something like this half-duplex UART

You can try by connecting RX and TX together and then setting the TX in high impedance with pinMode(1,INPUT). If this does not work (because the atmega overrides that), you can just put a tristate buffer on the TX pin. Or, better, a SPDT analog switch: it's the same as the "changeover relay", except that it is integrated. An example is the Analog ADG839, but there are tons of that.

I don't know much at all about protocols, I'm just trying to implement an easy method of sharing functionality between several arduino compatable nodes (possibly including ESPs) that requires using the least resources on each node, and with my limited knowledge and experience it seems that Nick Gammons RS485 library may offer me the best chance for achieving those goals. Thank you all for your helpful comments and advice, it makes exploring the unknown a much less daunting experience.

@frarugi87: Yes, the ATmega overrides your pin mode. C.f. the datasheet: “When the USART Transmitter is enabled, this pin is configured as an output regardless of the value of DDD1.”

@EdgarBonet yes, but in the PortManipulation page on the Arduino wiki they say It would be very easy to accidentally cause your serial port to stop working by changing pin 0 into an output pin!. So I think that when you enable the serial port it modifies the pin mode, but then you can modify it. Or not? This should be investigated ;)

@frarugi87: You think wrong. And it appears that the authors of that page do not know what they are writing about... and they did not try either! Atmel seems to know better how they chips behave.

@EdgarBonet it looks like you are right... Of course Atmel knows their chip better, but that sentence could also be interpreted as "when you enable it, it turns the pin to output" instead of "when it is enabled the pin is forced to be an output". It appears that the author of that page should fix that ;)

On an AVR-based Arduino, you can selectively enable the transmitter and
receiver side of the UART (c.f. the datasheet of your MCU). Thus, you
could in principle just connect all the TX and RX together, and make
sure only one transmitter is enabled at a time, while all the others are
in high impedance. If you do this, I would strongly recommend you put a
current-limiting resistor in series with each TX, just in case.
For example, on an Arduino Uno
(Atmega328P),
you can use the following functions:
static inline void enable_tx()  { UCSR0B |=  _BV(TXEN0); }
static inline void disable_tx() { UCSR0B &= ~_BV(TXEN0); }
static inline void enable_rx()  { UCSR0B |=  _BV(RXEN0); }
static inline void disable_rx() { UCSR0B &= ~_BV(RXEN0); }

Edit: Beware that Serial.begin() enables both the transmitter and
the receiver.

Thank you Edgar Bonet, that is the type of 'wizardry' I was wondering if was possible.

It sounds to me like you are misunderstanding the purpose of the TX Enable pin and you are trying to come up with some convoluted method to do exactly what TX Enable actually does.
Under normal circumstances, in RS485, the UART's RX pin is connected to the bus.  When TX Enable is asserted the RX pin is disconnected and the TX pin is connected, thus allowing any node on the bus to be a transmitter and all the other nodes a receiver.
The main thing to watch out for though is that only one node is ever a transmitter at a time, otherwise you get a collision which means that the data is completely garbled.
The simplest way of stopping that happening is to have one node nominated as the master and all the other nodes as slaves.  The master first initiates communication by making a request to a slave.  The slave will then respond with data (it becomes the transmitter and the master a receiver) to send data to the master.  That way the only node that is a transmitter is either the master making the request, or the slave that is responding to a request.
If you want "random" peer-to-peer communication where any node could become a transmitter at any time it becomes a whole lot more complex.  There are things you should implement to try to avoid, or deal with, collisions, including monitoring the bus and only transmitting after a certain amount of idle time has been detected, reading the bus while writing to it (requires more hardware) and confirming that the data you read from the bus is the same as the data you wrote to the bus, and random delays before retrying a failed communication.  That last one is probably the trickiest to get right, since random numbers on Arduinos aren't really random unless you "seed" them from a truly random source. You don't want both ends delaying for the same amount of time to retry otherwise it will never complete.

Since you apparently want to achieve that kind of thing but without using RS485, it all gets much more complex.
No, you cannot "swap" the functionality of the TX and RX pins in the Arduino.  BUT you can do serial communication (albeit somewhat heavyweight) using pure software.  Take a look at the SoftwareSerial library - you will most likely need to make modifications to that to achieve what you want.
To do it externally with hardware is possible, but the end result will most likely be more complex than just using a simple RS485 interface chip which are very inexpensive and easy to get hold of.
Yes, you could use relays (clunky) or buffers, or multiplexers, etc, but why would you when RS485 does what you want?

No, what I am trying to do is achieve the same sort of master/slave multi-node capability as RS485, but WITHOUT using RS485, just using the standard serial port TX and RX.

Ah, I see. Your question wasn't clear at all. You should make it more explicit in your question.

It was just a thought that popped into my head when I discovered my batch of RS485 interfaces came as conjoined siamese twins which I cannot snap apart even after scoring the join with a sharp blade, so I must now try to carefully hacksaw them apart.
If it was possible to achieve similar RS485 multi-node capability via software using the standard serial RX and TX it could have made my initial steps for developing arduino cluster capability using Nick Gammons RS485 library a liitle bit less 'hardwarey' is all, and perhaps may even have made the clunky little interfaces unnecessary.


text:
RS485 bus voltage?
Does anyone know the voltage situation regarding multi-drop nodes on an RS485 bus please?
Nick Gammons RS485 article shows 2 different hardware configurations, one using 5v devices, and another using 3.3v devices, and I am fairly sure my Pelco PTZ CCTV system uses 12v.
But I have never seen anything mentioned anywhere about needing to voltage-match nodes on an RS485 bus.
So I am unsure whether the MAX driver chips isolate the RS485 bus voltage from the mcu logic levels.
Or do any lower voltage devices (3.3v or 5v) need logic-level matching to their MAX driver chips, which all need powering from the higher bus level (perhaps 12v)?
Basically, I wish to add an 'intelligent' arduino controller to an existing ptz cctv system.

RS-485 is a differential bus. As long as the difference in voltage between the two lines reaches certain thresholds the signal can be interpreted unambiguously regardless of the system supply voltages. Isolation (from ground loops) is not provided by default by the driver, but can be implemented easily enough.

According to my datasheet for the LTC1480:

–7V to 12V Common Mode Range Permits ±7V Ground Difference Between Devices on the Data Line

Absolute maximum ratings

Supply Voltage (V CC ) : 7V
Driver Input Voltage  : – 0.3V to V CC + 0.3V
Driver Output Voltage : ±14V
Receiver Input Voltage : ±14V
Receiver Output Voltage : – 0.3V to V CC + 0.3V

I am fairly sure my Pelco PTZ CCTV system uses 12v.

Judging by the above you would need to drop Vcc on the part involving your 12V gadget and use level shifters for the logic levels (if you used this particular chip).

I suspect that the line-driver Vcc may be using a commercial standard of 5v which we are not aware off.
The RS485 Vcc VMax is only 7v anyway, so presumably the thousands of different 12v RS485 CCTV devices on the market must use line-drivers chips with a Vcc of 5v because they were historically assumed to be interfacing to TTL logic levels, and therefore still will be for compatibility.
So for integration, I think any 3.3v logic nodes will require level-matching up to a line-driver chip which has its Vcc connected to 5v for RS485 bus compatibility.
Line-driver Vcc would not normally be a problem for any home-brew systems, but could offer a potentially serious gotcha if mixing 3.3v home-brew with existing commercial 5v equipment.
I had been expecting it to be an already known problem, but apparently not, so it would seem to be something worth being aware of.


text:
Pelco D Library for Arduino
Does anyone know of any Pelco D libraries available for Arduino?
I already have a PTZ joystick controlling 3 PTZ cameras, but I would like to add an Arduino 'intelligent' controller capable of sending automated sequences of Pelco D commands according to various PIR triggers etc.

did you succeed in using the suggested library? Ho do I determine the address of the camera to be written in the sketch?

It looks like someone wrote a Pelco library. Check out:
https://github.com/Pixelbo/Pelco_And_Arduino


text:
Is there a practical way to broadcast and receive ascii payloads over ethernet or wifi?
How best might arduino nodes pass incoming serial ascii messages out as ascii network broadcasts for all others to receive and pass out through their serial ports?
ie: typing a msg from the IDE serial monitor of any ethernet node should cause that msg to be output to the serial monitors of all other nodes.

The magical trick you are looking for is Ethernet UDP Broadcast. By chance there is an example sketch in the Arduino Tutorial. I cannot say if it is up to date but this will help you get started.
Cheers!

That looks to be an excellent starting point for what I'm trying to do, thank you very much indeed Mikael.

Something crucial in the example is puzzling me...
The arduino is a listening UDP client which returns an acknowledgement to any sender(s). But the processing sketch which should be broadcasting a message seems to only be sending it to the specified client, rather than globally to all listening clients...
void keyPressed() {
String ip       = "192.168.1.177"; // remote IP address
int port        = 8888;        // destination port
udp.send("Hello World", ip, port );   // message to send
}
Is it possible to broadcast to all of the subnet by using something like 0 as the address byte?

More reading https://tkkrlab.nl/wiki/Arduino_UDP_multicast.