text:
Wakeup Pin ESP8266
Is there a way to put an ESP8266 into a sort of "sleep" mode where it draws less power than usual, and then wakes up on a pin going high? I've tried doing this with delay, which still draws 20 mA, and with the deepsleep function that comes with the esp library, which can't sleep for short periods of time to watch for the pin going high. I'm building a watch, and power draw is of great concern to me. Is there possibly a way I could build or code this differently to make it more power efficient?
Basically it works like this, but the full code (at it's current state) can be found here.
void loop() {
    delay(1);
    // check for power signal stuff
    if(digitalRead(0)) {
        // execute data fetching 'n stuff
    }
}

With this many code level attempts you have, it would be nice to see, what is your current efforts on code sample level. In short: show yer codez.

Just connect the RST pin to the button, to "wake" up the ESP8266. You need to connect the other side of the button to Vcc.

In that case @Gerben how much power does it take to call WiFi.begin('stuff')

Added a link to a gist @mico

@CarrotM that's totally unrelated to your question. Create a new question for it, or better, try it out yourself and measure it.

GPIO16 is the only hardware interrupt pin available in deep sleep, and your MCU will reboot when it's triggered.

Without seeing the code and optimizing it I can tell you the following:
ESP8266 has three ways to save power:

Modem sleep - only wlan modem shutdown, connection kept open
Light sleep - less cpu usage, fast recovery
Deep sleep - suspend all, close wifi too, slow recovery

http://bbs.espressif.com/viewtopic.php?t=133

ESP8266 does have deep sleep mode. The link to http://bbs.espressif.com/viewtopic.php?t=133 posted earlier sums it up pretty well, despite being old.
However, a few things that are different from Arduino or should be considered if you're building a battery-operated device:

when the MCU wakes up from deep sleep, the entire application is restarted. Yes, beginning from the setup() function - just as if it was reset. You cannot put it to the deep sleep and then resume from the same place keeping all variables etc. You can only detect that the device was woken up from the sleep by reading a flag in the setup() function.
check your board. If you're not using bare ESP8266, but some development board such as NodeMCU or WittyCloud, it usually has number of other circuits powered on even when the MCU is sleeping. Particularly, USB-UART bridge and maybe power LED.
check your power source. Again, if you're using a development board, very likely it has an inefficient LDO voltage regulator. Even when MCU is powered down, the LDO can still use a few mA just to power itself (quiescent current). There are special low quiescent current regulators exist, very useful for battery-operated application.
finally, I see your code refers some OLED display. Just to be sure - is it powered down or excluded from the measurement? OLED doesn't need a lot of energy, but will drain a battery in a few days.

Personally, I do have experience creating a battery-operated device on ESP8266, which wakes up every few minutes, connects to wifi and sends some data. An old 700mAh Lithium battery is enough to run it for approximately a month. And I managed to get the sleep power to about 40 microAmps. Still a few times more than the chip itself needs, but good enough for me.

Only a month? I roughly estimate for your case 250 mAs per wake-up, plus the 40 uA standby. To use 250 mAs per wake-up I guess you are using DHCP? static IP reduce the connection time to about 250 ms (multiplied by 200 mA is 50 mAs) and should extend the battery a lot (or... your battery is way lower than 600 mA I assumed).

I use static IP, so it's not a problem. But there is also a sensor that needs to be initialized and used. Also establishing the network connecting and sending data takes some time. So the awake time for each wake up is 2-3 seconds (every 5 minutes). It probably doesn't use full 250mA all that time, but twice less on average, which, over 5 minutes, gives average consumption of 0.9mA. Or 650mAh in 30 days. Seems pretty accurate.


text:
Unable to receive SMS on Android
I have a GSM/GPRS shield for Arduino. It uses a SIM800 from SIMCOM. I've done several projects using it. Previously I used to send SMS from the same module. which were delivered appropriately. Since yesterday, whenever I am sending an SMS to my Android mobile, all what I receive is:
<<Content not supported>>

I also tried sending it to a basic mobile. It displayed:
Content can't be displayed

I tried changing the encoding using the AT command.
AT+CSCS="UCS2"
AT+CSCS="GSM"

It didn't work for any encoding.
The command I use to send SMS is:
---> AT+CMGF=1
<--- OK
---> AT+CMGS="10 digit number"
<--- >
> Hello!
^Z

Can someone please tell me what is going wrong? Thank you in advance!

In the SIM900 is an AT command that let you do a factory reset, your module will restart to the default values. It must be an AT command very similar to the SIM800.
The AT commando that (perhaps) will work for you is the ATZ, in the SIM900 works for me.
You can look over here to see what command is. Look over page 33. And be carefull, the link that I send to you is the AT command list for the SIM900, not the SIM800.
Hope you can find an answer.

source: Stack Exchange

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

sort: votes


text:
SSD1306 OLED LCD Library Errors
Recently i bought an "Serial 128X64 OLED LCD Display SSD1306".
I searched for available libraries and tried to find the best one to use before actually experimenting with this device.
I came across a hackaday article mentioning a "HIGH SPEED SSD1306 LIBRARY"
So that drew my attention and got on with it. This is the link to the afforementioned library for the Arduino DUE.
DayOLED_SSD1306
Right from the beginning i had some trouble with the wiring.
I wired 3.3 volts to input, GND, RES, DC, CS pins are wired according to the library example..
But the library contains no info on how to wire D0 and D1 pins. Since this OLED works both I2C and SPI, i thought maybe these two pins are ommited.
So i hooked it up, load up the example code and got compilation errors.
Here are the errors:
C:\Users\User1\Documents\Arduino\libraries\DayOLED_SSD1306-master\DayOLED_SSD1306.cpp: In member function 'virtual void DayOLED_SSD1306::drawPixel(int16_t, int16_t, uint16_t)':

C:\Users\User1\Documents\Arduino\libraries\DayOLED_SSD1306-master\DayOLED_SSD1306.cpp:114:14: error: 'swap' was not declared in this scope

     swap(x, y);

              ^

C:\Users\User1\Documents\Arduino\libraries\DayOLED_SSD1306-master\DayOLED_SSD1306.cpp: In member function 'virtual void DayOLED_SSD1306::drawFastHLine(int16_t, int16_t, int16_t, uint16_t)':

C:\Users\User1\Documents\Arduino\libraries\DayOLED_SSD1306-master\DayOLED_SSD1306.cpp:598:16: error: 'swap' was not declared in this scope

       swap(x, y);

                ^

C:\Users\User1\Documents\Arduino\libraries\DayOLED_SSD1306-master\DayOLED_SSD1306.cpp: In member function 'virtual void DayOLED_SSD1306::drawFastVLine(int16_t, int16_t, int16_t, uint16_t)':

C:\Users\User1\Documents\Arduino\libraries\DayOLED_SSD1306-master\DayOLED_SSD1306.cpp:666:16: error: 'swap' was not declared in this scope

       swap(x, y);

Anybody got a clue what is going on with the swap() function?
Maybe it's deprecated?
Anyone has managed to get this library working?
Or maybe has managed to get this Display working even with another library?

I've had good success with the u8g2 library for the small I2C OLEDs.
u8g2 on GitHub

I have managed to get this somewhat working with these 4 libraries:
#include <SPI.h>,
#include <Wire.h>,
#include <Adafruit_GFX.h>,
#include <Adafruit_SSD1306.h>.
These should all be in the include library in the ide.
Hope this helps!

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

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


text:
toInt error when converting character of string to interger
with the following code:
int foo = bar[1].toInt;

or
int foo = bar[1].toInt();

I get this error
request for member 'toInt' in '*(bar + 1u)', which is of non-class type 'uint8_t {aka unsigned char}'

the context for this is bar is the response from a HTTP client over web sockets

Why are you trying to call a method on something that isn't an object?

I am trying to convert a character of a string to an integer https://www.arduino.cc/en/Tutorial/StringToIntExample

Then what is bar? It must be an array of String objects then, otherwise this doesn't work. The error clearly shows that you have something like uint8_t* bar;. Are you trying to convert a single character to a int, i.e. something in the range of '0' to '9'?

'bar' is the web sockets response (payload). this is generated by the arduino web sockets library https://github.com/Links2004/arduinoWebSockets (i am basing most of my code on this example https://github.com/Links2004/arduinoWebSockets/blob/master/examples/WebSocketServer_LEDcontrol/WebSocketServer_LEDcontrol.ino)

Can you use atoi() ?

using this code int foo=atoi(payload[1]); i get this error invalid conversion from 'uint8_t {aka unsigned char}' to 'const char*' [-fpermissive] using this code     int bar=payload[1].atoi; i get this error request for member 'atoi' in '*(payload + 1u)', which is of non-class type 'uint8_t {aka unsigned char}'

It has to be int foo=atoi((char*)payload[1]);. And are you sure about the index 1, meaning the second character of the payload?

The question is meaningless without knowing what datatype bar is.

The Arduino function toInt requires a String object.
You're passing it a single character, not a String.
int foo = String(bar[1]).toInt();

I'm not quite clean on what you are trying to do.  So lets assume the String has "abc123" in and you want the numeric part.
const String input = "abc123";
const int foo = input.toInt();  // This will not work!

const String input = "abc123";
const String tmp = input.substring(3); // Take the end of the string
const int foo = input.toInt();  // foo == 123

const String input = "abc123";
const String tmp = input.substring(3,4); // Take the end of the string
const int foo = input.toInt();  // foo == 1 or 12 (can't quite tell from the docs)

Is one of those what you want to do?
You can't take a character and then apply a function from the string class to it without making it a String first.
int foo = String(bar[1]).toInt();  // This should work

You mean .toInt()?

I thought I did then I read the original question again.  I don't know about these new fangled String classes.  If its not a uchar I don't use it :)  Corrected post.


text:
Connect Two Arduino Uno's
Essentially I am looking to build a remote controlled car using dc motors and one arduino uno to be on the car to supply the power logic and i wanted to use another arduino to be the remote. I was curious what the most effective method would be as to pairing these two devices in a way that it would provide the maximum range possible while still maintaining a decently high bandwidth limit. The reason for this is hopefully i can have the arduino mounted to the car connected to a camera where the camera would send a video feed over to the remote control. I was thinking about using a bluetooth module between the two such as a HM-10 but i wouldn't be able to send a video feed this way because bluetooth cannot transmit that much data at once. However if that is the most practical option i can get over the fact of not having a live video feed and send an image ever 5 seconds or so instead of live. Appreciate any insight on what the most effective method would be in terms of efficiency between range and data stream bandwidth.

i would stick with analog video broadcasting for now, and keep an eye out for faster wifi modules

