body:
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 [WifiMCU](http://www.wifimcu.com/)s, if You want to do it with off-the-shelf boards.


sender: user

message:
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

sender: assistant

body:
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"][1].

  [1]: https://forum.arduino.cc/index.php?topic=393653.0


message:
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?

body:
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?


body:
> 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.


body: 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.


message:
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.

body:
`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.


message:
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:

 1. A short press just restarts the micro-controller
 2. 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!

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

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/NskfD.png)

<!-- End schematic -->

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.


body: 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.


body:
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.

[![RSTDISBL ATmega328P][1]][1]

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][2]):

<!-- language: c -->

    #include <avr/wdt.h>

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

  [1]: https://i.stack.imgur.com/0PyFw.png
  [2]: http://www.atmel.com/webdoc/AVRLibcReferenceManual/group__avr__watchdog.html


message:
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

body:
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.


message:
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)
    }

body:
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](https://www.arduino.cc/en/Main/arduinoBoardMega2560) system, which has 8 KB of RAM, vs the [Arduino Nano's](https://www.arduino.cc/en/Main/ArduinoBoardNano) 2KB RAM; or can use an [Arduino Due](https://www.arduino.cc/en/Main/ArduinoBoardDue) with 96KB RAM; or a [Teensy](https://www.pjrc.com/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.]


message:
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?

body: 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.


body:
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).


message:
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][1]

**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);
      }
    }

  [1]: https://drive.google.com/open?id=0B5NnRFsbrHprNlJYYnBFcUNJQ3M

body:
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.


message:
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);

          }
      }*/
    }

body:
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:

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/eL7bj.png


body:
[SimpleTimer][1] 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.

  [1]: http://playground.arduino.cc/Code/SimpleTimer


body:
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();
      }

    }


message:
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 :)

body:
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](https://github.com/sudar/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.]


body:
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.


message:
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:

[![Graph of angular velocity and angular position][1]][1]

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.

  [1]: https://i.stack.imgur.com/DTxPa.png

body:
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.

[![Updated, bug free sketch][1]][1]
Like the previous image, I suggest zooming in.

  [1]: https://i.stack.imgur.com/MAAdu.png


message:
Line Following Robot

[![enter image description here][1]][1]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);
    }

  [1]: https://i.stack.imgur.com/7Tb0c.jpg

body:
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;
 }


message:
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](https://github.com/exmakhina/libimu/commit/27fc4e7bbfda87061ca8e1bfd4b0121ef318199b).

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 :)

body:
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](https://github.com/exmakhina/libimu/blob/c68e38c897b8604e30da9afb25a6dd070bb98458/imu_mpu9250.i#L346), 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.


message:
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.

body: 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/


message:
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.

body: 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.


body:
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][1].
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][2]

Reference:

https://stackoverflow.com/questions/33473926/best-practice-java-serial-bluetooth-connection-hc-05

  [1]: https://code.google.com/archive/p/bluecove/downloads
  [2]: http://forum.arduino.cc/index.php?topic=396450.0


message:
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.

body:
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;


body: Read the In out data register would be the fastest.


message:
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?

body: 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.


body: 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.


body: 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.


message:
Unable to read and write serial data between two arduino's (hc-05 paired) when using a sensor

What I did was that I wrote a piece of code that will-in-fact move a servo motor when a clap is detected using a sound impact sensor (fc-04).
The code for this is seen here and in fact does work:

    #include "Arduino.h"
    #include <Servo.h>
    Servo myservo;//create servo object to control a servo
    enum {
        SERIAL_BAUD        = 9600,
        SENSOR_DIGITAL_PIN =    2,
        SOUND_DELAY        =   1500, /* Delay to avoid duplicate detection */
    };

    void setup() {
        Serial.begin(SERIAL_BAUD);
        pinMode(SERIAL_BAUD, INPUT);
        myservo.attach(9);//attachs the servo on pin 9 to servo object
        myservo.write(0);//back to 0 degrees
        delay(1000);//wait for a second
    }

    void loop() {
        if (digitalRead(SENSOR_DIGITAL_PIN) == LOW) {
            static int count;

            Serial.print("Sound detected: ");
            Serial.println(++count);
            myservo.write(170);//goes to 15 degrees
            delay(3000);//wait for 3 seconds
            myservo.write(10);//back to 0 degrees
            delay(1000);//wait for a second

            // Wait a short bit to avoid multiple detection of the same sound.
            delay(SOUND_DELAY);
        }
    }

On a seperate occasion I paired two arduinos together using two hc-05 bluetooth modeules making one a slave and another a master, the initial code I used for both of them are listed here:

    //                 == SLAVE CODE ==

    #include <Servo.h>
    #define button 8

    Servo myServo;
    int state = 20;
    int buttonState = 0;

    void setup() {
      pinMode(button, INPUT);
      myServo.attach(9);
      Serial.begin(38400); // Default communication rate of the Bluetooth module
    }

    void loop() {
     if(Serial.available() > 0){ // Checks whether data is comming from the serial port
        state = Serial.read(); // Reads the data from the serial port
     }
     // Controlling the servo motor
     myServo.write(state);
     delay(10);

     // Reading the button
     buttonState = digitalRead(button);
     if (buttonState == HIGH) {
       Serial.write('1'); // Sends '1' to the master to turn on LED
     }
     else {
       Serial.write('0');
     }
    }

and

    //                == MASTER CODE ==

    #define ledPin 9

    int state = 0;
    int potValue = 0;

    void setup() {
      pinMode(ledPin, OUTPUT);
      digitalWrite(ledPin, LOW);
      Serial.begin(38400); // Default communication rate of the Bluetooth module
    }

    void loop() {
     if(Serial.available() > 0){ // Checks whether data is comming from the serial port
        state = Serial.read(); // Reads the data from the serial port
     }
     // Controlling the LED
     if (state == '1') {
      digitalWrite(ledPin, HIGH); // LED ON
      state = 0;
     }
     else if (state == '0') {
      digitalWrite(ledPin, LOW); // LED ON
      state = 0;
     }
     // Reading the potentiometer
     potValue = analogRead(A0);
     int potValueMapped = map(potValue, 0, 1023, 0, 255);
     Serial.write(potValueMapped); // Sends potValue to servo motor
     delay(10);
    }

I attempted to use the master and slave code with the one with the servo and fc-04 so that the sound sensor will be on the master and the servo on the slave so that when ever I clap it will move the servo on the other arduino.

The new master and slave code that I used are :

    //New slave
    #include "Arduino.h"
    #include <Servo.h>
    int state = 0;
    Servo myservo;

    void setup() {
      Serial.begin(38400); // Default communication rate of the Bluetooth module
      myservo.attach(9);//attachs the servo on pin 9 to servo object
      myservo.write(0);//back to 0 degrees
      delay(1000);//wait for a second
      }

    void loop() {
     if(Serial.available() > 0){ // Checks whether data is comming from the serial port
        state = Serial.read(); // Reads the data from the serial port
     }
    // Controlling the servo
     if (state == '1') {
      myservo.write(170);//goes to 15 degrees
      delay(3000);//wait for 3 seconds
      myservo.write(10);//back to 0 degrees
      delay(1000);//wait for a second
      state = 0;
     }
     else if (state == '0') {
      state = 0;
      }
    }

    //new Master
    #include "Arduino.h"
    #include <SoftwareSerial.h>
    int state = 0;
    SoftwareSerial BTserial(1, 0); // RX | TX

    void setup() {
        Serial.begin(9600);
        pinMode(9600, INPUT);
        BTserial.begin(38400);

    }

    void loop() {
        if (digitalRead(2) == LOW) {
            static int count;
            BTserial.write('1');
            delay(1500);
        }
        else {
          BTserial.write('0');
        }
    }

However the slave and master code for the servo and fc-04 is not working at all despite knowing that all the conponents work individually. What I am aware of is that the fc-04 uses serial communication to transfer data and so does the hc-05 bluetooth modules. This causes an issue because I believe from experience is that you can not have two serial communications being transmitted from the arduino at the same time which I need.
I have been at this for days and It is driving me nuts.
If I could have some help at all I will be much appreciated.

body:
> SoftwareSerial BTserial(1, 0); // RX | TX

Well, there's your problem.  You are starting `SoftwareSerial` on the `Serial` pins.  Don't do that!

For best results, hook your BT to pins 8 & 9 and use [AltSoftSerial](https://github.com/PaulStoffregen/AltSoftSerial).  It is *much* more efficient than `SoftwareSerial`, and it will not interfere with `Serial` reads and writes.

If you really can't use those pins, pick two other pins and use my [NeoSWSerial](https://github.com/SlashDevin/NeoSWSerial).  It is almost as efficient, and it works on any PinChange interrupt pins at 9600, 19200 or 38400 baud rates.


message:
Reading multiple cases on Serial

I am using a Leonardo board and am testing the APIs in the `Serial` type. The board is talking to a screen using serial.

The pseudo code is as follows (I show code relevant to Serial):

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

    void loop(void) {

        if(Serial.available())
        {

            if (Serial.find(0x30))
            {
                 func1();
            }

            if (Serial.find(0x31))
            {
                 func2();
            }

        }

     }

     void func1()
     {
          // Serial.print() used multiple times

          asm volatile ("  jmp 0");
     }

     void func2()
     {
          // Serial.print() used multiple times

          asm volatile ("  jmp 0");
     }

I test using the Arduino IDE (1.8.0) and its Serial Monitor. When I send 0x30 over serial, the first if case gets triggered to invoke `func1`, but when I send 0x31, I cannot get the second if case (`func2`) to get triggered. This even happens when I test 0x31 first; the second if case never gets triggered. Can someone tell what I am doing wrong here and what is the right way to use serial ?

**Edit** For testing, one can use the pseudo code itself; I tested using different number of LED blinks in func1 & func2, and the problem still holds.

**Edit 2** Based on Dave's answer, I tried a test with serial using sample code from

I did another test where I used the sample loop code for read (https://www.arduino.cc/en/Serial/Read) and tried typing 0 or 1 through serial monitor. I observed the following:

    // Typed 0
    I received: 48
    I received: 13
    I received: 10
    // Typed 1
    I received: 49
    I received: 13
    I received: 10

body:
It is looping faster than the serial is delivered, so each time there is a byte delivered, it tests it against 0x30 until nothing is left, and then drops out, leaving nothing .available() for the next if(), so it fails out as well and starts up the loop() again.

I'd read a byte at a time and work with that:

    int incomingByte = 0;   // for incoming serial data

    void loop(void) {

    if(Serial.available())
    {
        incomingByte=Serial.read();

        if (incomingByte == 0x30)
        {
             func1();
        }

        if (incomingBute == 0x31)
        {
             func2();
        }

    }


message:
Playing a pcm file through a speaker with arduino

I'm trying to play an audio file through a speaker with arduino.
However, I do not want to use pre-constructed libraries such as the tmrpcm library.

I was instructed to perhaps even recreate the tmrpcm library, and my process so far is that I managed to extract the data chunk from the wav file in integers, and I also managed to turn the wav file into a pcm file.

I am currently studying http://playground.arduino.cc/Code/PCMAudio this link in order to gain more insight about how I might play the pcm file with the speaker. However, I'm stuck with the general concept of the code. In fact, I'm confused with the general concept of playing the pcm file through the speaker.

In my understanding, playing a music through the speaker works by outputting series of voltages to the speaker, so that the current in accordance with the magnetic field creates an outward force onto the voice coil with a certain frequency that creates the sound.

So my question is, what does the data in the pcm file actually mean? The integers cannot be frequencies, and by graphing it I can see that they are amplitudes in a waveform, but what kind of input they are continues to elude me.

So summing up my questions,

1. What is the theoretical aspect behind the link :http://playground.arduino.cc/Code/PCMAudio

2. What does the data in a pcm file (or even a wav file) actually represent?

Thank you so much.

body:
You are right that the values in a wav file are amplitudes. 16 bit signed values to be precise.

And that amplitude is just a voltage. Negative values are normally a negative voltage, but they don't have to be. They can be just a voltage below a pre-determined mid voltage around which the wave swings (known as a DC offset).

To play the waveform you just have to generate the corresponding voltages at the right times. That is usually done using a timer so you get the frequency right. For instance a 44100Hz file has to have a sample voltage generated 44100 times per second. 44100 samples will be a sound clip lasting 1 second.

But of course the Arduino cannot generate a voltage, so instead PWM is used instead. Filtered through a low-pass filter it turns into a voltage. It also uses 50% duty cycle as "zero" for the waveform, which is scaled to fit into the resolution of the PWM.  The PWM has to be running at a considerably higher frequency than the sample frequency of the waveform so it has a chance to represent a voltage before it is asked to change again.


message:
Solid-state relay boards: Can they be used to switch audio signals?

So I tried to use one of those widely available [solid-state relay boards][1] to switch some 12V power, and I found out the hard way that they are not designed to switch DC current. They use some sort of variac that only works when AC voltage is applied. Do I have that right??

So I got this other project where I need to multiplex some audio signals in a mixer board, and I was already planning on using those solid-state relays before I learned all this. If I send audio through these relays, is it going to work as planned? Will I suffer any noticeable delay, signal degradation or attenuation?

  [1]: http://img.dxcdn.com/productimages/sku_384265_4.jpg

body:
A solid-state relay seems to be the totally wrong tool for the job. The image you posted shows it is intended to switch 240V AC. So it is designed to switch something like a 240V light on and off.

Relays in general are things designed to connect one thing to another (eg. power to a light). They just aren't designed to switch audio signals.

> I need to multiplex some audio signals in a mixer board, and I was already planning on using those solid-state relays before I learned all this

The expression "when the only tool you have is a hammer, everything looks like a nail" springs to mind.

There are chips designed to multiplex analog signals (as I describe [on this page](http://www.gammon.com.au/forum/?id=11976)). That would be closer to what you need.

However that chip (the 74HC4067) is a "choose one input from many" sort of design. It isn't going to let you fade one audio signal in or out (neither would the relay for that matter).


body:
No. SSRs are completely wrong for switching audio.

Consider using the [CD4066][1] chip. But be aware that will mean you'll need to ask a whole bunch of new questions I'm sure.

I hope this answer helps you.

  [1]: http://www.ti.com/lit/ds/symlink/cd4066b-mil.pdf


message:
What is the point of a adafruit data logger

In order to play an audio file, I was suggested to get an Adafruit data logger, yet right now I am stuck with the project and I realized that I'm not using the data logger to its full potential.

Yet I am unable to comprehend the purpose of a data logger ; all I'm using it for is to read SD Cards, and I can do that with a SD Card reader. I did read the whole documentation, data sheet, etc, and I can see that it has some cool functions, but my question is still, why data logger?

I know this  might be a stupid question, but I genuinely don't get what the data logger is supposed to be a huge help of. Please help me.

body:
Are you referring to [this](https://learn.adafruit.com/adafruit-data-logger-shield/overview)?

[![Adafruit data logger][1]][1]

That is a shield that has an SD card interface (with appropriate level-shifting for the SD card) plus a real-time clock.

The rest is "prototyping" area for you to install your own devices.

> In order to play an audio file, I was suggested to get an Adafruit data logger

I don't see how this helps play audio files, however you might read the audio file from the SD card. Then you need to send it to a DAC (digital-to-analog converter) to convert the digital information to analogue.

The Adafruit data logger is fine for recording data (for example, temperatures) but I don't see why someone would recommend it for playing audio files (apart from the SD card interface).

> my question is still, why data logger?

Better ask the person that recommended it, eh?

  [1]: https://i.stack.imgur.com/MBB2t.jpg


message:
Can an Arduino power itself off [not low power mode] via software?

I'm working on a sketch where an Arduino UNO performs no useful work after the first 10 minutes following power on.  It is not needed again until power to it is shut down, then re-enabled.  This may not happen for hours or even days.  No wake-up function is required, or deemed useful.

Of course, the Arduino could simply be left on as long as it's connected to its power source, but it will be placed remotely, and it seems [to me] safer to have it powered off. when not in use.

In essence, the Arduino is powered by a wall wart and plugged in with other devices fed by a switchable 120v power source.

I found a couple of possible hardware/software solutions to the problem but it isn't clear whether they would work in this situation.  Power consumption is not the issue here.

body:
In general, an Arduino by itself has no control over its power input.  It can, of course, enter various Sleep modes, such as the Power-down mode with watch-dog-timer off, which uses 0.1  μA.

It isn't clear from the question what will turn the Arduino back on after it is off for a while, but if you have either a push-button or a signal to turn it back on, the [Pololu 2808 Mini Pushbutton Power Switch](https://www.pololu.com/product/2808) will work as an Arduino-controlled off switch.  This board has On, Off, Ctrl, and button-contacts inputs.  If your Arduino raises the Off input, power shuts off cleanly.  To turn it back on, either connect the  button-contacts inputs together, or raise the On input, or pulse the Ctrl input.


body:
A battery-powered Arduino can go into deep sleep mode where it can use as little as 100 nA, and still be woken by a switch closure if required.

There doesn't seem to be much point to me to power down a mains-powered Arduino. What would be the purpose of that?  The small amount of current it would use via the wall-wart would be trivial. If you are worried about voltage spikes (eg. lightning) then you should protect the input pins (or your power supply) whether or not it is powered off.

It seems to me that you may as well do whatever you need to do, and then go into an infinite loop. Once the Arduino is re-powered it will do it again. You aren't saving much by attempting to power it off, indeed that introduces an extra point which might fail.

>  but it will be placed remotely, and it seems [to me] safer to have it powered off. when not in use.

Safer in what way? Any extra hardware you introduce to make the Arduino "safer" might itself introduce safety issues. It reminds me of the days when we had a UPS (Uninterruptable Power Supply). The UPS would fail more-or-less as often as the power did. In other words, you replaced one possible failure (the power failure) with another possible failure (the UPS failure).


message:
How to make two small micros communicate with my Arduino over BLE?

I want to do a project with an Arduino Uno and two other BLE (or regular bluetooth) capable modules. I want the Bluetooth modules to be hooked up to buttons (one button for each Bluetooth module). I then want the Bluetooth-capable modules to send the state of their buttons to a central Arduino board.

Is this possible? Can I have two different BLE boards connected to one Arduino?

I have a RedBear BLE (Bluetooth low energy) shield for my Arduino. What micro-controllers should I get for the peripheral modules? And where can I learn about pairing Bluetooth modules? Everything I read seems to be about pairing Bluetooth boards to a phone.

Can I do this all with BLE or am I going to need to get a new shield for my Arduino to talk with the two peripheral boards?

Thanks.

body:
You can use SoftwareSerial to communicate with two modules from an uno. But You will have to wire 'em up separately, not through your shield. (making the total number of bluetooth modules 4.

You could also use your existing sheild and poll between the two remotes. I.e. disconnecting from one and connecting to the other at a regular interval.

For the micros and bluetooth for your button, you could use a HM10 with an ATtiny like in [this instructable](http://www.instructables.com/id/How-to-Use-Bluetooth-40-HM10/?ALLSTEPS). He uses two HM10 modules to talk to each other. HM-10 is a popular BLE module. If you want regular bluetooth(2.0), you can use HC-05.


body:
The page for the [RedBear BLE shield][1] that you note indicates that the BLE chip is the nRF8001, which it says supports peripheral (slave) role only. This means it must be connected to from a BLE Central role device.

Since you want your Uno to be the central device, listening for data from these 2 remote buttons, your RedBear shield won't work this way.

A [short overview of BLE][2] is available by AdaFruit.

  [1]: http://redbearlab.com/bleshield/
  [2]: https://learn.adafruit.com/introduction-to-bluetooth-low-energy/


message:
Burning a bootloader onto my Arduino MEGA 2560 without another arduino board, or isp board

[My youtube video explains it.](https://youtu.be/Rzkvhx_ctbw) It's starting to get on my nerves.

body: You need a programmer (isp or Arduino board as programmer). It is not possible to burn a bootloader without it. The USBasp version 2 plus a 10 to 6 pin adapter cost about 2 dollars.


message:
Read all relay output (high or low) from Bluetooth through Android app

I have written the following code for Arduino:

    #define relay2 2
    #define relay3 3
    #define relay4 4
    #define relay5 5
    #define relay6 6
    #define relay7 7
    #define relay8 8
    #define relay9 9
    byte val;
    void setup() {
      Serial.begin(9600);
      pinMode(relay2, OUTPUT);
      pinMode(relay3, OUTPUT);
      pinMode(relay4, OUTPUT);
      pinMode(relay5, OUTPUT);
      pinMode(relay6, OUTPUT);
      pinMode(relay7, OUTPUT);
      pinMode(relay8, OUTPUT);
    }

    void loop() {
      int a = 0;
      if (Serial.available()) {
        val = Serial.read();
        Serial.println(int(val));
        //Display received value on Serial Monitor
        //ASCII VALUES
        if (int(val) == 49) //Turn Light1 ON 1
          digitalWrite(relay2, HIGH);
        else if (int(val) == 50) //Turn Light1 OFF 2
          digitalWrite(relay2, LOW);
        if (int(val) == 51) //Turn Light2 ON
          digitalWrite(relay3, HIGH);
        else if (int(val) == 52) //Turn Light2 OFF
          digitalWrite(relay3, LOW);
        if (int(val) == 53) //Turn Light3 ON
          digitalWrite(relay4, HIGH);
        else if (int(val) == 54) //Turn Light3 OFF
          digitalWrite(relay4, LOW);
        if (int(val) == 55) //Turn AC ON
          digitalWrite(relay5, HIGH);
        else if (int(val) == 56) //Turn AC OFF
          digitalWrite(relay5, LOW);
        if (int(val) == 57) //Lock the DOOR
          digitalWrite(relay6, HIGH);
        else if (int(val) == 48) //Unlock the DOOR
          digitalWrite(relay6, LOW);
      }
    }

Now on the Android side I have written the following code:

     //Bluetooth connection code ....
      mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);

      mmSocket.connect();
      mmOutputStream = mmSocket.getOutputStream();
      mmInputStream = mmSocket.getInputStream();

      int byteCount = mmInputStream.available();
      if (byteCount > 0) {
        byte[] rawBytes = new byte[byteCount];
        mmInputStream.read(rawBytes);
        String string = new String(rawBytes);
        Toast.makeText(this, string, Toast.LENGTH_SHORT).show();
      }

Now it works perfectly when I press a button to turn the light on/off. But I want to read all relay current status (high/low) when a Bluetooth connection is made.

So basically after connecting to the Bluetooth module I want all relay status.

How can I do that?

body:
Changing the mode of the pins would be a pain, so you might be better to store the state of the relays within you Arduino code (a bool array) as long as you know what state they start in, then send the data back over the serial connection.

Define an array of pin numbers, an array of Boolean states and rework your code to change both arrays at the same time when a number comes in.


body:
It's rather undocumented, but you can actually use `digitalRead(relay2);` on a pin (ex _relay2_) that is set to `OUTPUT`. I discovered it accidentally, and it worked exactly as expected, so i looked it up and it's legit. This is very handy to check an output pin's hi/lo state from a non-connected part of the code.

There is a tiny performance dip compared to reading just a variable, but it usually won't be noticed. If you need top performance, wrap the digitalWrite() with your own function, and set a variable with the new state:

    int myState[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

    void digitalWrite2(int pin, int value){
       myState[pin] = value; // copy setting to a global array
       digitalWrite(pin, value); // apply the setting as intended
    }

Now, you can instantly get all the relay states from the _myState_ array, provided they've been set with `digitalWrite2`. The other advantage to an array is that you can easily persist it to SPIFFs or EEPROM as-needed and recover the relay states on the next boot.


message:
What is this green board?

![enter image description here](https://i.stack.imgur.com/kTWfb.jpg)
Hi I'm new to arduino and robotics itself. I have no idea what this giant green board is in the middle of the robot. I really need help!

body: The green board is probably a custom PCB that controls the vehicle. Unfortunately, the image does not have enough quality to determine much else.


body:
It's a sheet of [FR-4](https://en.wikipedia.org/wiki/FR-4) clad in copper, with much of the copper etched off to form a PCB. That is then coated in green UV cured paint (solder resist) and components are attached.

Other things are then plugged into it.

What function it performs depends on what the designer designed it to do.


message:
Reading Json object name in arduino

How do I read the Json object name in arduino? For { "pi" : "3.14" }, I want the arduino to automatically read the object name "pi" and then th value "3.14"
I'm using arduino Uno.

body:
There is a brilliant JSON library called ArduinoJSON. It can be installed using the arduino library manager.

See https://bblanchon.github.io/ArduinoJson/doc/decoding/ for further details.

To loop through the keys, you can use:
https://bblanchon.github.io/ArduinoJson/api/jsonobject/begin_end/

or if you know the key, you can do jsonObject["pi"] to get the value


message:
Arduino receives no external UART comms after Serial.begin(9600)

I face the following issue. I connected my RasPi (3b) with an Arduino Uno via RX/TX and a logic level converter. UART comms from the RasPi to the Arduino and vice-versa work fine on minicom and serial monitor. It also works fine from my qt program to the serial monitor, but as soon as I start a Serial.begin(9600,8N1) or Serial.begin(9600) function on the Arduino there seems to be no communication anymore at all between the two. Neither the expected result (toggle an LED, works from serial monitor), nor any blinking of the tx/ex LEDs onboard anymore. Issue occurs no matter if I provide power to the Arduino via USB or the 9v powercable. Any suggestions?

body: Solved. I double crossed the rx/tx connection which made it wrong again... stupidity attacks


message:
Arduino play many piezo at once

I need to play sound on 10 piezos at once. How to do that without `delay()` function.

body:
Use the [Timer library][1].

You can attach up to 10 events to each `Timer` object you declare. That will suit your use case.

  [1]: http://playground.arduino.cc/Code/Timer


message:
Why would uninitialized SD-card module without card disable CAN-Bus shield?

(I am able to successfully initialize CAN-Bus shield and SD-card module w/ card in it.)

Now I have removed all code related to the SD-card module, yet I left the module (without the card in it) physically connected. **This results in the CAN-Bus shield initialization failing.**
When I insert the card into the SD-card module the CAN-Bus shield initializes successfully. (I am still not doing SD-card module initialization.)

Of course, I can just disconnect the SD-card module or leave the card in it... But I am trying to understand this black magic.

I have connected the SD-card module CS to pin 8, the CAN-Bus shield clone CS is connected to pin 10. I tried to set the SD-card module CS pin to OUTPUT and to HIGH. That had no effect.

the CAN-Bus shield + schematics: http://www.elecfreaks.com/estore/can-bus-shield.html [Resource -> Schematics]
the SD-card module: https://ebay.com/itm/161366316226?_trksid=p2057872.m2749.l2649

body:
Without seeing schematics this is purely supposition:

My guess is that the SD shield contains bi-directional level shifting. The MISO pin, which connects the DO pin of the SD card to the MCU, will have a 3.3V -> 5V level translator on it.  This, with no SD card inserted, will be floating (flapping around in the breeze) causing the output of the level translator to randomly produce digital signals on the MISO pin. These signals interfere with the MISO signals from your CAN shield.

How best to cure the problem very much depends on what level shifting is in the circuit and how it is controlled and wired. For that we will need to see schematics of both the CAN and SD card shields.


message:
Arduino + motor driver (L293D) power consumption

Please help me on [this][1] question.

Original question :
My chip consists of 1 arduino nano and  3 [L293D][2] motor driver. This chip is for controlling motors and other equipments. My question is about how to calculate power consumption of my chip. I searched for about voltage settings of arduiono nano and L293D motor driver, but there are many phusical thinks that i cannot understand. How many hours 2000 mah battery enough for.

Note :
Motors and other equipments will have own power supply. That i say it is just for [Arduino Nano][3], Bluetoot adapter for arduino (HC-05) and 3 motor driver (L293D).

  [1]: https://arduino.stackexchange.com/questions/35445/arduino-motor-driver-l293d-power-consumption
  [2]: http://www.ti.com/lit/ds/symlink/l293.pdf
  [3]: https://www.arduino.cc/en/Main/arduinoBoardNano

body:
To calculate L293D power usage, you need to lookup the datasheet and check the Voh and Vol. These are the High level voltage and Low level voltage.

On Texas Instruments datasheet, we have:
[![enter image description here][1]][1]

So you will lose about 1.4V when your output is -0.6A, and 1.2V when your output is 0.6A. If your motor uses 2 outputs (bi-directional) then you have to add the losses.

Then, to get the power dissipated on the power side of the L293D, you take this voltage drop and multiply by the motor´s current.

**Example:**
Lets say your motor is using 0.6Amps and your power source is 5V + 24V @ 25°C (just like in the datasheet).

The power loss in the L293D is aprox.: (1.4V + 1.2V) x 0.6A = 1,56W.
Since you´ve lost 2.6V in the L293D, your motor will use: (24V - 2.6V) x 0.6A = 12,84W.

To measure this directly on your real circuit, use a multimeter in Ampere mode to measure current, and Volt mode to measure the voltage on the motor terminals when it is on.

As for the arduino, your battery has 2000mAh and I assume it is a 7,4V battery. So it has 2000mAh x 7,4V = 14800mWh of energy stored in it.

If you are running your arduino at 5V, then: 14800mWh / 5V = 2960mAh at 5V.
Now let´s say your arduino and it´s modules, the L293D´s and the motors are using 500mA average, then your battery will last: 2960mAh / 500mA = 5.92 hours in theory.
Why "in theory"? because in real life it is impossible to extract all the energy from inside a battery. A minimum ammount of energy has to remain inside it and some power is lost when you extract it´s energy.

Of course, this is a very raw calculation. In reality, you have to calculate power used in every component. But by calculating the "big guns" first you can get an idea of where you stand.

Basic power loss calculation is done by multiplying voltage drop by the current in each circuit. Voltage drop is the difference between your volts before and after the component.

  [1]: https://i.stack.imgur.com/6eAYh.jpg


message:
Help with struct variable

I made a struct like this:

    typedef struct {
      int color[3];
      int positions[4];
      char init[20];
      void (*fn)();
    } buttons;

and a variable like this:

    button test[1] =
    {
      {{0,0,0},{0,0,100,100},"getSomething",setSomething}
    }

In loop() I call test[i].color, test[i].position normally.

Problems start when I want to execute a function.

I made two attemps, one with string and one with a function statement. With the string I have no problems using a strcmp() but it's not what I want.

I need to know how I can store 2 different functions in the struct and how I can execute.

Thanks in advance!

body:
The typedef is no longer needed, using the 'struct' with a name declares the type.

    // Arduino Uno

    struct buttons
    {
      int color[3];
      int positions[4];
      char init[20];
      void (*fn)();
    };

    // Declare the functions here, or use prototyping
    void func1();
    void func2();

    buttons test[] =
    {
      { {0,0,0},    {0,0,100,100}, "getSomething",  func1 },
      { {40,40,40}, {50,50,10,10}, "somethingElse", func2 },
    };

    void setup()
    {
      Serial.begin(9600);
      Serial.println("Calling the functions:");

      test[0].fn();
      test[1].fn();
    }

    void loop()
    {
    }

    void func1()
    {
      Serial.println("func1");
    }

    void func2()
    {
      Serial.println("func2");
    }


message:
Is it possible to digitally stop a moving motorbike using an Arduino module?

I am working on a bike protection project that is supposed to be part of my CS syllabus. Although I got most of the things worked out, there is one thing that bugs me; that is to how to stop a moving bike using an Arduino built into the bike, possibly from a remote system, like another Arduino or Android app.

Is it possible to do it using an Arduino and some other modules maybe?

body:
Assuming that you simply want to stop the engine, Gerben's comment has the answer: Put a relay in series with the ignition. Control the relay with the Arduino.

Opening the relay breaks the circuit. Ignition is now off, and the engine will no longer run.

Of course, the bike can still roll without engine power. If you want to completely immobilize the bike, you need to engage the brakes, or lock the wheels in some other way. And that takes a whole lot more hardware.


message:
3 buttons digital inputs

I have 3 digital button inputs, I want to do a continuous scan of 3 of them until a button is pressed and to know which button has been pressed. Please help, I'm new to programming and arduino.
Thanks

body:
Try out this code. You can see result on Serial Monitor. I hope it will help you.

    const int kPinBtn1 = 2;  // Button 1
    const int kPinBtn2 = 3;  // Button 2
    const int kPinBtn3 = 4;  // Button 3

    void setup()
    {
      pinMode(kPinBtn1, INPUT); // Button 1 as Input
      pinMode(kPinBtn2, INPUT); // Button 2 as Input
      pinMode(kPinBtn3, INPUT); // Button 3 as Input

      digitalWrite(kPinBtn1, HIGH); // Pullup
      digitalWrite(kPinBtn2, HIGH); // Pullup
      digitalWrite(kPinBtn3, HIGH); // Pullup

      Serial.begin(9600);
    }

    void loop()
    {
      if(digitalRead(kPinBtn1) == LOW)      // If button 1 pressed
      {
        Serial.println("Button 1 pressed"); // Print "Button 1 pressed" on Serial Monitor
      }

      if(digitalRead(kPinBtn2) == LOW)      // If button 2 pressed
      {
        Serial.println("Button 2 pressed"); // Print "Button 2 pressed" on Serial Monitor
      }

      if(digitalRead(kPinBtn3) == LOW)      // If button 3 pressed
      {
        Serial.println("Button 3 pressed"); // Print "Button 3 pressed" on Serial Monitor
      }
    }


message:
Input-Output Circuit Issue

I have design a circuit with 2 led (red and UV) and 2 button.So, the circuit supposed to work like this:
If i press the button for red led, the red led lights up and the uv led turn off, and if i press the button for uv led the uv led lights up and the red led turn off.

[![This what happen when i press the red button][2]][2]
[![The Schematic][3]][3]

But the circuit is not work like that, when i upload the code, the uv led suddenly turn on without touching the button.The red led had no issue.The red led turn on when the button is push.And turn off when the button is unpress.But when i push the red button, the uv led does not turn off.It stay glow.The uv led turn on whatever i push the button or not.

Here is the code :

    int red = 8;
    int uv = 9;
    int redbutton = 2;
    int uvbutton = 3;
    int redbutcondition = 0;
    int uvbutcondition = 0;

    void setup()
    {
      pinMode (red, OUTPUT);
      pinMode (uv, OUTPUT);
      pinMode (redbutton, INPUT);
      pinMode (uvbutton, INPUT);
    }

    void loop()
    {
      redbutcondition = digitalRead(redbutton);
      uvbutcondition = digitalRead(uvbutton);

      if (redbutcondition == HIGH)
      {
        digitalWrite(red, HIGH);
        digitalWrite(uv, LOW);
      }
      else if(uvbutcondition == HIGH);
      {
        digitalWrite(uv, HIGH);
        digitalWrite(red, LOW);
      }
    }

  [2]: https://i.stack.imgur.com/2hQlm.jpg
  [3]: https://i.stack.imgur.com/jzwO0.jpg

body:
Try out this schematic. It will work.

[![Setup][1]][1]

So code will be :

    int red = 8;
    int uv = 9;
    int redbutton = 2;
    int uvbutton = 3;
    int redbutcondition = 0;
    int uvbutcondition = 0;

    void setup()
    {
      pinMode (red, OUTPUT);
      pinMode (uv, OUTPUT);
      pinMode (redbutton, INPUT_PULLUP);
      pinMode (uvbutton, INPUT_PULLUP);
    }

    void loop()
    {
      redbutcondition = digitalRead(redbutton);
      uvbutcondition = digitalRead(uvbutton);

      if (redbutcondition == LOW)
      {
        digitalWrite(red, HIGH);
        digitalWrite(uv, LOW);
      }
      else if(uvbutcondition == LOW)
      {
        digitalWrite(uv, HIGH);
        digitalWrite(red, LOW);
      }
    }
  [1]: https://i.stack.imgur.com/TGLdc.png


message:
PulseIn tachometer

I tried to create a tachometer for my motorcycle using an Arduino Uno.
I am trying to measure the voltage of the ignition coil (stepped down to not destroy the Arduino).

I am trying to determine the time between two explosions (one ignition coil high voltage).

I tried to use the `pulseIn` command in the following way:

<!-- language: c++ -->

    unsigned pin=8;
    float t;

    unsigned long rpm;

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

    void loop() {

        rpm=pulseIn(pin,LOW);

        Serial.println(rpm/60);
    }

The problem with it is that it won't display stable values. It will go all crazy.
With an open circuit it still displays random values.

body:
I can't tell you why that isn't working, but I can give you a working alternative.

    unsigned int pin=8;

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

    void loop() {
        unsigned float rpm = 0;

        while (digitalRead(pin) == FALSE) {
            rpm++;
            delayMicroseconds(1);
        }

        Serial.println(rpm/60);
    }
I might've forgotten something, but that should work.

Edit: the comments may be right, are you stepping down your input voltage?


body: No one mentioned that there is back EMF from primary coil when switch (or points) becomes open. This means that there is 200-300V applied backwards to your voltage divider while you think there is only 0-12V.


message:
Correct connections: 7-segment, 4-digit display with common anode

I see this connections for 4-digit display.
[![enter image description here][1]][1]

All used pins set up on output. But, really, is it correct connections?

Why it used A* input pins, and, digital pins set up on output, it is right?

Maybe all pins need used by digital pins with NPN transistors? Collector is 5V, Base - Arduino digital pin, emitter - resistor with display anode, next, collector is display segment pin,  Base - Arduino digital pin, emitter - Ground.

What resistance is needed for the resistor? I think, more than 220 Ohm?

Sorry, but I'm really a beginner in electronics.

  [1]: https://i.stack.imgur.com/vj7DC.png

body:
That circuit looks OK to me.  It will allow you to light (reliably) a single segment at a time.  The A* pins will be used in digital output mode.

The A* pins are connected to the four anodes of the digits - each digit has common anodes for all the segments.  They should be driven HIGH to 'select' a digit.

The D* pints are connected to the cathodes of each segment.  They should be driven LOW to light that segment.

For example, to light the 'A' segment of the first digit, you would set:

* A1 HIGH, to drive the anode of the first segment
* A2, A3, A3 LOW, so that the other three segments are not driven
* D5 LOW, so that current flows from A1 to D5, lighting the digit
* D6-D12 HIGH so that no current flows from A1 through any of the other segments.

The expectation is that you will cycle around (very fast), lighting each required segment on each required digit in turn.

Without a (proper) data sheet we can't tell you what the correct resistor value is, but the 220R shown is probably OK.


message:
Is there a way to setup an interrupt to trigger at n number of clock cycles from now?

I currently have an nRF transmitter/receiver pair setup on my desk. The transmitter is sending a single byte (0xAA) every 5ms. The receiver sets an LED high to indicate that it received the byte, which is about 10us (+/-2) after the byte was sent. I want to use this nRF pulse for a precise timing/sync application with +/-0.5us accuracy so I need to filter these receiver pulses such that I can estimate the time the transmitter actually sent the byte and the time the next one *should* arrive. I created an algorithm that uses past nRF pulse times (measured in clock cycles using Teensy's ARM_DWT_CYCCNT register) to estimate the next pulse and it seems to be working reasonably well - though I can't say yet if I'll get the 0.5us accuracy I want.

Now I want to take that estimate and have my microcontroller set an output pin high as soon as the clock count reaches the estimated clock value. Currently I do this by waiting in a while loop and polling the register, but the loop itself takes up several hundred clock cycles which reduces my accuracy. Is there a way to instead have an interrupt trigger when the clock cycle counter reaches my estimated value? I would somehow need to set this interrupt after computing each estimate.

Thanks!

body:
1. Use a timer to count the system clock and preload the counter with an offset that overflows in the desired cycles.

2. Use a timer to count the system clock and set a compare match a desired number of cycles out.

To expand the number of cycles, you can do fancier processing in thee Isr but the basic gist IS the same.

Other approaches also exist but the two outlined here are easier.