text:
ADXL345 hangs the micro-controller as vibrations increase
I am using ADXL345 accelerometer with Adafruit_ADXL345 library for vibration measurement.
I am reading acceleration at X, Y, Z-axis of a sensor placed on a vibrating platform.And serially sending it to PC at a baud rate of 115200.
When vibration is low sensor shows vibrations but as i increase the vibrations serial transmission seems to be halted. As shown in figure:(x-axis=Samples y-axis=Values )
I thought it may be due to loose connections so I soldered its terminals but it behaved the same way at higher vibrations.
 Here is the code that I’m using.
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_ADXL345_U.h>
/* Assign a unique ID to this sensor at the same time */

Adafruit_ADXL345_Unified accel = Adafruit_ADXL345_Unified(12);
int i=0;
struct measure
{
    int timestamp;
    float x;  // ACC in x direction
    float y;  //ACC in y direction
    float z;  //ACC in z direction
};
sensors_event_t event;
struct measure measurements;

int timestamp = 0;

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

  Serial.println("Accelerometer Test"); Serial.println("");

  /* Initialise the sensor */
  if(!accel.begin())
  {
    /* There was a problem detecting the ADXL345 ... check your connections */
    Serial.println("Ooops, no ADXL345 detected ... Check your wiring!");
    while(1);
  }
  accel.setDataRate(ADXL345_DATARATE_3200_HZ);
  accel.setRange(ADXL345_RANGE_16_G);
     pinMode(LED_BUILTIN, OUTPUT);
  delay(2000);
}

void loop(){

 accel.getEvent(&event);
   measurements.timestamp = timestamp++;
   measurements.x  = event.acceleration.x;
   measurements.y  = event.acceleration.y;
   measurements.z  = event.acceleration.z;

if(measurements.timestamp%2==0)
  digitalWrite(LED_BUILTIN, HIGH);
  else
    digitalWrite(LED_BUILTIN, LOW);

  /* Sending the array with data through serial*/

  Serial.print(measurements.timestamp);
 Serial.print(",");
 Serial.print(measurements.x+0.06);
 Serial.print(",");
 Serial.print(measurements.y+0.7);
 Serial.print(",");
 Serial.println(measurements.z-10.10);
}

Where does problem lie? How to resolve this issue?
Circuit Connections:

After a quick look at the Adafruit code I'd expect it to return zero or junk even if the ADXL stopped working. Is the Arduino subject to vibration as well? I'd try removing the accelerometer code and just transmit 'ABC' or something and see if it still stops due to a hardware problem.

If i remove the accelerometer code and transmit anything, it prints perfectly without any problem (with or without subjecting arduino to vibration)

The Adafruit example has a delay at the end of the loop and you don't. Perhaps you might be transmitting too much data via the serial port. If you want maximum speed, try the SPI bus. You could try an other library, search on Github.com for adxl345. What do you want to do ? How many samples per second do you want ?

Maybe the vibration is shaking your wires loose and breaking communication...

@MasoodSalik - (a) From a quick read of the Arduino & Adafruit I2C code, there is no "hardening" to cope with I2C errors. (b) I see no evidence that the micro-controller is hanging - the code could be in a loop with no timeout (for example). It's important not to blame the MCU prematurely. I recommend you view the I2C signals, ideally using a 'scope, otherwise with a logic analyser(LA), both before and after the problem. Even better if your scope or LA can trigger on the start of the problem. (c) "x-axis=Samples y-axis=Samples" I doubt that - perhaps x-axis = samples & y-axis = values?

(d) It's unclear which axis the red (R), green (G) & blue (B) lines represent, and why they are centred on different values e.g. R centred on +10, B centred on 0 and G centred on -8. Please explain. (e) Compare the "stuck values" on each axis after the start of the problem on several tests. Is the G line always "stuck" on a very different value than R & B? (f) It would also be interesting if you can test increasing G-force on one axis at a time, and reviewing sensor response until problem occurs.

I have also your problem with adxl and micro did you solved?
can you help me?
my email : m.amir.kom@gmail.com