You wouldn't be able process (acquire, store, resize, output) any sensible video signal with the Uno (or any other Atmega-based board). The amount of memory and clock speed is way too low. Peripherals and instruction set are also lacking - no DMA, FPU, DSP instructions. Arduinos barely cope with audio - any kind of video is out of question, except if you want something like a 5fps 32x32 raw feed. Uncompressed, of course.
If you want another hobby-friendly open source solution, I'd look at something with at least an ARM M4 core, with DMA of course. For communication, regular IEEE 802.11 Wifi is your best bet (high throughput) - those 433Mhz RF modules only transmit 4800bps or so.
There may be better solutions, but I've only used stm32f429 for video: they have DMA(2D), display interface (RGB, 8080 memory interface, ...), DCMI (digital camera interface). Wifi could be handled by something like WifiMCU.
You could use the STM32F429DISCOVERY board with LCD for you remote controller, another STM32F4 board with a camera (ex http://hackaday.com/2014/12/04/serial-camera-courtesy-of-the-stm32f4/) and pair them with two WifiMCUs, if You want to do it with off-the-shelf boards.

You can use raspberry pi and computer to send commands and receive video feed

i was looking to utilize just Arduinos as I'm looking to get more familiar with the architecture

@A.Epstein - you might be hoping to, but that will not work.  This answer is so far the only remotely sensible one that has been posted.  Digital video really requires substantial memory buffers to do right, and no MCU, Arduino or otherwise, has those - the only cost effective solutions going to be those that use a variation of DRAM technology, which isn't something that ends up on the same die as a processor, hence either a stacked assembly like a pi or an S/DD/RAM next to an SoC or special function type CPU..


text:
Arduino + DS18B20 array
I want to connect 24 DS18B20 sensors to arduino by onewire library in the same digital pin .
Can anyone post an example code ?
Thanks

Use the OneWire and the DallasTemperature libraries. They are both in the Arduino IDE in the Library Manager.
The DallasTemperature library has the example "Multiple". You need to make an array of DeviceAddress.
To tell them apart, you have to label each temperature sensor with its device address (a unique identifier inside each DS18B20). Therefor you have to connect them one-by-one and write down the device address.
Start with one sensor, and if that works, try to make arrays.
For 24 temperature sensors, you need a lot of wires. That could make it less reliable. You can use two or three or more pins as well. Then you have to create more than one "OneWire" bus in the sketch.
There are many examples for multiple DS18B20 sensors. For example this one is with an array: Arduino forum: "multiple temp sensors ds18b20".


text:
Can I drive an LM334(Z) from an Arduino with AnalogWrite()?
I need programmable current control, fading from zero to 2 milliAmps.  I was hoping to use Arduino's AnalogWrite(), which uses Phase Width Modulation (PWM) to simulate analog output with a sawtooth wave on a duty-cycle; to control an LM334Z to deliver a slowly ramped low current delivery.
[The application is a TransCranial Direct Current Stimulation (TDCS) micro-current delivery to the human scalp. Jumping straight to 2 milliAmps is uncomfortable].
Will PWM work? Or, do I need some sort of smoothing circuitry to soften the PMW before it is applied to the LM334Z's Rset pin to accomplish the above?

an LED glued to the face of an LDR converts voltage to resistance, but a digital pot would be simpler to calibrate. I'm using a MCP41010 with the 334, which works very well and cost me ~$1us

an LM317 can provide 0-2ma CC with common 1/4watt resistors, look at the datasheet.

On Arduino, PWM stands for Pulse Width Modulation, not  “Phase Width Modulation”

If you don't need super high accuracy, using a MOSFET's ohmic region, plus a smoothing filter on the output of your PWM (analog out), could be a solution.

You control the LM334 with a resistance, not a voltage. The current is set by multiplying the current through the resistor.
Maybe you can do what you want by replacing the Rset with a digital potentiometer?

LM334Z's Rset pin to accomplish the above?

Most of that type of circuit has its operations be determined by the current In or out of that pin. So a voltage signal may not work - you will need to experiment. I have had some success with analogs dds chips and linear programmable osscillators.
So try it on your chip. Nothin to lose.

since it's output current is independent of any voltage, that will not work, it needs a resistor.


text:
Atmega32 push button library problem
I have two files, the first file is a library that I use to handle push buttons and initialize it and the second is where I handle my code and change LED state when push button is pressed, but my code doesn't work, I'm using Atmega32A micro-controller.
my library code:
#ifndef ButtonLibrary
#define ButtonLibrary

#ifndef numberOfButtons
#define numberOfButtons 2
#endif

#ifndef bit_is_clear
#define bit_is_clear(sfr, bit)   (!(_SFR_BYTE(sfr) & _BV(bit)))
#endif

#include <avr/io.h>

char ButtonPressed(int buttonnumber, unsigned char pinofbutton, unsigned char portbit, int confidencelevel);
void initialize_button(int pinofbutton, unsigned char port, unsigned char datadirection);
void initialize_led(int pinofled, unsigned char port, unsigned char datadirection);
void change_led_state(int pinofled, unsigned char port);

char pressed[numberOfButtons];
int pressed_confidence_level[numberOfButtons];
int released_confidence_level[numberOfButtons];

void initialize_button(int pinofbutton, unsigned char port, unsigned char datadirection)
{
    datadirection &= ~(1 << pinofbutton);
    port |= 1 << pinofbutton;
}

void initialize_led(int pinofled, unsigned char port, unsigned char datadirection)
{
    datadirection |= 1 << pinofled;
    port &= ~(1 << pinofled);
}

void change_led_state(int pinofled, unsigned char port)
{
    port ^= (1 << pinofled);
}

char ButtonPressed(int buttonnumber, unsigned char pinofbutton, unsigned char portbit, int confidencelevel)
{
    if(bit_is_clear(pinofbutton, portbit))
    {
        pressed_confidence_level[buttonnumber] ++;
        released_confidence_level[buttonnumber] = 0;
        if(pressed_confidence_level[buttonnumber] > confidencelevel)
        {
            if(pressed[buttonnumber] ==0)
            {
                pressed[buttonnumber] = 1;
                return 1;
            }
            pressed_confidence_level[buttonnumber] = 0;
        }
    }
    //button isn't pressed
    else
    {
        released_confidence_level[buttonnumber] ++;
        pressed_confidence_level[buttonnumber] = 0;

        if(released_confidence_level[buttonnumber] > confidencelevel)
        {
            pressed[buttonnumber] = 0;
            released_confidence_level[buttonnumber] = 0;
        }
    }
    return 0;
}
#endif

my main code:
#define F_CPU 1000000UL

#include <stdio.h>
#include <stdlib.h>
#include <avr/io.h>
#include <util/delay.h>
#include "ButtonLibrary.h"

int main(void)
{
    initialize_button(PIND4, PORTD, DDRD);
    initialize_button(PIND3, PORTD, DDRD);
    initialize_led(PINC7, PORTC, DDRC);
    initialize_led(PINC6, PORTC, DDRC);

    while(1)
    {
        if(ButtonPressed(0, PIND, 3, 500) == 1)
        {
            change_led_state(PINC6, PORTC);
        }
        if(ButtonPressed(1, PIND, 4, 500) == 1)
        {
            change_led_state(PINC7, PORTC);
        }
    }
}

when I press the push button nothing happens, I think there is something wrong in my initialize functions or change_led_state function but I don't know it.

Have you tried adding trace (serial prints for example) to see where it is going wrong?

I'm not using serial in my project, I'm sort of still learning.

Try adding some sort of trace - anything which lets you know what's going on. It could be serial prints, or lighting an LED, or anything which is convenient. You will hit a problem sooner or later which you can't solve by looking at the code.


text:
Arduino randomly does incorrect addition
I've been trying to make an accelerometer calibration tool for my Arduino Nano and MPU6050, but the arduino seems to randomly do incorrect addition. If you look at the output of the console, it works fine for the first 4 iterations, then on the fifth, decides that -31904+-7964 is equal to 25668. It is supposed to be -39868. It does this every time I run it, usually between the 3rd to 6th iteration, but with different numbers.
bool calix = true; //X calibrated or not
      while(calix)
      {
        accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
        Serial.print("PrevAvgX: "); Serial.println(axo/i);
        Serial.print("Axo: "); Serial.println(axo);
        Serial.print("RawX: "); Serial.println(ax);
        axo = (float)ax + (float)axo;
        i += 1;
        Serial.print("Axo2: "); Serial.println(axo);
        Serial.print("RawX: "); Serial.println(ax);
        float cax = axo/i; //Current Average (x)
        Serial.print("AverageX: "); Serial.println(cax);
        delay(100);
        accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
        Serial.print("NewX: "); Serial.println(ax);
        float offsettocurrent = ax-(axo/i);
        Serial.print("AverageX-RawX: "); Serial.println(offsettocurrent);
        if(offsettocurrent>5 or offsettocurrent<-5)
        {
          Serial.println("Offset not accurate enough. Continuing.");
        }
        else
        {
          Serial.println("Offset accurate enough. Finishing calibration");
          break;
        }
        delay(100);
      }

Serial console output:
Initializing I2C devices...
Testing device connections...
Connected to MPU6050
Attempting full calibration
PrevAvgX: -1
Axo: 0
RawX: -8048
Axo2: -8048
RawX: -8048
AverageX: -8048.00
NewX: -8028
AverageX-RawX: 20.00
Offset not accurate enough. Continuing.
PrevAvgX: -8048
Axo: -8048
RawX: -7940
Axo2: -15988
RawX: -7940
AverageX: -7994.00
NewX: -7964
AverageX-RawX: 30.00
Offset not accurate enough. Continuing.
PrevAvgX: -7994
Axo: -15988
RawX: -7972
Axo2: -23960
RawX: -7972
AverageX: -7986.00
NewX: -8016
AverageX-RawX: -30.00
Offset not accurate enough. Continuing.
PrevAvgX: -7986
Axo: -23960
RawX: -7944
Axo2: -31904
RawX: -7944
AverageX: -7976.00
NewX: -8016
AverageX-RawX: -40.00
Offset not accurate enough. Continuing.
PrevAvgX: -7976
Axo: -31904
RawX: -7964
Axo2: 25668
RawX: -7964
AverageX: 5133.00
NewX: -7944
AverageX-RawX: -13077.00
Offset not accurate enough. Continuing.

What do you want to calibrate ? Do you use the sensor for fast 3D motion with accelerometer/gyro fusion or as a spirit level ? For a spirit level you only need the accelerometer. For 3D motion there is an alternative using the AHRS calculations. This code has also a selftest and calibration: https://github.com/kriswiner/MPU-6050/blob/master/MPU6050IMU.ino

I'm going to use the MPU6050 for a quadcopter, so gyro and accel. I'll check out that link, thanks.

int only goes from -32768 to 32768, and rolls-over, as you've seen.
Use a long data type instead and you can go MUCH further from zero. Use double instead of float likewise, when you need more room. Be aware however that larger types use more RAM, and in the case of double, execute a bit slower as well.

Double doesn't give more room - it gives more precision. Also, on Arduino, double and float are exactly the same thing.

Changing all the variables to doubles and longs fixed it. Thanks!

Although an overflowed int usually rolls overs this way, you cannot even count on that, as in C and C++ it's undefined behavior. Use unsigned integer types if you want predictable roll-over.


text:
Two function Reset button - long/short press
I am trying to make a circuit using an ATmega328, that has a reset button that behaves like many consumer devices:

A short press just restarts the micro-controller
A long press (5 seconds?) causes the settings to be restored to default

What is the best way to achieve this behaviour? I imagine it is going to require two pins? Can it be done just using passive components?
Thanks!

I wouldn't use the reset pin but a regular pin. Time how long button is pressed. Then, when released optionally restore the settings and reset the board using software. That way you don't have to experiment with different resistor and capacitor values, and don't have to work around bootloader delays.

I am personally more inclined to use the reset pin because it re-initialises the hardware. It should also always succeed - there is always a risk of a bug in software and not resetting correctly.

Using the Watchdog to reset the device is pretty reliable.

It can be done with one button, one resistor, one capacitor and one GPIO pin (in addition to the RESET pin):

simulate this circuit – Schematic created using CircuitLab
Pressing the button causes a LOW pulse on the RESET pin (in the exact same way as the USB interface does).
During your startup procedure you read the GPIO pin you have chosen. If it's LOW the button is still being pressed in. If it's HIGH it has been released.
If you are using an Arduino with the normal bootloader the bootloader itself imposes a 2 second delay (which may be enough for you). Alternatively you will need to have your own delay in your program before reading the button to ensure that you have plenty of time to release the button so you don't accidentally reset your settings.

Thank you for the very complete answer. Exactly what I was hoping for!

You can set the RSTDISBL (bit 7 on the HIGH fuse) to disable the external reset and use the reset pin as PC6 to manage the reset behavior from your program.

The second part is to capture when reset button is pressed: put some code in the ISR for PCINT1 handler when the pin changes (PCINT14 pin function). If you are programming an Arduino board, the reset button is pulled up (press becomes LOW and release becomes HIGH).
Detecting long press or short press is a timer affair. According to your requirements, you will restore some EEPROM values or external state to factory defaults before the microcontroller resets with a long press.
This C snippet will reset the microcontroller after the short or long press (watchdog timer feature):
#include <avr/wdt.h>

    // ...
    wdt_enable(WDTO_15MS);
    for (;;) {}

Use a state machine to detect thee king presses. Once done, you can either trigger a hardware or a software reset, or to simulate one by jumping to the reset vector - you will need to write the code to support that, like an explicit initialization of variables, etc.

Notice that jumping to the reset vector does not initialize the hardware to its normal power-on state. It does however initialize the memory (data and bss sections), as this is performed by the C runtime before it calls main(). A hardware reset can be triggered by configuring the watchdog with a very small timeout.


text:
In line following robot do this code work perfectly as iam unclear about the right and left moving programing lines
    #define LS 2      // left sensor
#define RS 3      // right sensor

/*-------definning Outputs------*/
#define LM1 4       // left motor
#define LM2 5       // left motor
#define RM1 6       // right motor
#define RM2 7       // right motor

void setup()
{
  pinMode(LS, INPUT);
  pinMode(RS, INPUT);
  pinMode(LM1, OUTPUT);
  pinMode(LM2, OUTPUT);
  pinMode(RM1, OUTPUT);
  pinMode(RM2, OUTPUT);
}

void loop()
{
  if(digitalRead(LS) && digitalRead(RS))     // Move Forward
  {
    digitalWrite(LM1, HIGH);
    digitalWrite(LM2, LOW);
    digitalWrite(RM1, HIGH);
    digitalWrite(RM2, LOW);
  }

  if(!(digitalRead(LS)) && digitalRead(RS))     // Turn right
  {
    digitalWrite(LM1, LOW);
    digitalWrite(LM2, LOW);
    digitalWrite(RM1, HIGH);
    digitalWrite(RM2, LOW);
  }

  if(digitalRead(LS) && !(digitalRead(RS)))     // turn left
  {
    digitalWrite(LM1, HIGH);
    digitalWrite(LM2, LOW);
    digitalWrite(RM1, LOW);
    digitalWrite(RM2, LOW);
  }

  if(!(digitalRead(LS)) && !(digitalRead(RS)))     // stop
  {
    digitalWrite(LM1, LOW);
    digitalWrite(LM2, LOW);
    digitalWrite(RM1, LOW);
    digitalWrite(RM2, LOW);
  }
}

i got this code from a site.My doubt is if the left sensor is not reading means it has value of zero hence it is on black line and the right sensor is on white line.Then it should move to left side itself.BUt the program says it should moves to right.Iam a beginner.Please help me to clear my doubt

This depends on how the sensors are arranged. However, assuming they are setup like eyes on our heads, then the code would be correct.
If the left sensor does not see the line, but the right sensor does, then that means the line is on the right side of the robot, and thus turning to the right would bring the line back into view of the left sensor.


text:
How do I free up space on arduino Yun shield?
I recently bought arduino Yun shield, and I didnt had any external USB storage connected, I downloaded get-pip.py on Yun using wget and ran python get-pip.py which resulted in 5mb storage on yun now full and even pip is not installed.
how do I free up space or reset yun shield to original , and use USB storage as default location for storing all opkg and python onto USB storage drive ?


text:
attachInterrupt HIGH
I'm trying to understand the implementation of attachInterrupt. For LOW, CHANGE, RISING and FALLING it seems simple enough; it sets some chip-specific registers and stores the given callback in intFunc, then invokes the callback from inside its own thin wrapper callback.
But the documentation says that on the Arduino Due, Zero and MKR1000, it can also accept HIGH. I can't find any reference to this in the code, and I can see that HIGH (= 0x01) and CHANGE (= 1) would be indistinguishable after preprocessing, so I can only assume a macro is involved somewhere, but I can't see one in the source.
How does the library implement this? Where is the code?

CHANGE is defined as 2 in the SAM core.

@EdgarBonet ah, thank you. That explains it. And I see that the SAM version also checks which value is given inside attachInterrupt, unlike the AVR version which just passes it though. I'd got stuck on the AVR version since github's search seems incapable of seeing the SAM core.

For a reason I don't know, they recently moved that core to a different repository.


text:
Arduino Nano memory issue. SD card and LCD screen together
When i am uploading my code to arduino nano, i am getting message about high dynamic memory usage (87%):
Sketch uses 17,628 bytes (57%) of program storage space. Maximum is 30,720 bytes.
Global variables use 1,751 bytes (85%) of dynamic memory, leaving 297 bytes for local variables. Maximum is 2,048 bytes.
Low memory available, stability problems may occur.

But despite this, its uploading to my arduino nano and everything works fine without action method's code. How to use code (code to work with LCD) wich is located in action() method. If i use hidden code, im getting message error opening test.txt (not enough memory). But if code which is controls LCD screen is annotated then SD card works fine.
If i use this code, i'm getting problem with SD card. But i can still use LCD and SD on same arduino board separately without any problems, but if i try to combine it, im getting some problems with SD card reading.
void action() {
//  display.display();
//  display.clearDisplay();
//  display.setCursor(0, 0);
//  display.setTextSize(2);
//  display.setTextColor(WHITE);
//  display.println(sensorValue);
// if uncomment this code, i am getting error with sd card reading (possible memory issue)
}

All code:
#include <Wire.h>
#include <Adafruit_SSD1306.h>

#include <SPI.h>
#include <SD.h>

#define OLED_RESET 4
Adafruit_SSD1306 display(OLED_RESET);

const int analogInPin = A0;  // Analog input pin that the potentiometer is attached to
const int analogOutPin = 9; // Analog output pin that the LED is attached to

int sensorValue = 0;        // value read from the pot
int outputValue = 0;        // value output to the PWM (analog out)

int count_iterations = 0;

#if (SSD1306_LCDHEIGHT != 32)
#error("Height incorrect, please fix Adafruit_SSD1306.h!");
#endif

File myFile;

void setup() {

  /// SD START
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.print("Initializing SD card...");

  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");
  myFile = SD.open("test.txt", FILE_WRITE);

  // if the file opened okay, write to it:
  if (myFile) {
    Serial.print("Writing to test.txt...");
    myFile.println("testing 1, 2, 3.");
    // close the file:
    myFile.close();
    Serial.println("done.");
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }
  myFile = SD.open("test.txt");
  if (myFile) {
    Serial.println("test.txt:");
    while (myFile.available()) {
      Serial.write(myFile.read());
    }
    myFile.close();
  } else {
    Serial.println("error opening test.txt");
  }
  //// SD END
}

void loop() {
  sensorValue = analogRead(analogInPin);
  if (sensorValue < 1000) {
    action();
  }
}

void action() {
//  display.display();
//  display.clearDisplay();
//  display.setCursor(0, 0);
//  display.setTextSize(2);
//  display.setTextColor(WHITE);
//  display.println(sensorValue);
// if uncomment this code, i am getting error with sd card reading (possible memory issue)
}

Your code is using in the neighborhood of 150 bytes for text-strings in RAM, much of which can be moved to PROGMEM quite easily.  For example, replace
Serial.print("Initializing SD card...");

by
Serial.print(F("Initializing SD card..."));

Changes like that to Serial.print() arguments should free up about 140 bytes of RAM.  To free up another 8 bytes, instead of SD.open("test.txt" ...), write SD.open(FileName ...) with FileName previously declared via char *FileName = "test.txt"; so that the text test.txt appears in RAM once instead of twice.
In short, if 150 bytes will make the difference, that much memory reduction is easy.

I briefly examined the source code behind the Adafruit_SSD1306.h and SD.h headers, to see if they use some large arrays in RAM, such as 512 bytes of sector data, or some hundreds of bytes for frame buffers.
Ordinarily, such arrays are difficult to get rid of without a rewrite from scratch or without major loss of functionality.  For most one-off projects, the effort involved isn't worthwhile:  one can instead use an Arduino Mega2560 system, which has 8 KB of RAM, vs the Arduino Nano's 2KB RAM; or can use an Arduino Due with 96KB RAM; or a Teensy, with 8, 16, or 64KB RAM.
However, if you plan a production run and are trying to hold down costs by using Nanos, consider the following approach:   Carefully arrange the processing so that you are done with SD buffers before needing a display frame buffer; and revise the libraries so the SD buffer and frame buffer overlap.  That is, place the smaller buffer within the same region of memory holding the larger buffer.  If processing can't be neatly separated, blank the display while using the shared buffer area for accessing SD data.
[Note, I edited this answer and expanded discussion of buffers in the libraries.]


text:
Serial Write fails to send when Motors moving
I have an unusual bug with the code I have written for my rover V2 robot.
I have a raspberry pi running some computer vision code written in opencv tracking an object doing the heavy processing.
Once the object is detected, a command is sent via serial (USB) to make the robot move left, right, forwards etc.. The pi sends: w, a or d for the direction it wants the rover to move, it then turns off it's ability to send any further commands via a flag and will turn this back on when the rover sends a response confirming it has completed the command.
The idea is, eventually the rover v2 will be able to do some audio processing itself so it can turn and face the direction of a sound impulse but always prioritize any incoming serial data, sending the more accurate movement commands.
So my idea has been to implement an interrupt routine that is called upon receiving a command using the less than perfect approach suggested here.
So now for the weird part.. the code works entirely... until the motors have power!
If the Rover V2 motor power is entirely disabled the interrupt routine will work flawlessly. The Raspberry Pi will send a command and receive every reply from the Rover.
However, if the Rover V2 Motors are powered on, the Rover will receive all commands and send replies accordingly. The issue is for some reason, the Raspberry Pi will occasionally not receive a reply rendering the robot stationary as no more commands can be sent, this happens after varying periods of time all the way from 2 successful command interrupts to 100.
The fact that this occurs only when power is applied to the motors on the Arduino, is leading me to believe it is not a fault in the Pi code.
Why is it, that as soon as the power is applied to the motors there is inconsistency in the transmission of serial replies?
Does anybody have any suggestions on how I could further diagnose the cause of this fault?
Or is there any obvious issues in this code I have not seen?
Thanks in advance!
ohkneel
Code can be  viewed HERE

Without examining your code my immediate thought is EMI. As the motors spin then induce noise in the comms signals which corrupts them making the Pi not receive the right thing. What EMI filtering do you have on your motors?

One thing to try would be doing a dry run - let it "move" the motors but disconnect them.  Also consider if your power source is truly sufficient for the motor demands and sufficiently separated from the logic supply source.  It's possible you will see messages related to USB interference is the dmesg output of the pi.  You might ultimately want to consider using a different interface than USB, and implementing error correction.  Also consider a mechanism (timeout, break, or even watchdog) to get out of unexpected but possible software states - ideally indicate the issue before recovering.

Fixed: Interrupt routine was calling itself nestedly, terrible practice, lesson learnt!
Thanks for the suggestions guys!


text:
Arduino IDE doesn't release COM port after programming
I have an arduino mega 2560 and I'm trying to program it using Arduino IDE 1.8.1. The problem is that I also need to keep open another program that will communicate with the Arduino using the COM port. I usually have to make very small changes to the code with the IDE and then check the results in the program.
However, when the IDE has finished uploading the program it will not release the COM port, and the program I'm using will give me an error message saying "access denied". This is a problem because I want to keep both programs open at the same time.
In fact I could just: make my correction to the code, close the IDE when it has finished, open the program I need, check whether the correction I made was right, otherwise close it again and open the IDE again, but that would take an insane amount of time and it would be quite annoying.
Is there a way to force the Arduino IDE to release the COM port so that other programs could communicate with the Aduino?

To force the Arduino IDE to disconnect from the COM port, simply go into the Tools menu, go to Ports and select another COM port.
Alternatively, you can open and then close the serial port monitor (Ctrl+Shift+M then Alt+F4).

This type of problem happens many time with me. Try to disconnect your ARDUINO MEGA from your PC / LAPTOP and then connect it again. It must be solve your problem. If this will not work then restart your PC / LAPTOP and try it out again.

disconnecting the arduino right after the upload will cause the IDE to freeze.

So, first disconnect your arduino and then close IDE. And now open again IDE and connect your Arduino. Try it. Otherwise may be cable fault possible. Try it out with other cable.

I don't think you really understood my question, I've updated to make it more clear.


text:
Problem in getting the output (language: Processing and Arduino IDE)
I am working on a small project with Processing and Arduino, in which, depending upon the value of a photoresistor, it displays whether it is day/night/evening.
I read the value from the photoresistor and write the value to the serial port. Then in Processing I read the value from the serial port and display depending on the value.
But I get a very flickery output, and there is always a -1 imprinted on the screen as shown in the video.
Please help me out.
link to the video
Code for Arduino:
int ldr1 = A0;
int x,y;

void setup() {
  pinMode(ldr1,INPUT);
  Serial.begin(9600);
}

void loop() {
  x = analogRead(ldr1);
  Serial.write(x);
  delay(100);
}

Code for Processing:
import processing.serial.*;
Serial port;
int x,y;

void setup() {
  size(640, 320);
  port = new Serial(this, "COM3", 9600);
}

void draw() {
  background(0);
  x = port.read();
  text(x,100,100);
  if(x < 400 && x > 200) {
    textSize(32);
    fill(0,0,255);
    text("it is evening",200,200);
  }
  if(x < 200 && x > 20) {
    textSize(32);
    fill(0,255,0);
    text("it is night",200,200);
  }
  if(x > 400 && x < 900) {
    textSize(32);
    fill(255,0,0);
    text("it is morning",200,200);
  }
}

Is the Arduino actually on COM3? If serial read returns -1, then you did not receive a byte. You should check for if read >= 0 before entering your "if x < ... " etc.

If you read the documentation for Serial::read() at https://processing.org/reference/libraries/serial/Serial_read_.html
it says:
"Returns a number between 0 and 255 for the next byte that's waiting in the buffer. Returns -1 if there is no byte, although this should be avoided by first cheacking available() to see if data is available."
Either before calling "Draw" function, or inside "Draw", you should first check:
if(port.available()){
  //do your checking for X value and set text as you are doing before

}

IMPORTANT - you are only ever sending the lower byte (values 0-255) from Arduino when you do Serial.write(x). That is only 1 byte. The "int" return from an analogue read is 10 bits, and needs 2 bytes to store the information from 0-1023.
You should use the Arduino function Map() to scale it down from 0-1023 to 0-255. It looks like your application should be okay with this, in terms of resolution.
  int val = analogRead(ldr1);
  val = map(val, 0, 1023, 0, 255);
  Serial.write(val); //now you will not lose information

On the Processing side, you would then look at values from 0-255 to determine daylight/times of day.

Map is great if you need to do a linear interpolation but in a situation like this it's complete overkill. Rather than using map you could just divide the value by 4 or shift it right by 2 bits using 'val = val >> 2'. Either of these options are both far smaller and faster.

@Andrew you are correct, it's handy that it's a factor of 2 so shifting or division is fine.


text:
Arduino Blink two LEDs without Delay(amount of repetitions)
Arduino community.  I have had experience with Arduino for 3 years now and have finally come to the conclusion to get rid of the delay function entirely.
Below is the code to blink two LEDs a complete 10 times.  The problem is that the setup() doesn't repeat like a loop(), which means it doesn't last a long enough to find a time difference between PreviousMillis and CurrentMillis because it runs once; thus, defeating the idea of blinking a LED in the setup().  But, I have researched ways to imitate the loop() with while loops; I have used Adafruit's method to spice things up(Constructors and classes!),
https://learn.adafruit.com/multi-tasking-the-arduino-part-1/overview.
But I need a little help because it doesn't work, instead, it blinks forever(Mission half-complete =)).
Notice how I have used while loops in the Update(), which is located within the Flasher Class, to mimic a loop() until the condition becomes true.
The problem is, I don't know why this code doesn't work and what to do from here.
The ultimate goal is to blink the LEDs at pin 12 and pin 13 a total of 10 Times, instead of repeatedly blinking for an eternity.  I am using an Arduino Uno R3 and a Serial baud rate of 115200.
Ignore what I did in the loop().  It's the same function as the setup() code, instead, the led blinks an eternity (unfortunately), when a value of "1" is typed.
    class Flasher{
    // Class Member Variables
    // These are initialized at startup
    int ledPin;      // the number of the LED pin
    long OnTime;     // milliseconds of on-time
    long OffTime;    // milliseconds of off-time

    // These maintain the current state
    int ledState;                 // ledState used to set the LED
    unsigned long previousMillis;   // will store last time LED was updated
    unsigned long currentMillis = 0;

  public: Flasher (int pin, long on, long off)
{            // Constructor - creates a Flasher
    // and initializes the member variables and state

      ledPin = pin;
      pinMode(ledPin, OUTPUT);

      OnTime = on;
      OffTime = off;

      ledState = LOW;
      previousMillis = 0;
    }

    void Update(int a){
      // check to see if it's time to change the state of the LED
      for (int i = 0; i < a; i++) {
        while ((currentMillis - previousMillis <= OnTime) || ((currentMillis - previousMillis <= OffTime))) {
          currentMillis = millis();

          if ((ledState == HIGH) && (currentMillis - previousMillis >= OnTime))
          {
            ledState = LOW;  // Turn it off
            previousMillis = currentMillis;  // Remember the time
            digitalWrite(ledPin, ledState);  // Update the actual LED
          }
          else if ((ledState == LOW) && (currentMillis - previousMillis >=OffTime))
          {
            ledState = HIGH;  // turn it on
            previousMillis = currentMillis;   // Remember the time
            digitalWrite(ledPin, ledState);   // Update the actual LED
          }
        }
      }
    }
};

Flasher led1(12, 100, 400);
Flasher led2(13, 350, 350);

void setup(){

  Serial.begin(115200);
  led1.Update(10);

}

void loop(){

   /* if (Serial.available()) {
      String str = Serial.readString();

      if (str.substring(0, 1).equals("1")) {
        led1.Update(10);

      }
  }*/
}

SimpleTimer and similar millis()-based timer libraries are made for just this kind of job. SimpleTimer even allows you to specify a number of repetitions as well. The gist of it is you set a timer to an interval and perhaps a number of repetitions, and a callback function to be called at the end of each interval. Your main code just calls the timer's update function, "run()" in this case, very frequently. Your callback function will be called at the appropriate times. This is one of the easiest ways to implement this kind of job, mimicking foreground/background but without the complexity of interrupts and interrupt service routines.

I've modified your sketch so that when you instantiate a LED Flasher object with a 4th argument, it flashes forever. If you instantiate a Flasher object with 3 arguments, use the Start() function to start the LED flashing the number of times you specify. Just call it once, not repeatedly in the loop() function (e.g. when a button is pressed). You can call the Start() function again and specify a different number of flashes. You can have multiple LED flasher objects. Each object can have different on/off times. Some LEDs can flash forever, and some the number of times specified.
EDIT
I've added a few functions in the class to make it more versatile: Stop(), SetPinHighTime(), SetPinLowTime() and SetFlashForever().
class Flasher{

  // Class Member Variables. These are initialized at startup.
  byte ledPin;
  byte ledState;
  byte flashForever;
  unsigned int flashCounter;
  unsigned long highTime;
  unsigned long lowTime;
  unsigned long previousMillis;

  // Constructor. Create a LED Flasher object.
  // Initialize the member variables and LED state.
  public:

  Flasher(byte pin, unsigned long on, unsigned long off, byte continueFlashing = 0){
    ledPin = pin;
    pinMode(ledPin, OUTPUT);
    highTime = on;
    lowTime = off;
    ledState = LOW;
    flashForever = continueFlashing;
    previousMillis = 0;
  }

  void Update(){

    // Check to see if it's time to change the state of the LED.
    unsigned long currentMillis = millis();

    if((ledState == HIGH) && (currentMillis - previousMillis >= highTime) && ((flashCounter > 0) || (flashForever == 1))){
      ledState = LOW;
      previousMillis = currentMillis;        // Remember the time.
      digitalWrite(ledPin, ledState);        // Update the actual LED.
      if(flashCounter > 0){flashCounter--;}  // Update the flash counter.
    }
    else if((ledState == LOW) && (currentMillis - previousMillis >= lowTime) && ((flashCounter > 0) || (flashForever == 1))){
      ledState = HIGH;
      previousMillis = currentMillis;        // Remember the time.
      digitalWrite(ledPin, ledState);        // Update the actual LED.
      if(flashCounter > 0){flashCounter--;}  // Update the flash counter.
    }
  }

  void Start(unsigned int flashNumberOfTimes){
    flashCounter = flashNumberOfTimes * 2;
    flashForever = 0;
    ledState = LOW;
    digitalWrite(ledPin, ledState);
  }

  void Stop(){
    Start(0);
  }

  void SetPinHighTime(unsigned long pinHighTime){
    highTime = pinHighTime;
  }

  void SetPinLowTime(unsigned long pinLowTime){
    lowTime = pinLowTime;
  }

  void SetFlashForever(byte oneOrZero){
    flashForever = oneOrZero;
    if(oneOrZero == 0){Start(0);}
  }

  void SetPinToInput(){
    pinMode(ledPin, INPUT);
  }

};

// Used for testing purposes only.
byte doOnce = 0;
const byte led1PinNumber = 2;
const byte led2PinNumber = 3;
const byte led3PinNumber = 4;

// Instantiate LED Flasher Object(s).
// e.g. Flasher object_name(Pin Number, ON Time, OFF Time, OPTIONAL Flash Forever);

// Three argument constructor.
// The number of times to flash the LED is specified
// when you call the Start() function. The LED will NOT
// start flashing until you call Start().
Flasher led1(led1PinNumber, 10, 990);
Flasher led2(led2PinNumber, 100, 400);

// Four argument constructor.
// Flash an LED forever. This will start the LED flashing immediately.
Flasher led3(led3PinNumber, 1000, 1000, 1);

void setup(){}

void loop(){

  // Call the Update function as fast as possible.
  led1.Update();
  led2.Update();
  led3.Update();

  // Test output. Flash 3 LEDs with different on/off times.
  // Use the Start() function to flash 2 of the LEDs X number
  // of times, then restart each LED flasher object with
  // a different number of flashes. Set 1 LED to flash forever,
  // then stop it and start a different LED flashing forever,
  // altering the flash rates of one LED before restarting it.
  // Finally, set the 3 LED pins to INPUT.

  // Start the led1 object 4 seconds after Arduino startup.
  if(millis() > 4000 && millis() < 5000 && doOnce == 0){
    led1.Start(3);  // Flash the LED 3 times.
    doOnce = 1;
  }

  // Start the led2 object 5 seconds after Arduino startup.
  if(millis() > 5000 && millis() < 6000 && doOnce == 1){
    led2.Start(5);  // Flash the LED 5 times.
    doOnce = 0;
  }

  // Restart the led1 object 10 seconds after Arduino startup.
  if(millis() > 10000 && millis() < 11000 && doOnce == 0){
    led1.Start(7);  // Flash the LED 7 times.
    doOnce = 1;
  }

  // Restart the led2 object 15 seconds after Arduino startup.
  if(millis() > 15000 && millis() < 16000 && doOnce == 1){
    led2.Start(9);  // Flash the LED 9 times.
    doOnce = 0;
  }

  // Stop flashing the led3 object.
  // Start flashing the led1 object forever.
  if(millis() > 30000 && millis() < 31000 && doOnce == 0){
    led3.SetFlashForever(0);
    led1.SetFlashForever(1);
    doOnce = 1;
  }

  // Stop flashing the led1 object.
  // Start flashing the led3 object forever and change
  // it's flash rate.
  if(millis() > 50000 && millis() < 51000 && doOnce == 1){
    led3.SetPinHighTime(250);
    led3.SetPinLowTime(500);
    led3.SetFlashForever(1);
    led1.SetFlashForever(0);
    doOnce = 0;
  }

  // Stop flashing the led3 object. No LEDs should be flashing.
  if(millis() > 60000 && millis() < 61000 && doOnce == 0){
    led3.Stop();
    doOnce = 1;

    // My test shield has one High and one Low LED per pin.
    // Set the pins to input to turn off the Low LEDs.
    led1.SetPinToInput();
    led2.SetPinToInput();
    led3.SetPinToInput();
  }

}

From pure C++ point of view, this implementation might be correct, however, 1) for Arduino, setup() get call in Arduino main() after some initialisation of hardware, it is why Arduino advocate to have initialise hardware with a begin() method than using the construct (it happened before the initialisation of the hardware).

For C++, if your implementation of class methods within the Class, by default, all the methods would be considered as inline methods. what this means is that for example the update() will be inserted as inline at where it get called. It is therefore necessary to separate the Class prototype from implementation.

@hcheung - The constructor takes care of initializing the required variables when the object(s) are instantiated. If you could answer the OP's question with the code required to implement the begin() function, I would up-vote such an answer.

@hcheung - 2) "It is therefore necessary to separate the Class prototype from implementation. - Says who? I can write "Arduino code" any way I like, so long as it compiles, is the smallest compile size, and works perfectly. I think the compiler is smarter than me, and can take code written by millions of different users world wide, and make it work just fine :) Feel free to answer the question with a better answer.

Well, I didn't say it doesn't work, and for Arduino, people may not care about the size of the code much either, in fact, most of Arduino users think of learning C++ is optional. It is not part of compiler optimisation, it is how C++ is defined. "A class's member functions can be declared inline, either by using the inline keyword or by placing the function definition within the class definition". You can check any book about C++ from Bjarne Stroustrup.

@hcheung - I don't care what the books say. I'm retired, so I write code the way I like. If you have a "proper" answer, which agrees with your book(s), do tell...

Let us continue this discussion in chat.

For such a simple task, the code is very complex.
First, write a piece of code that blinks the LEDs if sufficient passage of time has been met.
You can implement a blink counter, either in the main loop or the blink routine mentioned earlier.
Should be fairly simple.
edit: here is how I would have implemented it.
//blink the led for a given number of times
//cnt: number of times of the blinks needed
uint8_t led_blinky(uint8_t cnt) {
    static uint8_t led_cnt=0;       //blinky count
    static uint32_t millis_prev=0;  //previous millies

    if (led_cnt>=cnt) return led_cnt;   //return blink count
    if (millis() > millis_prev + LED_ms) {    //enough time has passed
        millis_prev += LED_ms;                      //update the time
        digitalWrite(LED, (digitalRead(LED)==HIGH)?LOW:HIGH);       //flip led
        led_cnt+=1;                 //increment the led count
    }
    return led_cnt;                 //return blinky count
}