There is a known issue with the default "Wire" library, where if a certain transition is missed, the code goes into an infinite loop (rather than timing out). You possibly are reaching that situation. A possible reason is your printing of numbers at quite a high baud rate. The printing could be taking up so much time (itself causing serial interrupts as the serial buffer empties) that the I2C code doesn't execute in time the I2C interrupt.
You could try dropping the printing baud rate (something I wouldn't normally recommend) which means the serial interrupts would occur less frequently.
There is a library by DSS Circuits that has a time-out for I2C which may work around this issue to an extent:
http://dsscircuits.com/articles/arduino-i2c-master-library
Another thing you could try would be to summarize the data (eg. sample for 500 ms and then send the average), which would reduce the amount of serial comms.

Also you might try lower values for the pull-up resistors, like 4.7k.

So, my recommendations are:

Drop the baud rate (eg. to 9600 baud) and see if the hanging goes away
Summarize data rather than sending each reading
Try 4.7k pull-up resistors

If you have a logic analyzer you could look at the I2C signals and see if you can work out if the data is being transmitted as expected when the vibrations occur.
Saleae sell logic analyzers, the cheapest being $US 109. I use their (more expensive) analyzers extensively for debugging this sort of thing.


text:
Do I need to run an expand drive sketch if I update the Yun Firmware subsequent to expanding?
I have a Geeetech Iduino Yun shield, that initially had Geetech's System image (v2.02, 2015) on it. I then ran a USB storage expander sketch to take advantage of the space on a flash drive. I then installed a number of packages (such as vim). I subsequently flashed/updated the firmware with Dragino v2 yun-4.1.2 sysupgrade firmware, only to find that vim and other packages have disappeared, as well as my Python code.
Has the update undone the expansion and is the Linux system now confined to what's provided by the firmware? Do I need to run an expansion sketch and install packages again?

After upgrading the firmware and rebooting:

Log in to your Yun through your browser and use the LuCI interface.
Navigate to "System" > "Software" and observe the "Free space" meter. You will see that the total space shown is between 800KB and 1MB, instead of the size of your flash drive. This indicates that the system is that of the memory available on the board.

Yes, you will need to run the expander sketch again and reinstall software that was previously there. (You might want to back up the contents of the drive beforehand, using a PC running GNU/Linux.)

source: Stack Exchange

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

sort: votes


text:
Is the LGT8F328P legal?
Since some months, everyone can buy a board with this IC.
It is compatible with the ATMega328 and has some features like 12bit ADC (instead of 10 bit), DAC, unique ID and also 32MHz.
But I can't find it in the "normal" shops. Also on the LCSC it is not available. Only in this shop:
https://www.electrodragon.com/product/5pcs-logicgreen-lgt8f328p/
For 0.68$ compared to the 2$ for the atmega326P-AU of the other electronic parts shops (it is cheaper than the cheapest attiny with ADC!)
So the question. Is this chip just a clone for private use or can it be used as official alternative to the more expensive and original ATMega328?

My understanding is that it is legal since it is just engineered to be (somewhat) compatible with ATmega328p but their difference are substantial if you deep dive.
It has a RISC core and its core instructions are quite different from ATmega328p. Most multi-cycle instructions are replaced by single-cycle instructions or less cycle instructions. And the core runs at 32Mhz from 1.8V-5.5V.
The peripheral registers are largely (backward) compatible with ATmega328. However, LGT has more or advanced peripherals.

2 16-bit timers, with capture and compare output
ADC has 12 bits instead of 10.
DAC, so you don't need PWM to emulate DAC.
9 high current PWM. 3 complementary PWM with dead band control.
PGA 1x-32x differential amp. Which saved me 1 op-amp.
16 bit computing accelerator/Co-processor.
High and adjustable current GPIO (so you can light up LEDs without current limiting resistors).
These peripherals provide lots of additional registers for control and status reporting that don't exist on ATmega.

Development environment is also different. The best way for hobbyists to develop on this chip is either using LGT Arduino Core but not ATmega328 Arduino Core:
https://github.com/dbuezas/lgt8fx  (Arduino IDE)
or
https://community.platformio.org/t/how-to-add-lgt8fx-board/13294 (PlatformIO) Or you can use their official SDK for development which is very different from AVR's environment.
LGT8F328p also has SSOP20 and LFP48 package offering smaller or larger number of GPIOs, which are not so well known by DIY community since they are not similar to ATmega328p.
So in general LGT is a different, forward engineered chip and highly unlikely a direct silicon clone copied by reverse engineering.
In general having peripheral registers and pin compatibility are not illegal, unless the IP core of the peripherals are stolen from ATmega328p. And since CPU instructions (and clock trees) are quite different, if assembly language is used for development, developer would likely feel they are two distinct MCUs. It is just that a C compiler and Arduino framework can hide those details and make them similar.
However, the laws and regulations differ across countries and states so I am not sure if that applied to all markets. And there is natural murkiness in what is an IP and what is not. In software, API similarity could result in infringement but in the world of MCU pin compatibility would not, despite they are both "interface similarity" issues.

Legal or not, I DO NOT reccomend this clone. It is similar and compatible to some extend but it lacks features like an EEPROM. With fuses you can only reserve some FLASH to emulate an EEPROM. Thus have less space for your code.
Also the manual is only available in chinese. There are english translations but those are hard to read as the layout got screwed up.
It has some new features that sound great but I would not see them as replacement for the ATmega328P from Atmel/Microchip.
I bought an Arduino clone with LGT8F328P by accident. I find it barely usable as there are itches here and there which I don't want to deal with.

time has passed and this alterative has become more and more popular, documentation and even Arduino support appeared. Having successfully used it in a product with no more headaches (including after-sales) than the Ex-Atmel Microchip counterparts, I think this answer could use some updates.

As legal as any other clone CPU / MCU.  See

Intel vs The World

In short:  if you copy the silicon design it's illegal. If you create it yourself from the ground up it's legal.
However, IANAL, so don't quote me on that.

Yes, I can remember the Cyrix fight! If I remember it correctly, it was not 100% compatible and a "Windows bug" made the OS working only on Intels, right? It would be nice to find out why this processor is only sold by this seller and not from digikey, farnell or mouser.

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


text:
Arduino Due DAC pins with 0V
I know the DACs on the Arduino Due only allow for a range of output voltages from 1/6*Vdd to 5/6*Vdd (see here). This suits my needs, for the most part.
My question is if it is possible to have 0V on the DAC pins by, for example, switching the DACs of completely, or using them as normal digital out pins. I'd like to do this without the need for any external hardware or circuitry.
I googled for solutions but found none.

The DAC is port B15 and B16 so yes, it is possible to disable the DAC and use those pins as normal GPIO pins. Not sure how you would do it though, if the Arduino definitions have those pins set up for GPIO or not (away from my computer at the moment).

It's apparently not possible. This answer covers the topic very precisely. https://arduino.stackexchange.com/a/25843/16623

authors: Антон Карзаков

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


text:
How do interrupts work on the Arduino Uno and similar boards?
Please explain how interrupts work on the Arduino Uno and related boards using the ATmega328P processor. Boards such as the:

Uno
Mini
Nano
Pro Mini
Lilypad

In particular please discuss:

What to use interrupts for
How to write an Interrupt Service Routine (ISR)
Timing issues
Critical sections
Atomic access to data

Note: this is a reference question.

TL;DR :
When writing an Interrupt Service Routine (ISR):

Keep it short
Don't use delay ()
Don't do serial prints
Make variables shared with the main code volatile
Variables shared with main code may need to be protected by "critical sections" (see below)
Don't try to turn interrupts off or on

What are interrupts?
Most processors have interrupts. Interrupts let you respond to "external" events while doing something else. For example, if you are cooking dinner you may put the potatoes on to cook for 20 minutes. Rather than staring at the clock for 20 minutes you might set a timer, and then go watch TV. When the timer rings you "interrupt" your TV viewing to do something with the potatoes.

Example of interrupts
const byte LED = 13;
const byte SWITCH = 2;

// Interrupt Service Routine (ISR)
void switchPressed ()
{
  if (digitalRead (SWITCH) == HIGH)
    digitalWrite (LED, HIGH);
  else
    digitalWrite (LED, LOW);
}  // end of switchPressed

void setup ()
{
  pinMode (LED, OUTPUT);  // so we can update the LED
  pinMode (SWITCH, INPUT_PULLUP);
  attachInterrupt (digitalPinToInterrupt (SWITCH), switchPressed, CHANGE);  // attach interrupt handler
}  // end of setup

void loop ()
{
  // loop doing nothing
}

This example shows how, even though the main loop is doing nothing, you can turn the LED on pin 13 on or off, if the switch on pin D2 is pressed.
To test this, just connect a wire (or switch) between D2 and Ground. The internal pullup (enabled in setup) forces the pin HIGH normally. When grounded, it becomes LOW. The change in the pin is detected by a CHANGE interrupt, which causes the Interrupt Service Routine (ISR) to be called.
In a more complicated example, the main loop might be doing something useful, like taking temperature readings, and allow the interrupt handler to detect a button being pushed.

Converting pin numbers to interrupt numbers
To simplify converting interrupt vector numbers to pin numbers you can call the function digitalPinToInterrupt(), passing a pin number. It returns the appropriate interrupt number, or NOT_AN_INTERRUPT (-1).
For example, on the Uno, pin D2 on the board is interrupt 0 (INT0_vect from the table below).
Thus these two lines have the same effect:
  attachInterrupt (0, switchPressed, CHANGE);    // that is, for pin D2
  attachInterrupt (digitalPinToInterrupt (2), switchPressed, CHANGE);

However the second one is easier to read and more portable to different Arduino types.

Available interrupts
Below is a list of interrupts, in priority order, for the Atmega328:
 1  Reset
 2  External Interrupt Request 0  (pin D2)          (INT0_vect)
 3  External Interrupt Request 1  (pin D3)          (INT1_vect)
 4  Pin Change Interrupt Request 0 (pins D8 to D13) (PCINT0_vect)
 5  Pin Change Interrupt Request 1 (pins A0 to A5)  (PCINT1_vect)
 6  Pin Change Interrupt Request 2 (pins D0 to D7)  (PCINT2_vect)
 7  Watchdog Time-out Interrupt                     (WDT_vect)
 8  Timer/Counter2 Compare Match A                  (TIMER2_COMPA_vect)
 9  Timer/Counter2 Compare Match B                  (TIMER2_COMPB_vect)
10  Timer/Counter2 Overflow                         (TIMER2_OVF_vect)
11  Timer/Counter1 Capture Event                    (TIMER1_CAPT_vect)
12  Timer/Counter1 Compare Match A                  (TIMER1_COMPA_vect)
13  Timer/Counter1 Compare Match B                  (TIMER1_COMPB_vect)
14  Timer/Counter1 Overflow                         (TIMER1_OVF_vect)
15  Timer/Counter0 Compare Match A                  (TIMER0_COMPA_vect)
16  Timer/Counter0 Compare Match B                  (TIMER0_COMPB_vect)
17  Timer/Counter0 Overflow                         (TIMER0_OVF_vect)
18  SPI Serial Transfer Complete                    (SPI_STC_vect)
19  USART Rx Complete                               (USART_RX_vect)
20  USART, Data Register Empty                      (USART_UDRE_vect)
21  USART, Tx Complete                              (USART_TX_vect)
22  ADC Conversion Complete                         (ADC_vect)
23  EEPROM Ready                                    (EE_READY_vect)
24  Analog Comparator                               (ANALOG_COMP_vect)
25  2-wire Serial Interface  (I2C)                  (TWI_vect)
26  Store Program Memory Ready                      (SPM_READY_vect)

Internal names (which you can use to set up ISR callbacks) are in brackets.
Warning: If you misspell the interrupt vector name, even by just getting the capitalization wrong (an easy thing to do) the interrupt routine will not be called, and you will not get a compiler error.

Reasons to use interrupts
The main reasons you might use interrupts are:

To detect pin changes (eg. rotary encoders, button presses)
Watchdog timer (eg. if nothing happens after 8 seconds, interrupt me)
Timer interrupts - used for comparing/overflowing timers
SPI data transfers
I2C data transfers
USART data transfers
ADC conversions (analog to digital)
EEPROM ready for use
Flash memory ready

The "data transfers" can be used to let a program do something else while data is being sent or received on the serial port, SPI port, or I2C port.
Wake the processor
External interrupts, pin-change interrupts, and the watchdog timer interrupt, can also be used to wake the processor up. This can be very handy, as in sleep mode the processor can be configured to use a lot less power (eg. around 10 microamps). A rising, falling, or low-level interrupt can be used to wake up a gadget (eg. if you press a button on it), or a "watchdog timer" interrupt might wake it up periodically (eg. to check the time or temperature).
Pin-change interrupts could be used to wake the processor if a key is pressed on a keypad, or similar.
The processor can also be awoken by a timer interrupt (eg. a timer reaching a certain value, or overflowing) and certain other events, such as an incoming I2C message.

Enabling / disabling interrupts
The "reset" interrupt cannot be disabled. However the other interrupts can be temporarily disabled by clearing the global interrupt flag.
Enable interrupts
You can enable interrupts with the function call "interrupts" or "sei" like this:
interrupts ();  // or ...
sei ();         // set interrupts flag

Disable interrupts
If you need to disable interrupts you can "clear" the global interrupt flag like this:
noInterrupts ();  // or ...
cli ();           // clear interrupts flag

Either method has the same effect, using interrupts / noInterrupts is a bit easier to remember which way around they are.
The default in the Arduino is for interrupts to be enabled. Don't disable them for long periods or things like timers won't work properly.
Why disable interrupts?
There may be time-critical pieces of code that you don't want interrupted, for example by a timer interrupt.
Also if multi-byte fields are being updated by an ISR then you may need to disable interrupts so that you get the data "atomically". Otherwise one byte may be updated by the ISR while you are reading the other one.
For example:
noInterrupts ();
long myCounter = isrCounter;  // get value set by ISR
interrupts ();

Temporarily turning off interrupts ensures that isrCounter (a counter set inside an ISR) does not change while we are obtaining its value.
Warning: if you are not sure if interrupts are already on or not, then you need to save the current state and restore it afterwards. For example, the code from the millis() function does this:
unsigned long millis()
{
  unsigned long m;
  uint8_t oldSREG = SREG;    // <--------- save status register

  // disable interrupts while we read timer0_millis or we might get an
  // inconsistent value (e.g. in the middle of a write to timer0_millis)
  cli();
  m = timer0_millis;
  SREG = oldSREG;            // <---------- restore status register including interrupt flag

  return m;
}

Note the indicated lines save the current SREG (status register) which includes the interrupt flag. After we have obtained the timer value (which is 4 bytes long) we put the status register back how it was.

Tips
Function names
The functions cli / sei and the register SREG are specific to the AVR processors. If you are using other processors such as the ARM ones the functions may be slightly different.
Disabling globally vs disabling one interrupt
If you use cli() you disable all interrupts (including timer interrupts, serial interrupts, etc.).
However if you just want to disable a particular interrupt then you should clear the interrupt-enable flag for that particular interrupt source. For example, for external interrupts, call detachInterrupt().

What is interrupt priority?
Since there are 25 interrupts (other than reset) it is possible that more than one interrupt event might occur at once, or at least, occur before the previous one is processed. Also an interrupt event might occur while interrupts are disabled.
The priority order is the sequence in which the processor checks for interrupt events. The higher up the list, the higher the priority. So, for example, an External Interrupt Request 0 (pin D2) would be serviced before External Interrupt Request 1 (pin D3).

Can interrupts occur while interrupts are disabled?
Interrupts events (that is, noticing the event) can occur at any time, and most are remembered by setting an "interrupt event" flag inside the processor. If interrupts are disabled, then that interrupt will be handled when they are enabled again, in priority order.

How do you use interrupts?

You write an ISR (interrupt service routine). This is called when the interrupt occurs.
You tell the processor when you want the interrupt to fire.

Writing an ISR
Interrupt Service Routines are functions with no arguments. Some Arduino libraries are designed to call your own functions, so you just supply an ordinary function (as in the examples above), eg.
// Interrupt Service Routine (ISR)
void switchPressed ()
{
 flag = true;
}  // end of switchPressed

However if a library has not already provided a "hook" to an ISR you can make your own, like this:
volatile char buf [100];
volatile byte pos;

// SPI interrupt routine
ISR (SPI_STC_vect)
{
byte c = SPDR;  // grab byte from SPI Data Register

  // add to buffer if room
  if (pos < sizeof buf)
    {
    buf [pos++] = c;
    }  // end of room available
}  // end of interrupt routine SPI_STC_vect

In this case you use the "ISR" macro, and supply the name of the relevant interrupt vector (from the table earlier on). In this case the ISR is handling an SPI transfer completing. (Note, some old code uses SIGNAL instead of ISR, however SIGNAL is deprecated).
Connecting an ISR to an interrupt
For interrupts already handled by libraries, you just use the documented interface. For example:
void receiveEvent (int howMany)
 {
  while (Wire.available () > 0)
    {
    char c = Wire.receive ();
    // do something with the incoming byte
    }
}  // end of receiveEvent

void setup ()
  {
  Wire.onReceive(receiveEvent);
  }

In this case the I2C library is designed to handle incoming I2C bytes internally, and then call your supplied function at the end of the incoming data stream. In this case receiveEvent is not strictly an ISR (it has an argument) but it is called by an inbuilt ISR.
Another example is the "external pin" interrupt.
// Interrupt Service Routine (ISR)
void switchPressed ()
{
  // handle pin change here
}  // end of switchPressed

void setup ()
{
  attachInterrupt (digitalPinToInterrupt (2), switchPressed, CHANGE);  // attach interrupt handler for D2
}  // end of setup

In this case the attachInterrupt function adds the function switchPressed to an internal table, and in addition configures the appropriate interrupt flags in the processor.
Configuring the processor to handle an interrupt
The next step, once you have an ISR, is to tell the processor that you want this particular condition to raise an interrupt.
As an example, for External Interrupt 0 (the D2 interrupt) you could do something like this:
EICRA &= ~3;  // clear existing flags
EICRA |= 2;   // set wanted flags (falling level interrupt)
EIMSK |= 1;   // enable it

More readable would be to use the defined names, like this:
EICRA &= ~(bit(ISC00) | bit (ISC01));  // clear existing flags
EICRA |= bit (ISC01);    // set wanted flags (falling level interrupt)
EIMSK |= bit (INT0);     // enable it

EICRA (External Interrupt Control Register A) would be set according to this table from the Atmega328 datasheet.
That defines the exact type of interrupt you want:

0: The low level of INT0 generates an interrupt request (LOW interrupt).
1: Any logical change on INT0 generates an interrupt request (CHANGE interrupt).
2: The falling edge of INT0 generates an interrupt request (FALLING interrupt).
3: The rising edge of INT0 generates an interrupt request (RISING interrupt).

EIMSK (External Interrupt Mask Register) actually enables the interrupt.
Fortunately you don't need to remember those numbers because attachInterrupt does that for you. However that is what is actually happening, and for other interrupts you may have to "manually" set interrupt flags.

Low-level ISRs vs. library ISRs
To simplify your life some common interrupt handlers are actually inside library code (for example INT0_vect and INT1_vect) and then a more user-friendly interface is provided (eg. attachInterrupt). What attachInterrupt actually does is save the address of your wanted interrupt handler into a variable, and then call that from INT0_vect / INT1_vect when needed. It also sets the appropriate register flags to call the handler when required.

Can ISRs be interrupted?
In short, no, not unless you want them to be.
When an ISR is entered, interrupts are disabled. Naturally they must have been enabled in the first place, otherwise the ISR would not be entered. However to avoid having an ISR itself be interrupted, the processor turns interrupts off.
When an ISR exits, then interrupts are enabled again. The compiler also generates code inside an ISR to save registers and status flags, so that whatever you were doing when the interrupt occurred will not be affected.
However you can turn interrupts on inside an ISR if you absolutely must, eg.
// Interrupt Service Routine (ISR)
void switchPressed ()
{
  // handle pin change here
  interrupts ();  // allow more interrupts

}  // end of switchPressed

Normally you would need a pretty good reason to do this, as another interrupt now could result in a recursive call to pinChange, with quite possibly undesirable results.

How long does it take to execute an ISR?
According to the datasheet, the minimal amount of time to service an interrupt is 4 clock cycles (to push the current program counter onto the stack) followed by the code now executing at the interrupt vector location. This normally contains a jump to where the interrupt routine really is, which is another 3 cycles. Examination of the code produced by the compiler shows that an ISR made with the "ISR" declaration can take around 2.625 µs to execute, plus whatever the code itself does. The exact amount depends on how many registers need to be saved and restored. The minimum amount would be 1.1875 µs.
The external interrupts (where you use attachInterrupt) do a bit more and take around 5.125 µs in total (running with a 16 MHz clock).

How long before the processor starts entering an ISR?
This varies somewhat. The figures quoted above are the ideal ones where the interrupt is immediately processed. A few factors may delay that:

If the processor is asleep, there are designated "wake-up" times, which could be quite a few milliseconds, while the clock is spooled back up to speed. This time would depend on fuse settings, and how deep the sleep is.
If an interrupt service routine is already executing, then further interrupts cannot be entered until it either finishes, or enables interrupts itself. This is why you should keep each interrupt service routine short, as every microsecond you spend in one, you are potentially delaying the execution of another one.
Some code turns interrupts off. For example, calling millis() briefly turns interrupts off. Therefore the time for an interrupt to be serviced would be extended by the length of time interrupts were turned off.
Interrupts can only be serviced at the end of an instruction, so if a particular instruction takes three clock cycles, and has just started, then the interrupt will be delayed at least a couple of clock cycles.
An event that turns interrupts back on (eg. returning from an interrupt service routine) is guaranteed to execute at least one more instruction. So even if an ISR ends, and your interrupt is pending, it still has to wait for one more instruction before it is serviced.
Since interrupts have a priority, a higher-priority interrupt might be serviced before the interrupt you are interested in.

Performance considerations
Interrupts can increase performance in many situations because you can get on with the "main work" of your program without having to constantly be testing to see if switches have been pressed. Having said that, the overhead of servicing an interrupt, as discussed above, would actually be more than doing a "tight loop" polling a single input port. You can barely respond to an event within, say, a microsecond. In that case you might disable interrupts (eg. timers) and just loop looking for the pin to change.

How are interrupts queued?
There are two sorts of interrupts:

Some set a flag and they are handled in priority order, even if the event that caused them has stopped. For example, a rising, falling, or changing level interrupt on pin D2.
Others are only tested if they are happening "right now". For example, a low-level interrupt on pin D2.

The ones that set a flag could be regarded as being queued, as the interrupt flag remains set until such time as the interrupt routine is entered, at which time the processor clears the flag. Of course, since there is only one flag, if the same interrupt condition occurs again before the first one is processed, it won't be serviced twice.
Something to be aware of is that these flags can be set before you attach the interrupt handler. For example, it is possible for a rising or falling level interrupt on pin D2 to be "flagged", and then as soon as you do an attachInterrupt the interrupt immediately fires, even if the event occurred an hour ago. To avoid this you can manually clear the flag. For example:
EIFR = bit (INTF0);  // clear flag for interrupt 0
EIFR = bit (INTF1);  // clear flag for interrupt 1

However the "low level" interrupts are continuously checked, so if you are not careful they will keep firing, even after the interrupt has been called. That is, the ISR will exit, and then the interrupt will immediately fire again. To avoid this, you should do a detachInterrupt immediately after you know that the interrupt fired.

Hints for writing ISRs
In brief, keep them short! While an ISR is executing other interrupts cannot be processed. So you could easily miss button presses, or incoming serial communications, if you try to do too much. In particular, you should not try to do debugging "prints" inside an ISR. The time taken to do those is likely to cause more problems than they solve.
A reasonable thing to do is set a single-byte flag, and then test that flag in the main loop function. Or, store an incoming byte from a serial port into a buffer. The inbuilt timer interrupts keep track of elapsed time by firing every time the internal timer overflows, and thus you can work out elapsed time by knowing how many times the timer overflowed.
Remember, inside an ISR interrupts are disabled. Thus hoping that the time returned by millis() function calls will change, will lead to disappointment. It is valid to obtain the time that way, just be aware that the timer is not incrementing. And if you spend too long in the ISR then the timer may miss an overflow event, leading to the time returned by millis() becoming incorrect.
A test shows that, on a 16 MHz Atmega328 processor, a call to micros() takes 3.5625 µs. A call to millis() takes 1.9375 µs. Recording (saving) the current timer value is a reasonable thing to do in an ISR. Finding the elapsed milliseconds is faster than the elapsed microseconds (the millisecond count is just retrieved from a variable). However the microsecond count is obtained by adding the current value of the Timer 0 timer (which will keep incrementing) to a saved "Timer 0 overflow count".
Warning: Since interrupts are disabled inside an ISR, and since the latest version of the Arduino IDE uses interrupts for Serial reading and writing, and also for incrementing the counter used by "millis" and "delay" you should not attempt to use those functions inside an ISR. To put it another way:

Don't attempt to delay, eg: delay (100);
You can get the time from a call to millis, however it won't increment, so don't attempt to delay by waiting for it to increase.
Don't do serial prints (eg. Serial.println ("ISR entered"); )
Don't try to do serial reading.

Pin change interrupts
There are two ways you can detect external events on pins. The first is the special "external interrupt" pins, D2 and D3. These general discrete interrupt events, one per pin. You can get to those by using attachInterrupt for each pin. You can specify a rising, falling, changing or low-level condition for the interrupt.
However there are also "pin change" interrupts for all pins (on the Atmega328, not necessarily all pins on other processors). These act on groups of pins (D0 to D7, D8 to D13, and A0 to A5). They are also lower priority than the external event interrupts. However they are a bit more fiddly to use than the external interrupts because they are grouped into batches. So if the interrupt fires you have to work out in your own code exactly which pin caused the interrupt.
Example code:
ISR (PCINT0_vect)
 {
 // handle pin change interrupt for D8 to D13 here
 }  // end of PCINT0_vect

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

ISR (PCINT2_vect)
 {
 // handle pin change interrupt for D0 to D7 here
 }  // end of PCINT2_vect

void setup ()
  {
  // pin change interrupt (example for D9)
  PCMSK0 |= bit (PCINT1);  // want pin 9
  PCIFR  |= bit (PCIF0);   // clear any outstanding interrupts
  PCICR  |= bit (PCIE0);   // enable pin change interrupts for D8 to D13
  }

To handle a pin change interrupt you need to:

Specify which pin in the group. This is the PCMSKn variable (where n is 0, 1 or 2 from the table below). You can have interrupts on more than one pin.
Enable the appropriate group of interrupts (0, 1 or 2)
Supply an interrupt handler as shown above

Table of pins -> pin change names / masks
D0    PCINT16 (PCMSK2 / PCIF2 / PCIE2)
D1    PCINT17 (PCMSK2 / PCIF2 / PCIE2)
D2    PCINT18 (PCMSK2 / PCIF2 / PCIE2)
D3    PCINT19 (PCMSK2 / PCIF2 / PCIE2)
D4    PCINT20 (PCMSK2 / PCIF2 / PCIE2)
D5    PCINT21 (PCMSK2 / PCIF2 / PCIE2)
D6    PCINT22 (PCMSK2 / PCIF2 / PCIE2)
D7    PCINT23 (PCMSK2 / PCIF2 / PCIE2)
D8    PCINT0  (PCMSK0 / PCIF0 / PCIE0)
D9    PCINT1  (PCMSK0 / PCIF0 / PCIE0)
D10   PCINT2  (PCMSK0 / PCIF0 / PCIE0)
D11   PCINT3  (PCMSK0 / PCIF0 / PCIE0)
D12   PCINT4  (PCMSK0 / PCIF0 / PCIE0)
D13   PCINT5  (PCMSK0 / PCIF0 / PCIE0)
A0    PCINT8  (PCMSK1 / PCIF1 / PCIE1)
A1    PCINT9  (PCMSK1 / PCIF1 / PCIE1)
A2    PCINT10 (PCMSK1 / PCIF1 / PCIE1)
A3    PCINT11 (PCMSK1 / PCIF1 / PCIE1)
A4    PCINT12 (PCMSK1 / PCIF1 / PCIE1)
A5    PCINT13 (PCMSK1 / PCIF1 / PCIE1)

Interrupt handler processing
The interrupt handler would need to work out which pin caused the interrupt if the mask specifies more than one (eg. if you wanted interrupts on D8/D9/D10). To do this you would need to store the previous state of that pin, and work out (by doing a digitalRead or similar) if this particular pin had changed.

You are probably using interrupts anyway ...
A "normal" Arduino environment already is using interrupts, even if you don't personally attempt to. The millis() and micros() function calls make use of the "timer overflow" feature. One of the internal timers (timer 0) is set up to interrupt roughly 1000 times a second, and increment an internal counter which effectively becomes the millis() counter. There is a bit more to it than that, as adjustment is made for the exact clock speed.
Also the hardware serial library uses interrupts to handle incoming and outgoing serial data. This is very useful as your program can be doing other things while the interrupts are firing, and filling up an internal buffer. Then when you check Serial.available() you can find out what, if anything, has been placed in that buffer.

Executing the next instruction after enabling interrupts
After a bit of discussion and research on the Arduino forum, we have clarified exactly what happens after you enable interrupts. There are three main ways I can think of that you can enable interrupts, which were previously not enabled:
  sei ();  // set interrupt enable flag
  SREG |= 0x80;  // set the high-order bit in the status register
  reti  ;   // assembler instruction "return from interrupt"

In all cases, the processor guarantees that the next instruction after interrupts are enabled (if they were previously disabled) will always be executed, even if an interrupt event is pending. (By "next" I mean the next one in program sequence, not necessarily the one physically following. For example, a RETI instruction jumps back to where the interrupt occurred, and then executes one more instruction).
This lets you write code like this:
sei ();
sleep_cpu ();

If not for this guarantee, the interrupt might occur before the processor slept, and then it might never be awoken.

Empty interrupts
If you merely want an interrupt to wake the processor, but not do anything in particular, you can use the EMPTY_INTERRUPT define, eg.
EMPTY_INTERRUPT (PCINT1_vect);

This simply generates a "reti" (return from interrupt) instruction. Since it doesn't try to save or restore registers this would be the fastest way to get an interrupt to wake it up.

Critical sections (atomic variable access)
There are some subtle issues regarding variables which are shared between interrupt service routines (ISRs) and the main code (that is, the code not in an ISR).
Since an ISR can fire at any time when interrupts are enabled, you need to be cautious about accessing such shared variables, as they may be being updated at the very moment you access them.
First ... when do you use "volatile" variables?
A variable should only be marked volatile if it is used both inside an ISR, and outside one.

Variables only used outside an ISR should not be volatile.
Variables only used inside an ISR should not be volatile.
Variables used both inside and outside an ISR should be volatile.

eg.
volatile int counter;

Marking a variable as volatile tells the compiler to not "cache" the variables contents into a processor register, but always read it from memory, when needed. This may slow down processing, which is why you don't just make every variable volatile, when not needed.
Turn interrupts off while accessing a volatile variable
For example, to compare count to some number, turn interrupts off during the compare in case one byte of count has been updated by the ISR and not the other byte.
volatile unsigned int count;

ISR (TIMER1_OVF_vect)
  {
  count++;
  } // end of TIMER1_OVF_vect

void setup ()
  {
  pinMode (13, OUTPUT);
  }  // end of setup

void loop ()
  {
  noInterrupts ();    // <------ critical section
  if (count > 20)
     digitalWrite (13, HIGH);
  interrupts ();      // <------ end critical section
  } // end of loop

Read the data sheet!
More information about interrupts, timers, etc. can be obtained from the data sheet for the processor.
http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf

Further examples
Space considerations (post size limit) prevent my listing more example code. For more example code see my page about interrupts.

A very useful reference-that was an impressively  quick answer.

It was a reference question. I had the answer prepared and it would have been even faster if the answer hadn't been too long, so I had to prune it back. See the linked site for more details.

About the "sleep mode" is it efficient to make the Arduino sleep for, let's say, 500ms?

@Nick Gammon I guess turning the power on or off (with automation or not) for the CPU can be defined as an unconventional interrupt- if you wanted to do that. "I had the answer prepared "-you just took out all the magic of that moment I thought it had.

is it efficient to make the Arduino sleep for, let's say, 500ms - certainly it is. I have a project that flashes an LED every second or so, and sleeps inbetween. The much lower power consumption when asleep saves a lot of battery power.

I guess turning the power on or off (with automation or not) for the CPU can be defined as an unconventional interrupt - turning the power off and on would cause a Reset "interrupt".

Just some notes: - Mechanical bouncing should be mentioned in the Example of interrupts. - Not every interrupt source can be used to wake up CPU in most sleep modes. - You can miss interrupt if there was more than one event during processing another ISR or critical section. (in section Can interrupt occur ...). - If you need only flag without knowing how many times, you can use corresponding flag without enabling interrupt. Flag must be cleared manually by writing logic 1 (in section Hints). - Max frequency for pin change interrupts and its duty cycle (F_CPU/2 for 50:50)

I'm constrained here by the post size limit. I initially had about a 36000 byte post, which exceeded the 30000 byte limit. I trimmed it down to 29990 bytes and hit "Send" only to be informed that my post was 36000 bytes. I then deleted 6000 bytes to get it accepted. So if you want to suggest additions, you also have to suggest equivalent deletions. Sorry. :)

Yes, Something like Arduino "Documentation" from SO would be more suitable. Too bad, it's not available here.

Fantastic reference! A few comments: In Wake the processor: any interrupt can wake the CPU unless in deep sleep (sleep mode other than IDLE). In Enabling / disabling interrupts: since many flags are called “interrupt flag”, I would rather follow Atmel and use “global interrupt flag” for SREG(I). In Why disable interrupts?: replace “save/restore processor registers” → save/restore status register. Or you may want to document ATOMIC_BLOCK() instead of explicitly saving and restoring SREG... In Writing an ISR: "ISR" define → "ISR" macro.

In How long does it take to execute an ISR?: The length of the prologue and epilogue depends on how many registers the ISR needs. Minimum is 8 (prologue) and 11 (epilogue) CPU cycles. In How long before the processor starts entering an ISR?: various somewhat → varies somewhat. In Performance considerations: You may barely respond in 1 µs if there are no other interrupts enabled and no cli(). In You are probably using interrupts anyway ...: drop “in the more recent library versions”, it's been like this since 1.0-beta2 (released on August 2011).

@EdgarBonet - added most of your suggestions (I think).

@KIIV - Not every interrupt source can be used to wake up CPU in most sleep modes - which ones did you have in mind? If you need only flag without knowing how many times, you can use corresponding flag without enabling interrupt. - what is this referring to?

@NickGammon 1. For example Power-down sleep mode can be waked up only by WDT, TWI address match and by External interrupt (low level detection only). Pin change interrupts can wake the CPU only in Idle mode (External interrupts only low level detection). And so on. 2. It's referring to the second paragraph in section Hints for writing ISRs

I'm afraid that isn't true. I have an example that uses pin change interrupts to wake from power-down mode. Also as I mention on my page about interrupts Atmel have confirmed that any external interrupt will wake the processor (ie. rising/falling/change and low).

It's referring to the second paragraph in section Hints for writing ISRs - yes but there is nothing explicitly wrong about what I wrote is there? Certainly checking the flag can let you know an interrupt was signalled (as is done in micros).

Well, then it serves its purpose and I've just learned something really interesting (I just have to retest it).
And yes, there is nothing wrong about that paragraph. It's just possible to use interrupt flags directly instead of calling ISR and set another variable. (If it's possible and you don't need immediate response/action. If you have to know how many times event happened between checks, you have to use ISR and counter variable anyways)


text:
Sketches won't upload to Uno
Today I tried to update the sketch on my Arduino Uno, but was unable to due to this error:
Sketch uses 1,870 bytes (5%) of program storage space. Maximum is 32,256 bytes.
Global variables use 188 bytes (9%) of dynamic memory, leaving 1,860 bytes for local variables. Maximum is 2,048 bytes.
D:\Users\User\Desktop\arduino-1.6.10\hardware\tools\avr/bin/avrdude -CD:\Users\User\Desktop\arduino-1.6.10\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM4 -b115200 -D -Uflash:w:C:\Users\User\AppData\Local\Temp\build2f7b4a32c3810b2d8e42648954faba05.tmp/nes_controller.ino.hex:i
An error occurred while uploading the sketch

Nothing will upload to the board now. I tried uploading a simple sketch with empty setup() and loop() functions, I've tried different PCs and gotten the same error, I've swapped USB cables, I've double-checked that I'm using the right COM port, I've disconnected every wire from the Arduino pins - nothing has helped.
The old sketch is still running fine on the Uno. It was uploaded a few days ago using the exact same setup I'm trying right now.
The Arduino IDE doesn't even indicate any errors, everything compiles and looks good until "An error occurred while uploading the sketch"

I'm going to put this in a copy buffer I think...  "Do you have a genuine Arduino or a (sigh) cheap Chinese clone?"

Genuine Uno from Arduino.cc

Can you ask Arduino IDE to put some more verbosity (there is a preference for that IIRC)? Also how did you check that was the right COM port? Sometimes COM ports can change after a reboot. I always use listComPort.exe to check this first.

That's as verbose as it gets. No error description as to what happened. Ive tried different USB ports, Ive triple-checked the COM port.

You can set the verbosity level in the Arduino IDE:

File menu
Preferences
Settings tab
"Show verbose output during" => check "upload"
Click OK

Upload again, and note the additional output telling you what is wrong.
It should also point you to this URL, which points out the most occurring issues.
The issue I have most, is that I forget to switch between Micro and Uno board (as I deploy my sketch on both boards).

assumption is windows, so with the old ide's a reboot to free up the usb ports, or sometimes simply swapping the usb port, and changing the port in the tools > port menu.
does it identify the board you are using when you choose the port? (Genuino / Arduino)

Yes "Get Board Info" works and identifies my board.

This is a guess based on what I have encountered previously. With all the information given remember I just took a guess!
Is it possible you are experiencing a serial flood, ie it is constantly sending something to the console.
Take these steps several tries may be needed:

Power off the board completely
Remove the USB cable
Hold down the Reset button
keep it held down (or, run a jumper wire from the RESET pin to the GND pin).
Still holding down Reset reconnect the USB cable.
Start uploading a sketch that does not have this problem (I use the Blink sketch).
When you see the Receive light blink, release the Reset button
Note: I have seen this happen several times when I flood the serial output. An indication is the tx light is on.

You can check the hardware as follows.
Here is a trick I use on some boards but first be the baud rate is the same in the terminal as in the sketch (Serial.begin(115200). If so then remove everything then put a jumper between ground and reset. Then put a jumper between TX and RX (pin o and pin 1 on uno). launch the IDE and what you type in the console should be echoed back to you. If this works the hardware is connected fine.

In my experience, sketch upload error occurred due to 4 different mistakes:
(1) Silly mistake: did not connect the serial cable to the PC
(2) I did not choose the right com port (Tools/port).
(3) I chose the wrong board type (Tools/board). connected a Nano, but selected Uno while uploading.
(4) While updating my Arduino IDE to the a version, I failed to select 'download USB drivers' option. There are 2 or 3 of them.

right click on computer, manage, device manager and disable the usb driver and enable it again.

This answer does not provide enough detail for it to be useful to the OP. Please provide more info such as: on which OS you do what, screenshots to show each step. If you could also explain why that way shall work, that would be even better.

Tried, no change.

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


text:
Arduino connection confirmation
I am using Arduino Uno. I want to control my room lamp both manually and over the network, so when I switch off my lamp manually, how do I get acknowledgement over the network that lamp is off ?

Disconnect the switch from the lamp and instead connect it to a digital pin on the Arduino. Have the Arduino toggle the lamp when the switch changes position.

Or attach a lightsensor to see if the bulb is on.

@Gerben not nice.

Please read How do I ask a good question?. What do you mean by "manually"? What do you mean by "acknowledgement over the network"? I don't know why the above comments have been reported to the moderators.

@PhillyNJ could you explain what you mean by not nice? Do you mean it's unsafe to do so?

@Gerben - My mistake.- I read it wrong. Sorry


text:
EEPROM bytes preset to 255 while programming
I'm working on a program with Arduino Uno which involves writing and reading EEPROM. I'm using a basic EEPROM library. My problem is: EEPROM values are preset to 255 whenever I burn my program. And there is nothing in my code which will write 255 in these bytes.
I even tried EEPROM_read example from the EEPROM library and got same result. I used EEPROM_clear code before EEPROM_read to set all values to 0. But when I read those values using EEPROM_read, they are 255.
Please help explain what is happening.

See http://forum.arduino.cc/index.php?topic=106754.0

In flash and eeprom memory an erased value is 255. It's all about how flash memory works. If you want something other than 255 in there you will have to write something other than 255 in there.

I've written other values in EEPROM in my program, and those values are retained through program. But they are not retained when I re-flash the code. The EEPROM memory should be retained through multiple flashes.

Then you need, as @Cano64 has suggested, the EESAVE fuse setting. You can read more about setting fuses here: http://www.ladyada.net/learn/avr/avrdude.html - I don't know the Arduino bootloader well enough to say if you can do it through there or not - you may need a cheap hardware programmer (or another Arduino) to set the fuses through ICSP.

You need to set EESAVE fuse
When the ATmega chip is programmed the memory is erased just before the new code is uploaded. Under normal circumstances the eeprom memory is erased as well as the program memory. The EESAVE fuse can be used to tell the chip not to erase the eeprom. This is useful when you want to upgrade code but keep user settings that are stored in eeprom.
The default value is EESAVE=1, not set and eeprom memory is erased during the chip erase cycle when programming.
This fuse calculator is quite handy.

Yes, the fuse calculator is really handy for knowing fuses, but how do I change these fuses using arduino. I'm working on a project with standalone atmega328.

You need a programmer for it (it can be another arduino), maybe you should make a new question about how to set fuses on arduino.

I know that this is relatively an old topic but I wanted to express my experience here that this answer is the only solution to preserve EEPROM data. Once HIGH.EESAVE is set in your programmer, the EEPROM data will be preserved. My setup was AVRISP MKII and Atmel Studio 7.


text:
How to use Serial Monitor without Arduino board?
I want to use Arduino(atmega8) on breadboard using USBASP programmer and want to use Serial Monitor without using any Arduino board as ISP programmer.
My questions: 1. Is such thing possible?
2. How do I do that?

How to use Serial Monitor without Arduino board?

Yes that is possible. Connect to the RX/TX pins on the breadboard chip. Remember these are 5V. You will need an Serial-USB or RS232 adapter to connect your development machine. Please see this blog post for some inspiration.
Cheers!

Don't forget to also connect GND.

I stripped a USB cable and connected its green wire to RX and white wire to TX and red/black to supply pins of atmega8. But my PC is not detecting anything. (Atmega8 contains a arduino bootloader burnt using AVRDUDE and a basic analog to serial program. Please suggest where I am wrong.


text:
Water level Detection using Ultrasonic Sensor and arduino
I'm making a water level detector to control my motor which supplies water in water tank and for that I'm going to use ultrasonic sensor to be attached to tank lid. My question is whether the vapor arising from water inside the tank hamper the overall working of ultrasonic sensor and/or it may be damaged permanently. I can cover complete ultrasonic sensor using hot glue stick but cannot cover its diaphragm as it will block sound waves. Please suggest something.

You may be able to find a data sheet for the usual in-air transducers giving humidity limits.  You will not be able to seal them yourself without making them not work.  Sealed ones do exist for vehicle parking systems, but require different electronics.  Also beware minimum distances.

For fluid level measurement you are best off using a capacitive fluid level sensor.

I'm not sure if there is even an issue here. But you could try out different types of plastic bags, to see which are "transparent" to ultrasonic sound. Alternatively, just replacing the sensor every one or two year, wouldn't be that bad. Just make sure that your code accounts for a bad sensor (e.g. turn of the pump after 10 minutes regardless of the water level).

Plastic bag shields will not pass enough signal for the common sensors.

I am posting an answer just because I do not have enough reputation in order to comment. This is not a straight answer but more like a workaround. Have you tried using the system from a toilet water tank? also, you could put a floating magnet inside the tank (and limit its x-y movement) and a reed switch (or more) outside of the tank at the desired levels. Another idea (not sure of it works, depends on the water quantity) is to place a barometer on the bottom of the tank and measure the pressure.

Majenko, agreed.
Use some FM antenna cable, if you can find it. Insulate the lower end by dipping in molten heat glue.
Two rods, insulated with heat shrink tubing also works well.
Use LM393 dual comparator as Schmitt trigger and inverter. That will oscillate at  frequency dependant on the water level. Works well, recalibrate or clean the sensor when accuracy suffers due to being too dirty. should not be necessary more than annually.

A friend of mine worked on a liquid level monitoring project, and after many iterations finally abandoned the kinds of sensors you're talking about. Ultimately he just pointed a cheap USB webcam at the thing and used OpenCV and the edge detection algorithm to find the level of the water.  Then it's just a matter of doing some math using the dimensions of the container, to figure out how full it is.
If you are using a clear container and if you have the option of using a Raspberry Pi (or a PC, whatever) that can run OpenCV, you might find that option worth exploring.

Sensors exist for exactly your use case. Here is an example;
Maxbotix MB7589 Ultrasonic Sensor
I have used several of these to measure river levels. they are virtually indestructible and have all the features that you would expect;

Temperature compensation
Self heating to deal with humidity/condensation
serial output
1mm resolution


text:
Which Barcode Scanner to be used with arduino in India
I know this question is not so releavant as it does not include any research, but I am in search of a barcode scanner that i can easily interface with arduino and get output from it but unfortunately the Scanner models which are listed from the people doing the same stuff are not easily available in India. So if anyone knows which barcode scanner would best suit the requirement please suggest.
Availabilty in Indian market would be much appreciated :)

Most barcode scanners behave just like a regular keyboard.
Try getting one with a PS2 port. You can pretty easily interface a PS2 keyboard to an Arduino. There are already libraries for it.


text:
Controlling a digital 12V addressable RGB led strip with Arduino?
I have a 12V addressable RGB strip that I want to control with an Arduino, the chips are ws2811s, is there a way to do this as the Arduino is 5V and 3.3V?

Can you post a link to where you got them? What pins are on the strip?

How did you plug to arduino can you show me pictures or diagram? i also have 12v addressable rgb strip

The only signal you need to worry about is DIN (data in) which is normally 5V from an Arduino. Use that to switch a MOSFET or transistor to convert the digital pulses to 12V. In other words, the Arduino switches the transistor, the transistor outputs 0 or 12 V.

Judging by this link you still just send 5V digital switching to the strip.

The data signal never needs to be 12 volts. The 12 volt pixels all drop the voltage down to about 5 volts to operate the chip. Usually just a resistor and a zener diode, sometimes just a resistor.

In other words, connect the "power" pin to +12V, and the ground pin to Gnd from your power supply.
Connect the Din (data in) to your Arduino pin directly. Of course, also connect the Arduino ground to the ground pin.

Also see this Youtube video. On the comments he says:

These 12v WS2811 "pixels" still use 5v signalling. You simply connect the 12v source power directly to the strip, tie the ground to the arduino and then treat them as if they were a 5v strip.

So i could just hook up a TIP120 MOSFET between the arduino and the DIN?
Or could i just connect the strip as 12v and connect the ground to the arduino and treat it as a 5v strip?

No, I was wrong. See amended answer.

Got the strip from a local store, but it has 4 pins: VCC, 2 ground and DO/DIN, guessing the ground is common and i only need to use 1?

Got it working, cheers!

If it has 2 ground pins I would ground both of them, to be safe.


text:
Why have resistor at end of circuit cycle if GND dissipates final energy?
The first challenge on the Arduino Uno manual is to make a closed circuit with a button and LED. The voltage is provided by the 5V pin (non IO), connected by wire to (+) on the bus (breadboard). The wire connects to a resistor, which makes sense since it resists current running from source. The button connects to the resistor, if pushed, the button closes the circuit and current passes through LED (making it shine) and through a wire to GND.
OK. The second challenge makes no sense. The resistors are connected not to the 5V, but the GND. WHY? Doesn't current dissipate past at ground?? As if the GND is supplying power!? It's like flipping the anode/diode! Here's the challenge: .What is the logic behind connecting the resistors to GND and WHY DOES IT SUPPLY POWER? I'm not talking about the button, which step two somewhat explains but not why, but the LEDs. Thank you thank you thank you!!
EDIT: Ok, then. I am now being told current flows negative to positive. Fine, then why resistor connected to positive? Also, I was told that GND is there to dissipate the energy flowing from positive because some of that energy was lost. Then, could you explain the circuit and whether flow is perpetual or lost at the end (wherever that is) and if it isn't perpetual in a loop, why have a resistor past the LED when the LED recieved all the volts and the electrical energy it then outputs back on the cycle is reduced by the resistor. Thanks.
Also, I'm changing my question to "Why does resistor on GND ever work on LED" to "Why have resistor at end of circuit cycle if GND dissipates final energy?".

Hint-Historically it was first thought that electricity travels from positive to negative. Then it was later discovered it actually travels from negative to the postive.

My world is flipped, not the LED. Ok then, what was the deal then with having the resistor attached to the POSITIVE, the 5V, not the GND, in challenge 1?

What do you think the resistor does in your circuit? I dont have your book in the photo by the way

I'm not big on physics or electricity, but if I have a resistor that converts 3V electrical energy to heat, then out of the 5V of current connected and flowing through the resistor, 2V will come out ;D

"Ground" means neither "no voltage" nor "no current".

Then what does it mean?

Ah. Ground it where current comes from. I need to get some sleep. AND so do you @qwerty10 you've been answering my questions all day.

why does resistor work on POSITIVE!? - you lost me there.

Sorry @NickGammon. I didn't mean to. I revised it.

Some images may help, other answers so far are quite good. You need to realise the concept that electrons are flowing in a circuit, with series it doesn't matter which order, so in the following schematic, the first 2 are the same and both work in exactly the same way, the 3rd functions the same but obviously uses 2 resistors instead of 1, It is there to help you understand the concept. The resistance of R3+R4 = 1K so the same amount of current flows through D3 the 3rd LED as D1 and D2.
Do you know Ohms law and about voltage drop ?
Also how to calculate resistance in series and parallel ?
There is some fairly simple maths that shows the 3 different legs are all doing the same thing, however it may over complicate things at this stage if it is above your knowledge as you state you are in middle school.

I'm learning about Ohm's law in the manual and voltage drop from a youtube channel. Don't underestimate the knowledge of an 8th grader! (So you are saying that current flows in a cycle without dissipating?)

I'm not sure what you mean by dissipating. If you flip that diagram upside down you could just as well say that "ground" is at the top. The current will still flow the same way. The word "ground" is really a convenient way of saying "reference point". For example, when you measure the height of kids in the classroom, you would normally measure with reference to the floor. However the floor is not "dissipating" their height.

I need to learn more about circuitry. I'll come back to this after I learn physics on Khan Academy. Brb.

One way to think of this is having marbles fall under gravity through some machines or restrictions. The further they drop, the more work they can do - but they remain intact all the way from top to bottom. The 12V battey here is an escalator lifting marbles back up to be used again.

Roman, As I understand your question you have a resistor, an LED and a switch in "series". It makes no difference in which order these are connected. It may help to think like water flowing through a hose, with a tap being a switch - it can be at either end.
"Current" flows through each in turn. As others have mentioned current conventionally is considered to flow from + to - (even though in most, but not all, cases electrons flow from - to +).
In practical circuits it is usually more convenient to select one configuration over another. An Arduino digital pin can be considered as a switch which is either connected to + or -. You could connect a LED (with a current limiting resistor) to either + or -, either is valid it just changes the logic controlling the switch.

If current flows - to + then why does a resistor on GND make no difference on LED but connected to the 5V, it does? I'm now getting that the GND is some sort of "power supply return"..

@Roman You don't have  "a resistor on GND". An electrical circuit is just that a "circuit". It is a closed loop comprising the Power Supply, LED, resistor and switch. It makes absolutely NO difference in which order these are connected.

To go further with the water analogy as proposed by @Milliways, consider the water system being closed and made of hard pipe (which cannot expand or contract). All of the water (electrical charge) there is, is contained within the closed system. (We'll use a battery instead of a power supply for clarity but it won't make any difference). Think of a simple loop containing a pump & small reservoir (battery), a small turbine or water motor (the LED or most any other electrical load), and a resistor (a constriction somewhere in pipes).
It won't matter where you put the restriction; it will still reduce the flow in the entire loop and therefore, through the turbine, reducing its mechanical output. Even if the restriction is on the return side. Why? Because the same amount of water has to flow past any point in the system, as flows past any other point. If that were not true - the water flowing toward any point != the water flowing away from that point, then there must be either a leak or a water source (loss or gain of water) at that point. Since we believe there is no leak (short circuit to ground) or source of water (battery), then water flowing in must == water flowing out at any point. So wherever you put the restriction (resistor), it limits the flow (current) through the entire loop, and the turbine will do less work.
Update:

If say, 3V are lost/used in the circuit one way, then 2V isn't enough
  to power, right?

The difference in voltage at various points in the circuit is like the change in pressure at various points in the hydraulic loop. Energy (which is neither pressure nor voltage) is transferred by the flow of water or electrons from the pump (battery) to the turbine (LED) and the restriction (resistor). But in a closed system, no water (electrons) is/are lost.

If the current (electricity) then "flows" in a closed system in a loop, what's the point of GND? My dad told me that it makes the energy dissipate.

"Ground" is a bit of a misnomer. Most of the time it is actually "power supply return" and the 0v reference rather than a connection to physical ground.

Thank you @IgnacioVazquez-Abrams.
Of course it's not literally "ground". But if some of the energy on the 5V circuit is lost along the way, then what's the point of a power supply return? If say, 3V are lost/used in the circuit one way, then 2V isn't enough to power, right? I'll come back to this once I get more experience with circuits, schooling system here where I'm at isn't thoughtfully implemented. I first learn electrical engineering in 6th grade, forget everything and then start learning physics in 8th.

All of the energy is lost in the circuit. But the electrons still need to be returned to whence they came.


text:
Is there any way to use a JTAG programmer with the Arduino IDE?
I am doing a lot of work with custom boards I've designed with the ATSAMD21G. I'd like to get away from using USB to program my boards since the USB port takes up space on the PCB and consumes extra pins. Is there any recommended way to configure the Arduino IDE to simply dump out the compiled program into a JLink debugger, much like the Atmel Studio IDE can?

For a one-click upload, you can make a custom hardware definition that calls any executable of your choosing.

The IDE makes a .hex file which you can then program onto your chip with a suitable programmer.

authors: สายัณห์ ผลมาก


text:
Anything wrong with this code?
Sorry for any grammar mistakes. It's my second language.
I had a little test with my Arduino Uno R3 I connected 2 buttons to power , GND using 10k resistors and pins 2 and 4.
I connected piezo to power and ground.
When you pressed a button1 then you should hear 'c' tone,
but when I pressed the second button nothing happend and I don't understand why?
Here is my code below:
const int buttonPin2 = 4;
const int buttonPin1 = 2;
const int piezopin =  6;

int buttonState1 = 0;
int buttonState2 = 0;

void setup() {

  pinMode(piezopin, OUTPUT);
  pinMode(buttonPin2,INPUT);
  pinMode(buttonPin1, INPUT);
}

void loop() {

  buttonState1 = digitalRead(buttonPin1);
  buttonState2 = digitalRead(buttonPin2);

  if (buttonState1 == HIGH) {
    tone(6,261.63,500);

  } else {

  }
  if (buttonState2 == HIGH) {
    tone(6,392.00,500);
  } else {

  }

There is a free schematic tool when posting. Use it please.

You should add a debounce in the code for the buttons. And this is a state change code. You should try going to the Arduino website for an example code as a reference. I'm a bit rusty, but I dont think the if/else statements are right. But this is relatively straight forward basic code, lots of help around the web if you look for it.

What is your wiring? Do you have any pull-down resistors?

I connected piezo to power and ground -- Not to pin 6 and ground...?

Try calling noTone() after the tone is played. This is a kind of "reset" for the pin.
Also, you forgot a } at the end of your code.
If these didn't solve your code, then it most probably is an electric problem.

I know what was my problem. i was thinking my buttons are upright but they are not.my program is working now.thank you for your help.:-)


text:
WiFiESP constantly losing connection
I am working on a traffic light with a ESP8266-01 wifi module on an Arduino.
The wifi card should act as a server and wait for a request to come in at /R (red), /Y (yellow), /G (green) or /O (off) and open the relay for that light.
The Arduino with wifi starts perfectly, and I can switch to a color.. but after a short while it dies and doesn't respond to requests. Sometimes after uploading a few times it seems to get the >>> TIMEOUT >>>, but that usually is resolved by turning of the power to the Arduino for a short while.
The ESP is set to 9600 baud and uses pins 9 and 10. Ping 6, 7 and 8 go to the relay shield for turning off/on the lights.
What is it I am missing here:
#include <SoftwareSerial.h>
#include "WiFiEsp.h"

#define PINGREEN 6
#define PINYELLOW 7
#define PINRED 8

#define OFF HIGH
#define ON LOW

// WIFI Settings
char ssid[] = "somewifi";
char pass[] = "somepass";
int status = WL_IDLE_STATUS;

// Serial settings
SoftwareSerial Serial1(9, 10);

// WiFi settings
byte mac[] = { 0xDE, 0xAD, 0xDA, 0x0D, 0x14, 0xBF }; // WIFI Sheild MAC address
int reqCount = 0;                                    // number of requests received

// NETWORK: Static IP details...
IPAddress ip(10, 0, 0, 223);

WiFiEspServer server(80);

// The state of the trafic light, default state should be off
enum traficLight {
  off,
  green,
  yellow,
  red
};

// The type of data that we want to extract from the page
struct TrafficLightData {
  char red[32];
  char yellow[32];
  char green[32];
};

// Set the default of the trafic light
traficLight currentLight = off;

// use a ring buffer to increase speed and reduce memory allocation
RingBuffer buf(8);

// Change the active light of the trafic light
void changeLightTo(traficLight light, int setDelay = 1000) {
  // Start with turning all lights off
  digitalWrite(PINGREEN, OFF);
  digitalWrite(PINYELLOW, OFF);
  digitalWrite(PINRED, OFF);

  // Check if the new light requested is not off
  if (light != off) {
    int pin;
    switch (light) {
      case green:
        pin = PINGREEN;
        break;
      case yellow:
        pin = PINYELLOW;
        break;
      case red:
        pin = PINRED;
        break;
      default:
        pin = -1;
        break;
    }

    if (pin > 0) {
      digitalWrite(pin, ON);
    }
    currentLight = light;
  } else {
    currentLight = off;
  }

  if (setDelay > 0) {
    delay(setDelay);
  }
}

// Test if all the lights work
void doLightTest() {
  // Turn all lights on for 2 sec
  changeLightTo(off);

  delay(500);

  digitalWrite(PINGREEN, ON);
  digitalWrite(PINYELLOW, ON);
  digitalWrite(PINRED, ON);

  delay(1000);

  changeLightTo(off);
}

void setup() {
  // start the serial library:
  Serial.begin(115200);
  Serial1.begin(9600);

  // Setup pins
  pinMode(PINGREEN, OUTPUT);
  pinMode(PINYELLOW, OUTPUT);
  pinMode(PINRED, OUTPUT);

  // Start with light test
  doLightTest();

  setupWifi();

  // Set the pins
  Serial.println("Settings pins:");
  Serial.print(" - GREEN: ");
  Serial.println(PINGREEN);
  Serial.print(" - YELLOW: ");
  Serial.println(PINYELLOW);
  Serial.print(" - RED: ");
  Serial.println(PINRED);

  delay(1000);

  changeLightTo(off, 0);
}

void setupWifi() {
  Serial.println("Starting wifi...");

  WiFi.init(&Serial1);
  //WiFi.config(ip);

  if (WiFi.status() == WL_NO_SHIELD) {
    changeLightTo(red, 1000);
    Serial.println("Wifi shield not present!");

    // Don't continue
    while (true);
  }

  while (status != WL_CONNECTED) {
    Serial.print("Attemting to connect to SSID: ");
    Serial.println(ssid);

    status = WiFi.begin(ssid, pass);
  }

  Serial.println("You're connected to the network");
  printWifiStatus();

  server.begin();
}

void loop() {
  WiFiEspClient client = server.available();

  if (client) {
    Serial.println("New client");
    buf.init();

    while (client.connected()) {
      char c = client.read();
      Serial.write(c);
      buf.push(c);

      if (buf.endsWith("\r\n\r\n")) {
        sendHttpResponse(client);
        break;
      }

      if (buf.endsWith("GET /R")) {
        Serial.println("LIGHT RED!");
        changeLightTo(red, 0);
      } else if (buf.endsWith("GET /Y")) {
        Serial.println("LIGHT YELLOW!");
        changeLightTo(yellow, 0);
      } else if (buf.endsWith("GET /G")) {
        Serial.println("LIGHT GREEN!");
        changeLightTo(green, 0);
      } else if (buf.endsWith("GET /O")) {
        Serial.println("LIGHT OFF!");
        changeLightTo(off, 0);
      }
    }

    // Give the browser time to recieve the data
    delay(10);

    client.stop();
    Serial.println("Client disconnected");
  }

  /*if (WiFi.status() == WL_DISCONNECTED || WiFi.status() == WL_CONNECT_FAILED) {
    setupWifi();
  }*/
}

void sendHttpResponse(WiFiEspClient client) {
  Serial.println("Sending response");

  client.print(
    "HTTP/1.1 200 OK\r\n"
    "Content-Type: text/html\r\n"
    "Connection: close\r\n"
    "\r\n");
  client.print("<!DOCTYPE HTML>\r\n");
  client.print("\r\n");
  client.print("\r\n");
  client.print("<title>Traffic light</title>\r\n");
  client.print("\r\n");
  client.print("\r\n");
  client.print("
Main page for traffic light!
\r\n");
  client.print("
Select light to use:
\r\n");
  client.print("
 - Red
\r\n");
  client.print("
 - Yellow
\r\n");
  client.print("
 - Green
\r\n");
  client.print("
 - Off
\r\n");
  client.print("\r\n");
  client.print("\r\n");
  client.print("\r\n");
}

void printWifiStatus() {
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // Print the IP Address
  IPAddress ip = WiFi.localIP();
  Serial.print("IP address: ");
  Serial.println(ip);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.print(" dBm (Signal strength is ");
  Serial.print(rssiToText(rssi));
  Serial.println(")");
}

String rssiToText(float rssi) {
  if (rssi > -30) {
    return "Amazing";
  } else if (rssi > -67) {
    return "Very good";
  } else if (rssi > -70) {
    return "Okay";
  } else if (rssi > -80) {
    return "Not good";
  } else if (rssi > -90) {
    return "Unusable";
  }

  return "";
}

The output I get is the following:
Starting wifi...
[WiFiEsp] Initializing ESP module
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] Initilization successful - 1.5.4
Attemting to connect to SSID: somewifi
[WiFiEsp] Connected to somewifi
You're connected to the network
SSID: somewifi
IP address: 10.0.0.145
signal strength (RSSI):-62 dBm (Signal strength is Very good)
[WiFiEsp] Server started on port 80
Settings pins:
 - GREEN: 6
 - YELLOW: 7
 - RED: 8
[WiFiEsp] New client 0
New client
GET / HTTP/1.1
Host: 10.0.0.145
Connection: keep-alive
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding: gzip, deflate, sdch
Accept-Language: sv-SE,sv;q=0.8,en-US;q=0.6,en;q=0.4,nl;q=0.2

Sending response
[WiFiEsp] Disconnecting  0
Client disconnected
[WiFiEsp] New client 0
New client
GET /favicon.ico HTTP/1.1
Host: 10.0.0.145
Connection: keep-alive
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
Accept: image/webp,image/*,*/*;q=0.8
Referer: http://10.0.0.145/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: sv-SE,sv;q=0.8,en-US;q=0.6,en;q=0.4,nl;q=0.2

Sending response
[WiFiEsp] Disconnecting  0
Client disconnected
[WiFiEsp] New client 0
New client
GET /GLIGHT GREEN!
 HTTP/1.1
Host:�[WiFiEsp] TIMEOUT: 416
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] No tag found
Client disconnected

Usually just stopping after a while is a memory leak, but I can' t see anything obvious apart from you circular buffer.  Could it be the web side is writing data into the buffer faster that it can be read.  Try a 1024byte buffer?  If it isn't that could the ESP be faulty in some way, can you swap it for a different one?

Please help us to help you by replacing your code with a minimal, complete, verifiable example .

Except for the debugging Serial.println() I would argue it pretty much is mcve. Maybe its a good idea to read the question, @MarkSmith?

@Matt good idea. I've ran the Arduino with the ESP over night now with the red light turned on and it is still on. The router stil sees the ESP connected with uptime of 17h, but when connecting to the IP I get a time out.

@PaulPeelen I respectfully disagree. Does the problem go away if you remove the LED lighting code?  What about if you only send a dummy HTTP response?

Yes and no, the LED code can impose a memory issue which gets the server to not respond. However, I can't seem to find that. The LED work on their own and the HTTP works a lot longer on its own. I removed the html return body and only return a one line text, which also keeps the module responding for a longer time.


text:
Sending textual and nontextual data simultaneously across a serial port
I am currently using an Arduino Uno and creating an LCD simulator that works by sending LCD data through the hardware UART (serial interface). This LCD data is very short in length; in this case, it's 2 bytes. The LCD simulator has already been made, and it is capable of detecting these LCD packets on the serial port and using them to control the simulated LCD.
However, I don't want to disturb the other traffic passing through the serial port; in this case, it's just text. The problem is that most serial monitors are able to pick up the LCD packets, which aren't supposed to be printed out because they appear as gibberish.
For now, I'm prefixing these short LCD packets with two magic numbers for it to be detectable by the LCD simulator alongside non-LCD traffic, and perhaps removable by a modified serial monitor.
I thought about using ASCII control characters to inform regular terminals that following data must not be printed, but there does not seem to be a specific control character to "hide" text/data; the closest thing there is is the BS character. All other control characters seem to give an inconsistent result among terminals - i.e. ESC doesn't actually hide text with the Windows console host, but it does with mintty.
My goal is to not have to integrate my own serial monitor and force others to use it if there is traffic present that can only be read by the LCD simulator. I want to allow others to use their own terminals and serial monitors to exchange textual data with the Arduino while seamlessly having LCD packets being sent invisibly and "under the hood."
Is this possible? Can I mix different types of data across the same serial port? If not, what are my options, or am I essentially forced to "reinvent the wheel" by making my own protocol that can mix the two types of traffic?

If it's only two bytes, the cost of encoding the data in hex or something like that so it won't seriously distort a serial monitor should not be too great.  But if you want to completely filter it out, yes, you will probably need your own client - theoretically you could follow it with a few backspaces or an ANSI escape sequence having similar effect, and that will work on some terminal emulators or configurations thereof, but it will only make an even bigger mess with other configurations.

The idea that sundry terminal programs can cleanly deal with binary data intended for your LCD simulator doesn't seem realistic.  Instead, look for a method to suppress the binary data when the Arduino isn't talking to an LCD simulator.
For example, during startup the Arduino could send some fixed text and a number to the host, and if the simulator is running, it would reply to the Arduino with some other fixed text and the 9's complement of the number.  If the Arduino doesn't get such a reply within a couple of seconds, it turns off LCD-simulation data transmission.

If I were to do something like this on Linux, I would probably have the
LCD simulator sit between the Arduino and the serial monitor, like this:
                    +---------------------------------------------------+
                    |                    host computer                  |
+-------------+     | +-------------------+         +-----------------+ |
|             |     | |                   |         |                 | |
| Arduino  UART-----tty  LCD simulator    ptmx----pts  Serial monitor | |
|             |     | |                   |         |                 | |
+-------------+     | +-------------------+         +-----------------+ |
                    +---------------------------------------------------+

For this, you have to:

open the serial port connected to the Arduino (“tty” on the figure)
create a pair of pseudo-terminals (ptmx/pts)
open the master side of the pair (ptmx)
ask the user to open the slave side (pts) with his serial monitor
forward all traffic but the LCD control messages between the Arduino
and the pseudo-terminal.

I don't know how this works on MacOS, but since the whole
pseudo-terminal concept is a standard Unix feature, I would expect it to
work in a similar way on MacOS and Linux. But then I have no idea how
hard it would be to port this to Windows.

From README.md at github ... LCDViewer, the Arduino links a LiquidCrystal library that substitutes for the usual LiquidCrystal library.  That library sends 4 bytes per LCD op, which a python program on host uses to control an on-screen simulated display.  Ie, there isn't a separate 'LCD simulator' piece of hardware.

@jwpat7: I know. I did read that README before answering. The LCD simulator is not a piece of hardware, it's a piece of software.

Ok - so in your diagram, the left box is Arduino hardware, and the other two boxes are host processes that communicate via pseudo-terminal or pipe?  Probably an elegant solution.

@jwpat7: Yes, via a pseudo-terminal rather than a pipe: a pseudo-terminal is essentially a virtual serial port, so it should play well with a serial monitor.

I would simply send the data as ASCII, in the form of hex bytes. It wil make your two bytes become four, plus the two "leader" characters to uniquely identify them becomes six. This minor overhead can probably be absorbed.
If you have much more binary (non-ASCII) data, you could look at using a different encoding format such as Base64. This only has a 2 character overhead for every 6 bytes of binary data.
You don't mention what data rate you use, either in baud rate or "packets per second", but if you're reading it on a serial monitor it can't be very much.


text:
Multi Agent Systems
In my project work, I have 3 robots with their own Arduino boards. Each robot has Infra Red Sensors, whose values I can read using its corresponding Arduino. The main thing however is that each robot must have every other Robots' values. Can anyone suggest me a suitable strategy? I tried using the Processing Software, using which I am able to read all the values from all the robots but sending them back to the robots is turning out to be a problem! It says ports are busy!
Any help would be great!

What do you mean when you say "Processing Software"?  What are you using to read the values from the robots?  Are you using more equipment then the 3 robots you described in your question?

This is just a guess, but I suspect you are using the robots to look for a single IR source.  And that you have not yet considered the need to locate the robots in space disseminate that information among all the robots.

Are you looking for a way for each robot to communicate parameters to its partners? (That sounds like things that are available on several commercially available swarm robots, using IR or optical LEDs and receivers on each robot.)

For example see this robot (Thymio) under "Local Communication". That's an open source robot so you might be able to get a look at the firmware for ideas.


text:
Creating linear motion using motor
I am trying to make a smart lock for bicycles. This lock can be controlled with the help of smartphones. For the purpose, I am using an Arduino interfaced with HC-05 Bluetooth Module which receive commands from an Android smartphone.
The overall project is almost over, except the actual lock. I want to create a lock with a pin which can be slide between the spokes of the wheel to cease the motion of the wheels. I can't find any product in the Indian market. Can you please suggest any product available or how to make one myself?

I've seen the solenoid locks but their stroke is too small to make a meaningful lock out of it.

Your help will be well appreciated.

Is it a proof of concept, or does the lock really have to be solid and temper proof?

You may find Robotics Stackexchange useful for questions like this.

I just have to show it as my college project @Paul

As a demonstration, you could show an servo that rotates and pushes a pin between the wheels. Or modify a regular lock in a way that you can drive it with a motor.

The pin that slides between the spokes should be just a metal bar that accepts your "small" pins in the ends to hold it in place.  Try looking at it from a different perspective and I think you will find a lot more suitable products.
You could use a worm gear, but this would be susceptible to bruit force attacks (literally) and would be easier to break.
Have you considered what happens when the power fails?  Does the lock lock or unlock?  If it unlocks on a power fail then it will be quite easy to open.  If it remains locked on a power fail then its not very user friendly, you would have to carry spare batteries and changing tools with you.
Sorry, but it is easy to poke holes in other peoples designs.

I like your suggestions @Matt, but it won't be a end product. I just have to show a working model for my college project.


text:
Using SIMCOM SIM800 as a Bluetooth SPP Client
I just bought a SIM800 module for my Arduino project and I found that I supports Bluetooth too. I have already worked with HC-05 and my Android phone.
I tried to play with this module and able to connect it successfully with my Android mobile. I am able to make a call using it, accept a call, etc. But when I tried to send text data using it (in SPP mode), I ran into problem.
I have an app called Bluetooth Terminal in my mobile with which I use to communicate with my HC-05. But with SIM800, I can't connect.
I have read all the AT commands which are used to make a SPP connection. Here's a screenshot of the PuTTy terminal where I tried to make the connection:

As you can see in the image, whenever I try to call

AT+BTGETPROF=1

It never returns to me. I also tried the command with my Bluetooth visible in the mobile, but still no result.
Whenever I try to run the command or

AT+BTCONNECT=1,4

My SIM800 goes into state 2 and I have to manually reset it.
Can someone please help me with this problem? I just want to use my SIM800 as a SPP client/server so that I can exchange text data with my Android APP.
Thanks in advance.

I tried to make my SIM800 as server by making the request from the mobile, but now I can't send data from SIM800 and the data send by mobile is echoed back.

AT+BTGETPROF failed, so no sense making AT+BTCONNECT=1, (where n should be SPP profile index on the list returned by AT+BTGETPROF). Make sure that SPP is listed first. Also did you get +BTPAIRING: message? If so answer with AT+BTPAIR=1,1

Yes I know that there is no sense making AT+BTCONNECT. Yes I got the +BTPAIRING: message when I make the request from my mobile, but then my SIM800 enters into Server mode because of which I can't use AT+BTSPPGET and AT+BTSPPSEND

In server mode, module shall received +BTCONNECTING: "...","SPP" message - reply with AT+BTACPT=1 (shall return OK) and  AT+BTSPPGET=0 (auto mode). Then you can do AT+BTSPPSEND. For client mode, isn't you module shall start the initiation?

For being in client mode, yes I should initiate, but the same problem occurs with me which I have posted in the image @Flanker. The server mode works well but whatever I send to SIM800, it is echoed back and I receive nothing at my terminal.

By default i see that the Android handset i used did not have SPP profile enabled. You need to open a App which enables the SPP profile to be advertised. Then after that you can get that in AT+BTGETPROF list. I made a tutorial for this, Have a look here,
https://youtu.be/zdQb8r2xRK8
and
http://www.raviyp.com/embedded/215-sim800-series-bluetooth-at-commands


text:
Multiple MuxShield 2's connected to a single Arduino Mega
I am working on a project and need alot of toggle buttons to control various things around the house. I connected 5 MuxShield 2's to my Arduino Mega. The first two will serve as inputs and the last two will serve as outputs.
The problem is when I try to loop over all the outputs (connected to LED's for now) to turn them on/off, only the first 3 rows work as expected. The LED's turn on one by one, but when the loop reaches a row number which it has already looped over on another multiplexer the LED's turn on all at once.
I think it has something to do with the arrays in the MuxShield library being shared across all multiplexers and therefor breaking all signals the second time it gets used but I'm not sure.
It's not that much code but, too much to post here so I uploaded it to GitHub.
If someone could please look over it and point me in the right direction, I'd greatly appreciate it. Thanks.