the code itself is fairly self-explanatory -> the only (marginally) tricky part is how it maintains timing accuracy over a long period of time. in this particular implementation, the test is done inside the led_blinky() routine so it is self-contained -> it does return the number of blinks that have been executed.
Here is the execution of performing 100ms blinks 4 times:

I'd like to proposes a couple of changes to @VE7JRO's implementation.
For C++, it is perfectly normal to initialise an Class instance via its construct, however, for Arduino, the setup() get call in Arduino main() after some initialisation of the hardware, including pin definition, etc., it is why Arduino advocates in Arduino Style Guide for Writing Libraries to use a begin() to initialize a library instance (it is perfectly okay to use the construct to setup some variables but not for something like pinMode() in the construct). Because very often the creating of a Class instance happened before the setup() get called.
With this in mind, the propose changes:
class Flasher{

  // Class Member Variables. These are initialized at begin().
  byte ledPin;
  byte ledState;
  byte flashForever;
  unsigned int flashCounter;
  unsigned long highTime;
  unsigned long lowTime;
  unsigned long previousMillis;

  public:

  Flasher() {}

  begin(byte pin, unsigned long on, unsigned long off, byte continueFlashing = 0){
    ledPin = pin;
    pinMode(ledPin, OUTPUT);
    highTime = on;
    lowTime = off;
    ledState = LOW;
    flashForever = continueFlashing;
    previousMillis = 0;
  }
  ....
};

To use the Class:
Flasher led1;
Flasher led2;
Flasher led3;

setup() {
  led1.begin(led1PinNumber, 10, 990);
  led2.begin(led2PinNumber, 100, 400);
  led3.begin(led3PinNumber, 1000, 1000, 1);
}

Another change has to do how C++ defined inline function or method. "A class's member functions can be declared inline, either by using the inline keyword or by placing the function definition within the class definition". What this means is that all the functions defined in the Flasher class in this case are implied as inline methods. so when led.update() get call, it is placed as inline code by the compiler at where it get call (and multiple times). There are certain methods that are perfectly okay and in fact should be inline, for example, SetPinHighTime(), and SetPinToInput() would actually benefit from being inline, but you will probable don't want the update() method to be inline. In order to do that, create a Class prototype and have the methods that you'd want to be inlined implemented within the Class definition, but separate the implementation of update() method.
#ifndef FLASHER_
#define FLASHER_
#include "Arduino.h"

class Flasher{

  // Class Member Variables. These are initialized at startup.
  byte ledPin;
  byte ledState;
  byte flashForever;
  unsigned int flashCounter;
  unsigned long highTime;
  unsigned long lowTime;
  unsigned long previousMillis;

  public:

  // All methods are inline, except update()

  Flasher() {}
  void begin(byte pin, unsigned long on, unsigned long off, byte continueFlashing = 0){
    ledPin = pin;
    pinMode(ledPin, OUTPUT);
    highTime = on;
    lowTime = off;
    ledState = LOW;
    flashForever = continueFlashing;
    previousMillis = 0;
  }

  void Update();

  void Start(unsigned int flashNumberOfTimes){
    flashCounter = flashNumberOfTimes * 2;
    flashForever = 0;
    ledState = LOW;
    digitalWrite(ledPin, ledState);
  }

  void Stop(){ Start(0); }

  void SetPinHighTime(unsigned long pinHighTime){
    highTime = pinHighTime;
  }

  void SetPinLowTime(unsigned long pinLowTime){
    lowTime = pinLowTime;
  }

  void SetFlashForever(byte oneOrZero){
    flashForever = oneOrZero;
    if(oneOrZero == 0){Start(0);}
  }

  void SetPinToInput(){ pinMode(ledPin, INPUT); }

};
#endif

Define update() method separately in implementation Flasher.cpp:
#include "Flasher.h"

Flasher::update() {

    // Check to see if it's time to change the state of the LED.
    unsigned long currentMillis = millis();

    if((ledState == HIGH) && (currentMillis - previousMillis >= highTime) && ((flashCounter > 0) || (flashForever == 1))){
      ledState = LOW;
      previousMillis = currentMillis;        // Remember the time.
      digitalWrite(ledPin, ledState);        // Update the actual LED.
      if(flashCounter > 0){flashCounter--;}  // Update the flash counter.
    }
    else if((ledState == LOW) && (currentMillis - previousMillis >= lowTime) && ((flashCounter > 0) || (flashForever == 1))){
      ledState = HIGH;
      previousMillis = currentMillis;        // Remember the time.
      digitalWrite(ledPin, ledState);        // Update the actual LED.
      if(flashCounter > 0){flashCounter--;}  // Update the flash counter.
}

I hope this will help to make the class better and better understanding on C++ and Arduino, and next time when you read the source of an Arduino library, you had better understanding on why the library implement its class and methods the way it does.

So, you took my 3 lines of code used to instantiate the 3 objects (via the constructor), added 3 more lines to it, which accomplishes the same thing as the original 3 lines did. Did you compare the compile size / memory usage for your method VS my method? -1 for taking simple code and making it more complex.


text:
How do I update library h-file in arduino create online editor?
I'm working on a sketch that includes i2c with a SSD1306 OLED and need to update a constant in Adafruit's h-file in the library.
How can I do this in the online editor?
/Jonas


text:
How get assembler/preprocessed code for library
I am using https://github.com/sudar/Arduino-Makefile project with https://github.com/ladislas/Bare-Arduino-Project to compile my Arduino projects from Linux command line. I put as much as possible functionality to libraries for reuse (and use the same libraries from many projects too).
Now I had run to some problems and I am not sure, if I am using the language (C/wiring/...) properly, as a lot of #define macros are used. I think, that seeing the resulting code would help me greeatly in finding, wheather some specific lines are compiled into what I want them to be compiled. I am interested mainly in the library code, even if it would mean to dump full program together with all used standard libraries. (I can find my way in large files.)
I would prefere intermediate files, as I suppose they could contain more info than just dissassembled .HEX file, but if this assumption is not correct, and I can get the same from .HEX, than I can use that way as well.
Question: How to get intermediate files (Ideally both "plain C" after preprocessing all macros AND "plain ASM" after compiling the code) ideally with corresponding lines of original code as comments inside.
Subquestion: In the above, how to disable optimalisation as much as possible, to get the code more verbatim similar to original C (I know, that it would hurt both speed and size and I do not care - I just want to be sure compiler does undertand my code the same way as I myself and if not, then see, where I made mistakes)
Thanks for all suggestions :)

seeing the resulting code would help me greeatly in finding, wheather some specific lines are compiled into what I want them to be compiled. - what, exactly, do you "want" them to be compiled into? The compiler generally compiles your C++ code accurately into machine code. Are you suggesting you could find flaws in the way it does that?

Exactly the other way. "Computer does every time exactly what you command it to do and never what you want it to do." I have some idea, I write a code and it does not work. So it means, there are some bugs. Some are in logic, some are in syntax, where I write command, which does something other, than I had in mind, when I wrote it. But seing the generated code means I see the same as computer and then I can see, that this value should not be here but there and should read this way. So that I wrote the command wrong. And should write it different way. Because I made some bad assumptions

http://stackoverflow.com/questions/42617079/how-to-pack-mix-of-up-to-4-uint-8t-and-int8-t-into-one-uint32-t

For example here http://stackoverflow.com/questions/42617079/how-to-pack-mix-of-up-to-4-uint-8t-and-int8-t-into-one-uint32-t I had bad types in the code, so it does not worked exactly as I needed. Writing some (uint8_t) here and (uint32_t) there solved problem. Finding where and what to write took much more time, than to do it then. Seeining the generated code can show me, where are bytes loaded to registers and where are converted to int16_t (which I did not want), then shifted, and that the shifts should be in 32-bits, not 16-bits blocks. Faster to read the result code, than to test values

One method I've used for creating assembly listings for Arduino sketches when using the Arduino IDE is as follows:
• Click Verify to compile the sketch
• Locate the the temporary build directory
• Use avr-objdump with -CSI... switches to decode the ELF file
Here are some commands you can put into a shell file to automate that procedure, on a Linux system:
item=*.ino
[ -z "$item" ] && echo ino file not found && exit
BDIR=/tmp/$(ls -t /tmp | egrep -m1 build.*tmp)
BASE=$(basename $item .ino)
avr-objdump -CSI$PWD $BDIR/$BASE.cpp.elf > $BASE.ino.asm

The above assumes the current working directory (ie, $PWD) is the directory with the sketch in it; variable item is the sketch name; variable BASE is the basename of the sketch, with .ino stripped off; $BDIR is the most-recently-used temporary build directory (which, on Ubuntu Linux systems, has a path that starts with /tmp/build); and the resulting deassembly is placed in $BASE.ino.asm for viewing.
To try this manually, as you may need to do on systems where the above shell commands don't work, say
avr-objdump -CSIddd bbb/sss.cpp.elf > sss.ino.asm

in a shell or at a command console, replacing ddd with the sketch's source directory name; bbb with the temporary build directory's name; and sss with the sketch's name.

Edit 2: Using Sudar's Arduino Makefile probably is the best starting point for looking at source code that has been pre-processed, or that has been compiled (into assembly language).  This makefile system is fairly easy to install and use.
When you have the makefile system  installed and working, you can generate  pre-processed code (code that's been run through the pre-processor to incorporate #include files and to expand macros) by adding the following line within a makefile:
CPPFLAGS += -E

The -E switch tells avr-gcc to stop after preprocessing.  According to man gcc its effect is:

Stop after the preprocessing stage; do not run the compiler proper.  The            output is in the form of preprocessed source code, which is sent to the            standard output.

To generate assembly language, add the following line within a makefile:
CPPFLAGS += -S

The -S switch tells avr-gcc to stop after compiling.  According to man gcc its effect is:

Stop after the stage of compilation proper; do not assemble.  The output is in the form of an assembler code file for each non-assembler input file specified. ... By default, the assembler file name for a source file is made by replacing the suffix .c, .i, etc., with .s.

If you are skilled at makefile writing, it may be possible to add a target with rules to generate assembly or pre-processed code for inspection.  Actually, Sudar's Arduino Makefile appears to have assembly-listing targets and rules already (as below for .pde; others for .ino and .cpp) although I haven't gotten them to work:
# generated assembly
$(OBJDIR)/%.s: %.pde $(COMMON_DEPS) | $(OBJDIR)
        @$(MKDIR) $(dir $@)
        $(CXX) -x c++ -include $(ARDUINO_HEADER) -MMD -S -fverbose-asm $(CPPFLAGS) $(CXXFLAGS) $< -o $@

[I now see that Edgar Bonet has mentioned this too.]

Thanks, the -S flag is nice.  Do you know about way to get preprocessed files too? This one dissassemble the compiled code, but I would like also to see the preprocessed code, where macros are expanded, but it is still the text, not binary translated back. (so I can see eq. a=16|4|2, not just loading 22 to some memory location)

@gilhad, I wasn't sure what you meant by preprocessed.  See -s or -S flag to avr-gcc, I don't remember which, will look tomorrow

accepted & upvoted. Just for record it can be called from command line like CPPFLAGS+=' -E ' make  respective CPPFLAGS+=' -S ' make  after make clean (to force generating code for everything)

You can get the generated assembly by passing the -S option to
avr-g++. The makefile you are using has a rule for that, so you would
just type
make build-*/my_file.s

to get the assembly for my_file.cpp.
For the pre-processed C++, you use the -E option. There is no rule for
that in the makefile, so you will have to write yo own, or manually
invoke the compiler. At a minimum:
avr-g++ -mmcu=my_mcu -E my_file.cpp > my_file.i

You may want to add -DF_CPU=... -DARDUINO=... just like the makefile
does when compiling the same file.


text:
MPU6050 Sending Bad values for Angular Velocity
The mpu gives me perfectly fine values for the yaw, pitch, and roll position of the chip, but when I use mpu.getRotation(&gx, &gy, &gz) to obtain the current angular velocity of the chip, the values returned are awful. I wrote a program in Processing to graph the data from my Arduino, and this is what it looks like:

I suggest you click on the picture and zoom in a bit because it's difficult to see. The green line represents zero (0), the Pink line represents the angular position of the mpu6050 chip, obtained from mpu.getYawPitchRoll..., and the Blue line represents the angular velocity on the same rotational axis.
A few extra things to note:

The scale between the Pink and the Blue lines is slightly off, but that shouldn't matter for this purpose.
The time-frame for this graph is about 16s.
Before being graphed, the raw gx value is divided by the gyro's sensitivity scale factor, 131, and then converted from radians to degrees.
In addition to this, it is also put through a complementary filter, so the whole formula looks like this: rollRate = (0.7*rollRate) + (0.3*(-180 * gx / 131 / M_PI));

As you can see, the measurements for angular velocity (Blue) make almost no sense when graphed next to the angular position (Pink).
My question is this: What can I do to clean-up/filter these angular velocities and get rid of all the errors? I need these values to be accurate enough to be used in something like a drone PID.
Things I have tried:

Complementary filters of various proportions.
Adjusting the MPU's built in low-pass filter.

Thanks for any suggestions.

At last! I have discovered the solution.
Quick Solution for those who don't like reading: Amend the previous rollRate formula to rollRate = (0.7 * rollRate) + (-0.3 * gx / 16.4);. Or, if you don't want the filter, rollRate = -1 * gx / 16.4;
The problem starts with the function mpu.getRotation(&gx, &gy, &gz) which accepts int16_t types for gx, gy, and gz. Since int16_t is a 16 bit integer, it has a maximum range of -32,768...+32767. The reason this integer type is used is because the output range for the gyro is -32750...+32750, which fits nicely into the 16-bit integer's range.
The problem was that when I converted these values to a readable angular velocity (and complementarily filtered) using  rollRate = (0.7*rollRate) + (0.3*(-180 * gx / 131 / M_PI)); , the gx value was multiplied by -180 in part of the calculation. This means that if gx was high enough initially, it would have rolled over to -32786 and ruined the whole calculation, causing the horrible spikes in the graph.
At the same time I discovered this problem, I also realized that converting from radians to degrees was unnecessary, as the gyro output was already in units of degrees (just scaled by a sensitivity factor). After that big face-palm, I revised my rate formula to the following: rollRate = (0.7 * rollRate) + (-0.3 * gx / 16.4);. You will notice the scale factor has changed from 131 to 16.4. That is because the gyro range is actually +/-2000 deg/s by default, not 250 deg/s. I tried to change it back to +/-250 with mpu.setFullScaleGyroRange(MPU6050_GYRO_FS_250);, but after examining the graph, it appeares that mpu.dmpGetYawPitchRoll(ypr, &q, &gravity); does not account for this setting change, and resulted in the ypr overshooting and then leveling out to its correct value after a delay. I decided not to mess around with the quaternion container, q, and just accepted the lower sensitivity.

Like the previous image, I suggest zooming in.


text:
Line Following Robot
I have written a code and it works OK with the robot on straight, curved, intersections.   But the robot just moves forward in the current direction whenever it comes across an acute angle turn. I am attaching the code in the description ....can anyone please guide me through the necessary changes or the troubleshoot procedures?
#define left_pwm 6
#define right_pwm 3
#define left_1 5
#define left_2 7
#define right_1 4
#define right_2 2
const int ledPin1 = 9;

int left1;
int left2;
int left3;
int left4;
int right1;
int right2;
int right3;
int right4;
int lc=1;
int sc=0;

float Kp=120, Kd=130;
float error=0, P=0, D=0, PID_value=0;
float initial_motor_speed_l=100;
float initial_motor_speed_r=100;
float left_motor_speed=0, right_motor_speed=0;
float previous_error=0;

int left=0;
int right=0;

void setup()
{

  pinMode(A0,INPUT);
  pinMode(A1,INPUT);
  pinMode(A2,INPUT);
  pinMode(A3,INPUT);
  pinMode(A4,INPUT);
  pinMode(A5,INPUT);
  pinMode(11,INPUT);
  pinMode(10,INPUT);

  pinMode(right_pwm,OUTPUT);
  pinMode(right_1,OUTPUT);
  pinMode(right_2,OUTPUT);
  pinMode(left_1,OUTPUT);
  pinMode(left_2,OUTPUT);
  pinMode(left_pwm,OUTPUT);
  pinMode(ledPin1,OUTPUT);

}
void loop()
{
    line_follow();
 if (right4==lc && left==lc)
 {
  brake();
 }
 else {
  forward();
 }

    if(right3==lc && left3==lc)
  {
    digitalWrite(9,HIGH);
  }
   else
  {
    digitalWrite(9,LOW);
  }
}
void pid()
{
    if((left1==lc)&&(right1==lc))
   {
    error=0;
   }
   else if(right1==lc)
   {
    error=0.5;
   }
   else if((right1==lc)&&(right2==lc))
   {
    error=1;
   }
   else if(right2==lc)
   {
    error=1.5;
   }
   else if((right2==lc)&&(right3==lc))
   {
    error=2;
   }
   else if(right3==lc)
   {
    error=2.5;
   }
   else if((right3==lc)&&(right4==lc))
   {
    error=3;
   }
   else if(right4==lc)
   {
    error=3.5;
   }
   else if(left1==lc)
   {
    error=-0.5;
   }
   else if((left1==lc)&&(left2==lc))
   {
    error=-1;
   }
   else if(left2==lc)
   {
    error=-1.5;
   }
   else if((left2==lc)&&(left3==lc))
   {
    error=-2;
   }
   else if(left3==lc)
   {
    error=-2.5;
   }
   else if((left3==lc)&&(left4==lc))
   {
    error=-3;
   }
   else if(left4==lc)
   {
    error=-3.5;
   }

   P = error;
   D = previous_error-error;
   PID_value = (Kp*P) + (Kd*D);
   previous_error=error;
   left_motor_speed = initial_motor_speed_l+PID_value;
   right_motor_speed = initial_motor_speed_r-PID_value;
   if(left_motor_speed>=255)
   {
    left_motor_speed=255;
   }
   if(left_motor_speed<=0)
   {
    left_motor_speed=0;
   }
   if(right_motor_speed>=255)
   {
    right_motor_speed=255;
   }
   if(right_motor_speed<=0)
   {
    right_motor_speed=0;
   }
   analogWrite(left_pwm, left_motor_speed);
   analogWrite(right_pwm, right_motor_speed);
   digitalWrite(left_1,HIGH);
   digitalWrite(left_2,LOW);
   digitalWrite(right_1,LOW);
   digitalWrite(right_2,HIGH);
}
void line_follow()
{
    left4=digitalRead(A0);
    left3=digitalRead(A1);
    left2=digitalRead(A2);
    left1=digitalRead(11);
    right1=digitalRead(10);
    right2=digitalRead(A3);
    right3=digitalRead(A4);
    right4=digitalRead(A5);

    if(left4!=0)
    {
     left=0;
    }
    if(right4!=0)
    {
     right=0;
    }
    if((left4==0)&&(left3==0)&&(left2==0)&&(left1==0)&&(right1==0)&&(right2==0)&&(right3==0)&&(right4==0))
    {
      if((left>150)&&(right<150))
      {
            left1=digitalRead(11);
          right1=digitalRead(10);
          while((right1==0)&&(left1==0))
      {
        right_turn();
        left1=digitalRead(11);
            right1=digitalRead(10);
       }

      }
      else if((left<150)&&(right>150))
      {
            left1=digitalRead(11);
            right1=digitalRead(10);

            while((left1==0)&&(right1==0))
        {
         left_turn();
         left1=digitalRead(11);
             right1=digitalRead(10);
            }
          }
        }
     pid();
     left=left+1;
     right=right+1;
     if(left>20000)
     {
       left=1000;
     }
     if(right>20000)
     {
       right=1000;
     }

}
void right_turn()
{
   analogWrite(left_pwm,75);
   analogWrite(right_pwm,75);
   digitalWrite(left_1,HIGH);
   digitalWrite(left_2,LOW);
   digitalWrite(right_1,HIGH);
   digitalWrite(right_2,LOW);
}
void left_turn()
{
   analogWrite(left_pwm,75);
   analogWrite(right_pwm,75);
   digitalWrite(left_1,LOW);
   digitalWrite(left_2,HIGH);
   digitalWrite(right_1,LOW);
   digitalWrite(right_2,HIGH);
}
void brake()
{
   analogWrite(left_pwm, 0);
   analogWrite(right_pwm, 0);
   digitalWrite(left_1,HIGH);
   digitalWrite(left_2,HIGH);
   digitalWrite(right_1,HIGH);
   digitalWrite(right_2,HIGH);
}
void forward()
{
   analogWrite(left_pwm,100);
   analogWrite(right_pwm,100);
   digitalWrite(left_1,HIGH);
   digitalWrite(left_2,LOW);
   digitalWrite(right_1,LOW);
   digitalWrite(right_2,HIGH);
}

Does it detect the line at all? You may blink an LED or send debug messages (bluetooth/serial?) to indicate that the sharp turn has been seen. Or is it a software error?

Just a small comment: did you really use 8 int variables for booleans? Moreover please describe more what is this setup... What are the sensors, how are they placed, what is the control technique?

@Paul it doesn't detect the acute turn lines , rest all the lines are detected by it perfectly. I suspect its a calibration and software error but I have no idea how to fix it ..can you please guide me through.

@frarugi87 the sensor used is a 8 sensor line following array clubbed with two 500 rpm medium torque motors. I have  used tb6612fng as the motor driver and Arduino uno as the microcontroller. I am attaching the picture of my robot in the description.

@frarugi87 the  6 out of 8 int variables read analog values not digital values . So basically only two of the int variables return Booleans.

@SomitSinha the left# and right# variables are only modified with a digitalRead, so they are either HIGH or LOW..

There are some lines in pid() that will never be called.
else if (right2 == lc)
{
    error = 1.5;
}
else if ((right2 == lc) && (right3 == lc))
{
    error = 2;
}

if right2 == lc then the second else if will never be called.
You need to refactor this function, its horrid.  Firstly the right and left values for error only differ in sign, so you could right a function that took 4 values in and returned an absolute number.  If you called it for left then make the result negative.  Something like this is actually better, but will prevent the error you had.
else if (right3 == lc)
{
      if (right4 == lc)
        error = 3.0;
      else
        error = 2.5;
}
else if (right4 == lc)
{
      error = 3.5;
}


text:
MPU-9250 IMU on SPI, external sensor or magnetometer using I2C master
I'm trying (for sport...) to use an MPU-9250 in SPI mode as it should be faster, and wasn't able to talk to the embedded magnetometer in my code.
I've gone through the documentation (RM-MPU-9250A-00 v1.4) which is a bit spartan on that subject but gives the rough idea, it should work by enabling the built-in I2C master feature and using "proxy" I2C registers; I've tried to "do as it says" to communicate with the magnetometer; I'm querying the magnetometer identification register, and I only see 0x00 in there.
I searched in nature, and couldn't find an example of F/LOSS software using an external sensor plugged on the MPU.
Perhaps I've done something wrong but I can't see it, so here's a bottle in the ocean :)

Why would you need to enable I2C master if you want to use SPI?  That just seems wrong, like the author of the doc was having a bad day.  Can you search around and see if there is any other evidence that this is the right thing to do,

The IMU chip can act as an I2C master to talk to downstream I2C devices...

It turns out that my mistake was in the SPI communication code, but nevertheless here is some info because it's not very obvious.
I went over the top and:

Review the electrical interface to see whether by any chance, my chip was badly hooked-up. Everything was fine.
Enabled register read-back and saw that... owww, it was bad.
Reviewing PS-MPU-9250A-01 § 7.5 SPI Interface I saw that I had made a stupid copy&paste error in my code... when copying my read code over to the write I forgot to adjust the MSB of the first spi byte.

Then:

I2C_MST_P_NSR=1 seems important or we get zeros
basic config in there, currently using the I2C proxy to read the magnetometer, and I don't like having a sleep to wait for I2C transfers to happen or not, but this is a WIP and the code won't go anywhere.

accept your onwn answer


text:
fast reacting color sensor
I want to recognize the color of passing by objects. The speed of the objects is quite fast, arround 1 meters per second maybe a bit slower. The objects can have only two colors, as an example red or green and the distance between the sensor and the passing by objects is only a few millimeter.
I want to use a color sensor or multiple sensors of the same type bheind each other and timed so that at least one of them take a measurement of the object.
But I dont know which sensor I should take.

I don't think this question has anything to do with Arduinos, at least not the way its currently written, but the answer is very simple look at the Pixie Cam. http://charmedlabs.com/default/pixy-cmucam5/


text:
Sending data from Arduino to laptop via bluetooth using java
I intend to establish communication between my laptop and Arduino via Bluetooth. I'm using BlueCove Java API. I'm unable to understand how to send data to Arduino using this. There are no clear examples available on the internet regarding how to establish the communication between these two. Could somebody provide any information on this?
I just want to send some string to Arduino, based on which it must send back something to the laptop. Any help on this would be greatly appreciated. Thank you.

I was able to establish bluetooth communication between Arduino and my laptop successfully. I made some observations, which I'd like to share. BlueCove library which I've been using, ultimately communicates to the Arduino by constructing a bluetooth URL. This bluetooth URL is of the form btspp://bluetooth_address_without_colon:1;authenticate=false;encrypt=false;master=false.
To find the bluetooth address of a device, enter the following command in the terminal
hcitool scan

This will display a list of devices along with their addresses.
For instance, if my HC-05 has an address  20:16:10:09:47:93 then the bluetooth URL can be formulated as
btspp://201610094793:1;authenticate=false;encrypt=false;master=false.
Note that the '1' here represents the rfcomm channel. By observation, I've found that HC-05 modules use rfcomm channel 1.
In your project, ensure that you import the two jars of BlueCove libraries viz bluecove-2.1.0.jar and bluecove-gpl-2.1.0.jar (latest version). You can download them from here.
This is the Java code for communicating with the Arduino to turn an LED ON/OFF:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;
import javax.bluetooth.UUID;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
public class HC05 {
boolean scanFinished = false;
String hc05Url =
"btspp://201610094738:1;authenticate=false;encrypt=false;master=false"; //Replace this with your bluetooth URL
public static void main(String[] args) {
try {
new HC05().go();
} catch (Exception ex) {
Logger.getLogger(HC05.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void go() throws Exception {
StreamConnection streamConnection = (StreamConnection)
Connector.open(hc05Url);
OutputStream os = streamConnection.openOutputStream();
InputStream is = streamConnection.openInputStream();
os.write("1".getBytes()); //'1' means ON and '0' means OFF
os.close();
byte[] b = new byte[200];
Thread.sleep(200);
is.read(b);
is.close();
streamConnection.close();
System.out.println("received " + new String(b));
}
}

This the Arduino code for controlling the LED:
int ledPin = 13;
int flag = 0;
int receivedData;
void setup() {
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);
Serial.begin(9600);
}
void loop() {
if(Serial.available()>0){
receivedData = Serial.read();
flag = 1;
}
if(flag == 1){
switch(receivedData){
case '0':
digitalWrite(ledPin, LOW);
Serial.println("LED Turned OFF");
break;
case '1':
digitalWrite(ledPin, HIGH);
Serial.println("LED Turned ON");
break;
default:
Serial.println("Nothing here");
break;
}
flag = 0;
receivedData = 12;
}
Serial.flush();
}

Thanks to @Sigma for sharing some valuable information
Reference:
https://stackoverflow.com/questions/33473926/best-practice-java-serial-bluetooth-connection-hc-05

Are using a bluetooth module like HC-05 or HC-06? Then first establish an connection to the module. Then start sending bytes(a string). But first thing first start the connection. Ive only done it with an Android to Arduino, but still the Android is written with Java.

Yeah, I'm using HC-05. I've been able to detect it by using the BlueCove library. I referred the code from here http://snapshot.bluecove.org/bluecove/apidocs/overview-summary.html#DeviceDiscovery. But, I have no clue what to do after this. I'm a beginner in Java.

I followed this one Github repo bluetooth Android, I understand that it isn't exactly Java but found a similar ex in Java with almost the same code, they follow the same practice. Open bluetooth, find the device-history of paired BT, set up an socket to that device, start sending and reciving message. Or else there is this one on SO link

The SO link worked out. It wasn't direct though. First I ran the Service Search program from here, and found out the url of my HC-05 device, after getting bombarded with exceptions few times. After that, I used that URL directly and sent data to the Arduino via bluetooth. But, while receiving data from Arduino on my laptop, there's loss of bytes. I send "LED" from Arduino, and end up receiving only "L". Thanks

Do you have a example code from Arduino and PC? Could be that your Read-method isn't running more then once. Are you sending the message from the Arduino, can you verify that? Are you using SoftwareSerial on Arduino? What BaudRate is everything running on, 9600-115200? Anyway you are doing progress, there is communication. Lets debug, is the problem on Arduino or PC?!

I'm running the Arduino code program from the SO link that you gave. I modified the code by just removing the delay(). I added a sleep of 200ms in my Java code after writing the request to Arduino. 200ms was enough for the Arduino to process my request. Then I read from the Arduino. This time it worked out well. But, I'm not sure if using Thread.sleep() is advisable in Java. I read somewhere that sleep() must be avoided.

I was successful in achieving bidirectional communication: PC to Arduino and vice versa. I didn't set any Baudrate in my Java code. I think it's taking 9600 by default. At the Arduino end, I set 9600bps. No, I didn't use SoftwareSerial on Arduino. I'll share the code and the method, once I optimize things. Whatever I did was not systematic. I need to make it systematic, so that everybody can understand. Thank you so much for providing the help.

You are awsome man! Hade the same problem and found out that thread.sleep(100) on the smartphone help me. Yes 9600 is default, you can change that by AT-commands to the HC-05. One thing to keep in mind is there shouldn't be any blocking code on the Arduino-side, it need to be flawless and always running. Read this a couple days ago, this awsome man explained what to use and what you should avoid in Serial communication. This is our bible now.

Thank you for sharing that link. It contains valuable information. Very soon, I'll be posting the shortcut that I've found.

I've posted it as answer. Hope it helps someone in future. Thanks for your help mate.


text:
MAX485 communication between multiple Arduinos
I purchased multiple Arduino Mini Pros and MAX485 TTL boards and now I'm trying to make them communicate together, but the problem is that I need that everyone can send and receive when needed.
I mean, normally, the "Master" request something and then the right "Client" responds. But in my application everyone's master and everyone can send at anytime to anyone. Is there a library, that synchronizes the Read/Write between those Arduinos, so that when one is sending (at anytime) that the other ones won't send, until the transmission of the Arduino who's sending is over?
If there's no library, could I attach one more pin between all Arduinos that act like a PTT switch? When one want to send, it pulls the pin X high and if some other Arduino want to send, it checks for that high pin: If it's high, it will wait. Could that work too? Or maybe this isn't reliable?
Any suggestion or help are highly appreciated.

everyone's master and everyone can send at anytime to the master... just think about that for a second and ask yourself if that makes sense.

sorry about the redundancy... but I hope you got the point @dannyf :)

I tried to write a helpful answer but failed.  Your PTT idea won't work, what happens when multiple devices pull it high at the same time?   You do need some sort of co-ordination to prevent collisions, but apart from a central master device I can't think or how you could do it without writing a big protocol library.

I just wrote my own protocol in theory here, it should work. If it works, I'll answer my own question. Basically MODBUS, the only difference is that the client can send something without the Master requesting first. The client sends a request to talk to the line, then the master accepts it and at the same time the other Arduinos will know that they should "shut up" until the master says that the message was received. If the client requests to talk and it fail (the master don't reply accepting it), it will timeout (20-XXms) and try to request again.

It's me from the future: This won't work. One needs to be master and all the others slave, so the master can coordenate all the others.


text:
The fastest way to read out a digital pin state in an Arduino Due
What is the fastest way to read a digital pin status in an Arduino Due? Is it possible to achieve speed in the Nanosecond area?
With which type of code I can achieve this?
Edit: This question is not a duplicate please see my comment.

Yes, write to or read from the correct GPIO / PORT registers directly. Best case this needs only a few CPU cycles to read, i.e. a few nanoseconds. The processing time after that unknown, dependent on what you want to do with the read out data. Duplicate of http://arduino.stackexchange.com/questions/9117/sam3x8e-arduino-due-pin-io-registers. Also read http://forum.arduino.cc/index.php?topic=260731.0 .

Possible duplicate of SAM3X8E (Arduino Due) Pin IO registers

No it is not a duplicate. There you will find the answer how to set a digital pin as an output, but NOT how to set it as in input and read its pin state. Or atleast it is not explained detailed enough.
Also you will not find the appropiate answer to the question "the fastest" but only sadly an alternative to the digitalWrite.
You will not find any type of code example to set a pin as an input and to read from it, which actually for beginners like me would be very vital, if you would not forget that espiacially the "unnormal" register commands are very cryptic for a beginner.

ns? no. us? yeah.

The OneWire library uses it: https://github.com/PaulStoffregen/OneWire/blob/master/OneWire.h

@Jot : Where exactly? Could you please post as snippet?

@WilliamRoy all the defines and the directRead and directMode and so on functions are fast direct port writing. The OneWire.cpp show how a bitmask is stored and the DIRECT... defines are used.

@WilliamRoy Please see the GPIO library for a portable high speed Arduino library. https://github.com/mikaelpatel/Arduino-GPIO

If the pin is declared as input, let's say pin 13:
uint32_t pin_status;
pin_status = PIOB->PIO_PDSR & PIO_PDSR_P27;

If the pin is declared as output, let's say pin 13:
uint32_t pin_status;
pin_status = PIOB->PIO_ODSR & PIO_ODSR_P27;

Read the In out data register would be the fastest.


text:
Is ATmega 328 on Arduino UNO already bootloaded?
I've seen many tutorials on programming a ATmega 328 via Arduino. If i'm right, the atmega need to be bootloaded. I thought to remove the atmega present on the arduino board. But to bootloading atmega we need another atmega on the arduino board. I can't buy a new one. After bootloading we need only one IC. So, can I remove the atmega which  is present on the arduino and directly program it? Can I consider it as a bootloaded one?

The original question is not answered. User wants to know if he has bootloaded the 328chip on breadboard, then after putting this chip on UNO board will it be programmed through the normal way of programming Arduino Uno board.

Arduino controllers are usually already bootloaded with Arduino. So yeah, you can use the chip on the arduino. Or you can buy a programmer to bootloaded empty chips.

In Arduino board, arduino controller means ATMEGA328P-PU already bootloaded. So, you can use directly. But if you buy only ATMEGA328P-PU chip or any other ATMEGA chip then you have to do bootloading for that.

Arduino boards come with the bootloader already installed. You only need to flash a bootloader to it if something damaged the original one. When you buy replacement chips, you generally have a choice of "factory fresh" ones (no bootloader) or ones that already have a bootloader installed, at a small difference in price.