body:
I need help on a project. I just started to experiment with arduino 2 weeks ago and I am building a lamp that react to movement and interactions.
So the idea is; when there is nobody in the room, the light stay white.
And when there is someone, it turns orange and I want it to « breathe » (fade function).

I am using a LDR sensor to make it happen and so far my code looks like:

    int LDRvalue = 1;
    int RedLED = 9;
    int GreenLED=10;
    int BlueLED=11;
    int pinLDR = A0;

    void setup()
    {
    pinMode(RedLED, OUTPUT);
    pinMode(GreenLED, OUTPUT);
    pinMode(BlueLED, OUTPUT);
    Serial.begin(9600);

    }
    void loop()
    {
    LDRvalue = analogRead(pinLDR);
    Serial.print("valeur ldr: ");
    Serial.println(LDRvalue);

    int colour = map(LDRvalue, 0, 1023, 0, 255);
    Serial.print("valeur mappe: ");
    Serial.println(colour);

    if(LDRvalue >= 1023)
    {
    analogWrite(RedLED, 255);
    analogWrite(GreenLED, 255);
    analogWrite(BlueLED, 255);
    delay(1000);
    }

    else if((LDRvalue >= 800) & (LDRvalue < 1023))
    {
    analogWrite(RedLED, 255);
    analogWrite(GreenLED, 255);
    analogWrite(BlueLED, 255);
    delay(1000);

    }

    else if((LDRvalue >= 600) & (LDRvalue < 800))
    {
    analogWrite(RedLED, 255);
    analogWrite(GreenLED, 105);
    analogWrite(BlueLED, 0);
    delay(1000);

    }
    else if((LDRvalue >= 300) & (LDRvalue < 600))
    {
    analogWrite(RedLED, 255);
    analogWrite(GreenLED, 35);
    analogWrite(BlueLED, 0);
    delay(1000);
    }

    else if((LDRvalue >= 150) & (LDRvalue < 300))
    {
    analogWrite(RedLED, 255);
    analogWrite(GreenLED, 15);
    analogWrite(BlueLED, 0);
    delay(1000);

    }

    else if((LDRvalue >= 0) & (LDRvalue < 150))
    {
    analogWrite(RedLED, 255);
    analogWrite(GreenLED, 0);
    analogWrite(BlueLED, 0);
    delay(1000);
    }

    delay(1);

    }
    void color(int red, int green, int blue)

    {
    analogWrite(RedLED, red);
    analogWrite(GreenLED, green);
    analogWrite(BlueLED, blue);
    }

The code is working for the light changes depending on the human presence.
But I don’t know how to make it fade and breathe when it turns orange.

Could you help me to make it happen ?

title: LED fade with LDR sensor depending on the light

Answers: 1

body:
While some parts of your code don't make much sense to me, the breathing led code is easily searchable on the internet, with one of the first results being:

    #include <math.h>
    #define ledPin 11
    int i=0;
    int breathe_delay = 15;   // delay between loops
    unsigned long breathe_time = millis();
    void setup() { }
    void loop() {
      nonBlockingBreath();  // call the nonblocking function
      // yourOtherCodeHere();
    }

    void nonBlockingBreath() {
      if( (breathe_time + breathe_delay) < millis() ){
        breathe_time = millis();
        float val = (exp(sin(i/2000.0*PI*10)) - 0.36787944)*108.0;
        // this is the math function recreating the effect
        analogWrite(ledPin, val);  // PWM
        i=i+1;
      }
    }

As you can see the code above works for monochromatic LEDs only, so my advise is to combine the code above with a conversion from HSL to RGB, like [RGBConverter][1] library, specifically the `hsvToRgb` function.

This way your version of the `nonBlockingBreath` function will become:

    byte[3] rgb;
    void nonBlockingBreath() {
      if( (breathe_time + breathe_delay) < millis() ){
        breathe_time = millis();
        float value= (exp(sin(i/2000.0*PI*10)) - 0.36787944)*108.0;
        hsvToRgb(hue, saturation, value, rgb);
        analogWrite(RedLED, rgb[0]);  // PWM
        analogWrite(GreenLED, rgb[1]);  // PWM
        analogWrite(BlueLED, rgb[2]);  // PWM
        i=i+1;
      }
    }

Obviously you will have to set the `hue` and `saturation` variables accordingly to the tonality of orange you wish to *breath*.

  [1]: https://github.com/ratkins/RGBConverter


body:
**What is the maximum number of serial ports (com) can Arduino IDE detect ?**

I need to connect 6 Arduino UNO Wi-fi at a time to make a small network and I use a 7 port USB hub for the same. The device manager shows 6 com ports detected but Arduino shows only 4 serial ports detected. Is there a limitation on the serial ports interfaced with the Arduino IDE ?

title: Arduino IDE - Maximum serial COM ports

Answers: 2

body:
According to the [last version of code for Arduino IDE][1], there are no limits of discovered Serial or Network devices since they are stored in a list (not limited as an array).

To discard problems, try with another operating system.

  [1]: https://github.com/arduino/Arduino/tree/master/arduino-core/src/cc/arduino/packages/discoverers

body: Thanks for your comments. I found the solution. Inside the **My computer -> Properties -> Device manager** under ports I found that *multiple Arduino's where assigned same COM values*. Therefore, just go to properties of the COM and change them to COM values that are not used


body:
I've written 6 C++ classes on the CLion IDE to be used on Arduino. One of these classes uses a C++ library called "Adafruit_PWMServoDriver.cpp" provided by Adafruit to use the PWM driver they sell. I'm trying to test my code in a main.cpp, but upon building my code, I noticed that "Adafruit_PWMServoDriver.cpp" has the following code:

    #if ARDUINO >= 100
     #include "Arduino.h"
    #else
     #include "WProgram.h"
    #endif

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

    #if ARDUINO >= 100
     #include "Arduino.h"
    #else
     #include "Arduino.h"
    #endif

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

title: Creating a library of C++ classes for Arduino; How to #include "Arduino.h", "WProgram.h"?

Answers: 2

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

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

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

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

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

---

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

body:
The `#if defined (AVR_<various_names>)` you see here have nothing to do
with Arduino: this is the avr-libc trying to import the IO register
definitions for the AVR chip you are using. Whenever you compile an AVR
program, you pass the option `-mmcu=<mcu-name>` to avr-gcc, and it
automatically defines the proper macro. For example, the Arduino Uno is
built around an ATmega328P. Programs for the Uno must then be compiled
with `-mmcu=atmega328p`, which makes the compiler define
`__AVR_ATmega328P__`, which directs the avr-libc to
`#include <avr/iom328p.h>`, which contains all the IO register
definitions for that chip.

As for the `ARDUINO` macro, this one is defined by the Arduino IDE to be
the version of you Arduino installation, without the dots. For example,
if you downloaded the core files from Arduino 1.8.2, then you should
compile with `-DARDUINO=182`.

Also, you should avoid copying all the library headers to your project,
and instead use the proper `-I` options. And don't forget to tell the
compiler your clock frequency with `-DF_CPU=...`, as it is needed by
some avr-libc and Arduino stuff.

In the end, you will see you need quite a lot of compiler options to
properly compile Arduino code. The easiest way to do it is definitely to
use the Arduino IDE, as it handles all this for you. If you don't like
the IDE (understandable...), you could try [Arduino
Builder](https://github.com/arduino/arduino-builder), which should be
entirely compatible. If you want to compile from just a Makefile, I
recommend you take a look at [Sudar Muthu’s Arduino
Makefile](https://github.com/sudar/Arduino-Makefile).


body:
I want to build up my automatic water pump with an arduino pro mini 5v and a 5v usb water pump (2.3 W). As I understand, I cannot power the pump directly through the vcc pins of the board, right?
Would it be possible to place a female USB Port in my system to power the board and the pump through a relay on the board? What would be an appropriate circuit diagram?

title: Run 5V/2.3W water pump on Arduino Pro Mini 5V

Answers: 2

body:
Hi Florian you can take power from USB fro both Arduino and the water pump.This is the schematic you have asked for your project. An arduino Pin can give maximum 20mA current that's why we need a limit resister to limit the current below 20mA and also this current should be such a way that it can drive the switching transistor. So the challenging thing is choosing the correct resister
I have taken the value 1K
So the current at Arduino Digital pin is Current I = 5V/1k = 5mA which is below of 20mA and sufficient to drive the Transistor. you can use BC548 transistor also.

<!-- 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/MVQLl.png)

<!-- End schematic -->

body:
> As I understand, I cannot power the pump directly through the vcc pins
> of the board, right?

This is from the [Arduino Pro Mini schematic][1]:

[![Pro-mini regulator][2]][2]

Note that the maximum current output is 150 mA. On the other hand, your pump needs 2.3 W / 5 V = 460 mA > 150 mA. So your understanding is right: **you can't power the pump directly through the Vcc pins of the board**.

> Would it be possible to place a female USB Port in my system to power
> the board and the pump through a relais on the board? What would be a
> appropriate circuit diagram.

There are lots of extremely cheap, commercially available, opto-isolated 5V relays modules in aliexpress and the like.

I'd recommend one [like this][3] because it allows you to have separate supplies for the relay coil and for the input diode in the opto. That will help you to avoid problems related to having "different" 5V levels due to dropout in the Pro Mini regulator.

Module picture:

[![5V relay module][4]][4]

Module schematic:

[![5V relay module schematic][5]][5]

Module connectivity:

 - VCC --> VCC from the Pro Mini.

 - JD-VCC --> V+ from the power supply (same as RAW input to the Pro Mini).

 - COMMON --> V+ from the power supply.

 - NO (normally open) --> connect it to the 5V rail of the USB pump.

 - NC (normally closed) --> leave it unconnected.

 - Be sure to connect all grounds together.

 - I'd also recommend adding an additional decoupling capacitor close to the RAW pin of the Pro Mini, to protect the regulator from voltage spikes caused by switching-off inductive loads like the relay coil and the pump motor.

**NOTE:** take into account that the relay module can draw up to an additional 80-100 mA of current. Take that into account in your power/current budget.

  [1]: https://www.arduino.cc/en/uploads/Main/Arduino-Pro-Mini-schematic.pdf
  [2]: https://i.stack.imgur.com/RnwKqm.png
  [3]: https://www.aliexpress.com/item/1PCS-1-Channel-Isolated-5V-Relay-Module-Coupling-For-Arduino-PIC-AVR-DSP-ARM/864904832.html
  [4]: https://i.stack.imgur.com/Zm6kQm.jpg
  [5]: https://i.stack.imgur.com/peU1A.jpg


body:
I had the 12V DC power jack plugged-in all the time, and "to make things more exciting" I also plugged-in the "data" USB whenever I had a new sketch to upload. Is this combination a big no-no, or is my step-up converter to blame?

I am completely new to this stuff but now when thinking of it those 12V from the power jack + 5V from the "data" USB probably violate this clause:
_If using more than 12V, the voltage regulator may overheat and damage the board._

title: I fried the AMS1117 voltage regulator on my Arduino Clone, is this the cause?

Answers: 2

body:
The "problem" with the AMS1117 voltage regulator is the amount of current they can safely provide drops as the input voltage rises. I'm a Arduino noob, so I looked at the data sheet for the AMS1117 series of voltage regulators. There is a formula: PD=(VIN-VOUT)(IOUT) and Note 2: which says the maximum power dissipation for the SOT-223 package is 1.2 W.

The best case scenario is to use an input voltage of 6.5 volts. (6.5-5)(0.8)=1.2W. This gives you 0.8 amps maximum output. If you use a 12 volt power supply: (12-5)(0.1714)=1.2W. This only gives you 0.1714 amps maximum output.

I'm not sure what kind of power jack you are using, so I'll give you an example of one that I used in a project. It says input 120VAC, output 12VDC, 200ma. The problem is, it actually puts out 20VDC open circuit with no load.

The data sheet gives a maximum input voltage of 15 volts but that would only provide a maximum of 120 mA output.

body:
Probably not. There is nothing fundamentally wrong with what you're doing - it's within the design parameters. In particular:

* 12V is within the 7-12V recommended range specified for that input. Yes, it means the regulator will get hotter, but the AMS1117 is supposed to be current limited and thermally limited so should just start shutting down if it supplies too much current or gets too hot. As [this answer](https://arduino.stackexchange.com/a/43894/56855) suggests, it would be wise to limit it to 1.2W, which is 171mA. That's plenty for the Arduino itself, so you'd only be running into trouble if you have other peripherals to power.
* The Arduino Uno has circuitry specifically designed to disconnect the USB's 5V rail if the external power supply is present. This is really only to protect the USB supply from being damaged by the external power supply - the Arduino doesn't care as long as it is getting 5V from somewhere. The USB data function is independent of whether the 5V comes from the USB's 5V rail or the 5V generated from the external supply you provide. The AMS1117 itself, according to its (various) datasheet, has no design susceptibility to an alternate 5V supply being on the output.

Finally, there's an alternate reason for the failure. We've also been using an Arduino Uno clone with the AMS1117, and have also been supplying 5V external (directly to the 5V rail in our case) as well as connecting to USB for programming. We've also had an AMS1117 fail, despite operating everything within normal limits. Our symptoms are that the OUT pin is shorted to the GND pin. Removing the regulator restores full functionality.

Based on various reports around the Internet of suspect behaviour and doubtful provenance of these chips on the clone boards, I would suggest that a faulty IC might be the root cause.


body:
I am doing an experiment. In this experiment I want to start the RTC by presing the external Push Button which is connected with Aquino's pin 2 and take varites of action according to Time. For interrupt I have made a ISR and in this interrupt I wrote my main logic. But this things is not working.
The schematics is[![Schematic Diagram][1]][1]

  [1]: https://i.stack.imgur.com/7FRtZ.jpg
and The code is

    `include <Wire.h>
    #include "RTClib.h"
    #include <LiquidCrystal.h>

    // initialize the library with the numbers of the interface pins
    LiquidCrystal lcd(12, 11, 5, 4, 3, 9);

    RTC_DS1307 rtc;
    int k = 0;
    int led =13;
    int pin =2;

    char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

    void setup () {
     lcd.begin(16, 2);
     rtc.begin();
     Serial.begin(11520);
     pinMode(led,OUTPUT);
     pinMode(pin,INPUT);
     attachInterrupt(0, Time  , LOW);
      // Print a message to the LCD.
      if (! rtc.begin()) {
        lcd.print("hello, world!");
        while (1);
    }

      if (! rtc.isrunning()) {
        Serial.println("RTC is NOT running!");
      }
    }
    void loop()
    {}

    void Time()
       {
        {DateTime now = rtc.now();
        lcd.setCursor(0, 0);
        lcd.print(now.year(), DEC);
        lcd.print("/");
        lcd.print(now.month(), DEC);
        lcd.print("/");
        lcd.print(now.day(), DEC);
        lcd.print(" ");
        lcd.print(daysOfTheWeek[now.dayOfTheWeek()]);
        int c = now.second();
        lcd.setCursor(0, 1);
        lcd.print(c);
        if(c==58)
          {
            k=k+1;
            lcd.setCursor(5, 1);
            lcd.print(k);
            if(k==4)
              {
                digitalWrite(led,HIGH);
                k=0;
              }
         }

        }}`

please help me.

title: Problem on Arduino Interrupt and RTC

Answers: 1

body:
Well, for example Arduino's `delay` needs interrupts to be working and as you may not know it's disabled inside of `ISR` handler.

Never ever use anything like `while (1)`, `delay(1000)` and so on inside of `ISR`! And also do not reenable interrupts either! Set a simple `volatile` flag and use it inside of `loop` function instead.

Basically something like this:
<!-- language: c++ -->

    constexpr int8_t button = 2;
    volatile bool      flag = false;

    void setFlag() {
      flag = true;
    }

    void setup() {
      pinMode(button, INPUT_PULLUP);
      attachInterrupt(digitalPinToInterrupt(button), &setFlag, FALLING);
    }

    void loop() {
      if (flag) {
        // it's running, you can do something here

        // and you can reset the flag here either
      }
      //delay(100); // if needed
    }


body:
After digging around on a [separate problem][1], I found that `avrdude`, `avr-gcc` and some more tools can be found in two different locations:

    (1): C:\Program Files\Arduino\hardware

    (2): C:\Users\<user>\AppData\Local\Arduino15\packages\arduino

These two folders also both contain similar copies of the `hardware` directory where all the bootloader hex-files and source code is stored:

    (3): C:\Program Files\Arduino\hardware\arduino\avr

    (4): C:\Users\<user>\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.6.17

I say similar because the `bootloaders\caterina` folder in (4) contains quite a few hex-files that are missing in (3).

When burning a bootloader, looking at verbose output from the Arduino IDE reveals that hex-file and executable of avrdude from (2) are used, not (1).

What is the reason for this? My guess would be that location (1) is deprecated, but why choose to put stuff like this into Appdata in the first place?

  [1]: https://arduino.stackexchange.com/questions/36071/how-does-avrdude-burn-a-bootloader-much-quicker-than-the-arduino-ide

title: Why are there two sets of tools and bootloaders in the Arduino IDE?

Answers: 1

body:
Arduino IDE comes with a "platform" (the arduino AVR) in the Arduino\hardware folder.
Then you can add/upgrade platforms with the boards manager.
These will be installed in C:\Users\<user>\AppData\Local\Arduino15\packages.
The reason for this is that Arduino IDE wants to be able to "work out of the box".
If they did not deliver the platform inside the installation/zip a "installation finishing" job needs to run after opening the Arduino IDE.


body:
I'm using Arduino Uno "Wifi Developer Edition". I made my Arduino to get connected with my local network based on [http://www.arduino.org/learning/getting-started/getting-started-with-arduino-uno-wifi][1]

Now I would like to disable it and work with USB serial communication to upload sketches. But now I'm unable to upload sketches even if I select the serial port. I'm getting an AVRDUDE : seropen() Access is disabled error. I could perfectly do uploading if I select the networked port of the same Arduino.

Can I know why ?

  [1]: http://www.arduino.org/learning/getting-started/getting-started-with-arduino-uno-wifi

title: Arduino Uno "WiFi Developer Edition" - How to disable WiFi?

Answers: 2

body:
The reason why "Arduino WiFi Dev Ed" USB upload sometimes doesn't work, is the esp8266 connected to UART of Atmega for the OTA upload. If esp8266 doesn't boot, it doesn't set pin 4 to disconnect from Atmega UART and the connection to UART stays and disturbs the upload from IDE.

The esp8266 hangs sometimes, because it has pin 2 floating on this board, but there is a trace and a soldering point on the bottom of the board for pin 2. If it is touched or otherwise grounded the esp8266 doesn't boot until the potential on the pin rises.

More about Uno WiFi Dev Ed hardware [here][1].

  [1]: https://github.com/jandrassy/UnoWiFiDevEdSerial1/wiki/Hardware

body:
You don't need to disable the Wi-Fi. The serial works with the Wi-Fi enabled.
You need to first install the driver and then select the Serial port on the Arduino IDE.


body:
On a 2560 MEGA I use serial(0) and serial1.

Serial1 is connected to an AT-328P   (not an UNO but a single AT controller)

The 2560 use Interrupt (serialevent) and Serial1Event.
Serial(0) is connected to the PC(USB) and is used to get commands that are planned to control both microcontrollers. And RX1 /TX1 (Serial1Event) is connected to the AT-328P .

I plan to use single letter Commands (eg. 'A' , 'B' .... 'Z') followed by a
delimiter (space or comma) again followed by 1 to 4 hexadecimals arguments.

EG:  "A 00,FFFF,AA,00"  or  "B,00,FFFF,33,00"  or "C 00,FF,FFFF,11"  or
"D 01,0000,FFFF,01" or "E,00,0910,1"

Valid delimiters are space, comma and Carriage Return

First argument is the number of the controller (00 = 2560 / 01 = AT328P, second to 4'th is the actual command to the controller.

The problem is parsing the command line from the PC. The one I use is far to slow (I scan the inputBuffer char by char and take my desiscion from that) - much to slow.

Now I want to parse the inputBuffer BEFORE I check the command letter (saving time and get the param's before I go into the specific subroutine) but here I  am i trouble.  I dont' know how to convert the 4 (2) Ascii chars into a valid HEX (or INT) -value.

I have seen some code somewhere ( and naturally forgotten where) doing it, but the methods I have used till now is oldfashioned and (far) out of date, and I am not very good to C++ (but I wanna learn it), so  I will be ashamed showing it.

Can any one give me an idea how to proceed .

Thanks

Kris AKA Snestrup2016

title: Read one(2) hex-adresses from a string

Answers: 0


body:
I need faster communication between the ESP and the ADC, so I found this
https://github.com/pasko-zh/brzo_i2c.

**Original wire Example**

    #include "Wire.h"
    #define PCF8591 0x48
    byte a0;

    void setup() {
      Wire.begin(13, 14);
      Serial.begin(115200);
    }

    void loop() {
      Wire.beginTransmission(PCF8591);
      Wire.write(0x04);
      Wire.endTransmission();
      Wire.requestFrom(PCF8591, 5);

      a0 = Wire.read();
      a0 = Wire.read();

      Serial.println(a0);
      delay(1000);
    }

**Brzo I2C example**

    #include "brzo_i2c.h"

    uint8_t buffer[10];
    uint8_t error = 0;
    float temp = 0.0;

    uint8_t ICACHE_RAM_ATTR get_temp(float *t) {
      uint8_t bcode = 0;
      brzo_i2c_start_transaction(0x48, 400);
      buffer[0] = 0x04;
      brzo_i2c_write(buffer, 1, false);
      brzo_i2c_read(buffer, 2, false);
      bcode = brzo_i2c_end_transaction();
      *t = ((buffer[0] << 8) | buffer[1]);
      return bcode;
    }

    void setup() {
      delay(500);
      Serial.begin(115200);
      brzo_i2c_setup(13, 14, 2000);
    }

    void loop() {
      error = get_temp(&temp);
      if (error == 0) {
        Serial.print("Temp = ");
        Serial.println(temp, 8);
      } else {
        Serial.print("Brzo error : ");
        Serial.println(error);
      }
      delay(500);
    }

But I get always the same error.

> 1 : Bus not free

I rewrote it in different ways, changing the frequency, pins and doing multiple transactions. The main reason I don't get it to work is the difference in the API.

There is no `Wire.requestFrom();` in the brzo_i2c lib. So I need to read the value with `brzo_i2c_read(buffer,2,false);`.

title: Fast I2C communication between ESP8266 & PCF8591

Answers: 2

body:
I have no idea about Brzo but this looks wrong:

     brzo_i2c_start_transaction(0x48,400);
     buffer[0]=0x04;
     brzo_i2c_write(buffer,1,false);       // Write
     brzo_i2c_read(buffer,2,false);        // Then a read ??
     bcode=brzo_i2c_end_transaction();

I think you end and read are the wrong way round, but like I say I've never done anything with this so I'm probably wrong.

body:
This line

    brzo_i2c_start_transaction(0x48,400);

Sets the SCL frequency to 400kHz.

According to the [Datasheet for the PCF8591](https://www.nxp.com/docs/en/data-sheet/PCF8591.pdf#page=20) the maximum SCL clock frequency is 100kHz.

The other issue *may* be the "repeated_start" flag on `brzo_i2c_write`.

If you look at the examples, and "apply" that to your code, your would do something like:

    uint8_t ICACHE_RAM_ATTR get_temp(float *t){
      uint8_t bcode=0;
      brzo_i2c_start_transaction(0x48,100); // changed 400 to 100
      buffer[0]=0x04;
      brzo_i2c_write(buffer,1,true); // changed to true because
      brzo_i2c_read(buffer,2,false);
      bcode=brzo_i2c_end_transaction();
      *t=((buffer[0]<<8)|buffer[1]);
      return bcode;
    }

My understanding of the code is that you would set `repeated_start` to true in the write if you want to then immediately read - which in your case you want to.


body:
**What I want to achieve**

I want to connect to my wifi network using Arduino UNO and ESP8266 using `WiFiEsp.h` library over `SofwareSerial, since UNO doesn't have additional H/W serial.

**What I am able to do already**

I have a Mega, which I am able to connect to my wifi network(using ESP8266) using its hardware serial (RX1 and TX1), I've been following up [this][1] code example. Though it has code to deal with both cases( when H/W serial is present and when it's not) It doesn't seems to work on Software Serial on UNO, works perfectly on MEGA's H/W serial. I have made a little change in code as to set the Serial1 baudrate to `115200` as this seems to be supported by my ESP's firmware (1.54)

**ERROR**

`[WiFiEsp] Initializing ESP module
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] Cannot initialize ESP module
`

**What I've tried**

 1. Tried running Software Serial on MEGA on pins 10,11 and 6,7 (Rx,Tx) (Same Error).
 2. Swapping Rx,Tx :P
 3. Changing pins to 10,11 instead of 6,7 on UNO
 4. Switching Baudrate to 9600 on UNO (no help)

Yeah, Not much, but it seems so straight forward I can't figure out what could go wrong. It seems like it can't communicate to ESP, but why?

  [1]: http://yaab-arduino.blogspot.in/p/wifiesp-example-connect.html

title: WiFiEsp not working on Software Serial, working fine on Hardware Serial

Answers: 1

body:
If you're going to talk to your ESP at 9600 baud - and that's about the upper limit for SoftwareSerial - you need to first change the ESP board's baud rate to 9600 baud. It is probably at 115200 right now.

You can do that with either kind of serial. Even though SoftwareSerial can't receive at 115200, it can usually transmit (Uno -> ESP) that fast. You need to send it the command:

    AT+UART_DEF=9600,8,1,0,0

If you do it with SoftwareSerial, the reply coming back from the ESP after changing its baud will be garbled because your serial terminal will still be listening at the faster speed. So at this point, change the speed of your terminal and send the command:

    AT

The ESP should respond with

    OK

If it does - and it probably will - you're all set and can continue using it at 9600 baud. If not, go back to 115200 baud on your serial terminal and try it again. (I've never had to do it twice).

Update:

> I tried sending AT commands @ 115200, Its actually sending and receiving back well at 115200. Is this normal ?

With hardware serial, yes. The Uno's hardware UART can probably go at up to 4x that! But I've never had any luck receiving with SoftwareSerial at 115200; the most I could count on was 9600.


body:
Here's a question for anyone knowledgeable of the ways of I2C.

I'm curious about sending multiple writes to a device and was looking at the code for a [MPU9250 module](https://www.sparkfun.com/products/13762).

There is a nice library that compiled straight off the shelf by Kris Winer [here](https://raw.githubusercontent.com/kriswiner/MPU-9250/master/MPU9250BasicAHRS.ino).

In one of his code examples he makes multiple calls to a function called writeByte():

    // Wire.h read and write protocols
    void writeByte(uint8_t address, uint8_t subAddress, uint8_t data)
    {
     Wire.beginTransmission(address);  // Initialize the Tx buffer
     Wire.write(subAddress);           // Put slave register address in Tx buffer
     Wire.write(data);                 // Put data in Tx buffer
     Wire.endTransmission();           // Send the Tx buffer
    }

here is a (truncated) example of the code calling writeByte():

    void initMPU9250()
    {
      writeByte(MPU9250_ADDRESS, PWR_MGMT_1, 0x00);
      delay(100);

      writeByte(MPU9250_ADDRESS, PWR_MGMT_1, 0x01);
      delay(200);
      writeByte(MPU9250_ADDRESS, CONFIG, 0x03);
      writeByte(MPU9250_ADDRESS, SMPLRT_DIV, 0x04);
      .
      .
      .
      etc
    }

My question is why call Wire.endtransmission() each time your sending I2C to the same device? I can see one reason straight off the bat which is you may need to call delay after your write() - but in cases where you do not need to call delay, wouldnt it be faster to do something like:

    Wire.beginTransmission(address);
    Wire.write(data1);
    Wire.write(data2);
    Wire.write(data3);
    Wire.write(data4);
    Wire.endTransmission();

at least when it's possible?

title: Performing multiple Wire.writes() - does endtransmission slow things down?

Answers: 1

body:
No, `Wire.endTransmission()` doesn't "slow things down". It is, however, critical to the operation of the Wire library.

When you do a Wire transaction all the data you send is first buffered in an internal array. Only when you call `Wire.endTransmission()` does that data actually get sent out. The actual `Wire.endTransmission()` doesn't add anything extra to the transmission though.

In your example you are sending a total of 5 bytes (address + 4 data bytes) plus start/ACK/stop bits. In general most devices require you to send specific numbers of bytes in a specific order - the most common being a register address followed by the content of that register. That means 3 bytes. Any more bytes after that in the same transaction will either be ignored or would overwrite the first bytes.

Some devices though would allow `<address><value><address><value>` to be sent, thus removing the need for the repeated I2C address byte for the device each time. Many won't though.

Other devices (most notably flash memory or SRAM chips) would allow you to do *page mode* accesses, which would be `<address><data1><data2>...<dataN>` where the `address` would automatically increment for each data byte. Again, some may, some won't.

It is entirely down to the device you are sending data to as to whether you are able to batch together multiple blocks of data, and the form that batching has to be in if it is supported at all. So you should look in the datasheet for the device to see just what it can support.


body: I want to use the Arduino to control various electronics on my motorcycle. I would need to power the Arduino with the motorcycle battery. So the question is, when the motorcycle is running the alternator will be putting out something like 13v to the battery. So can I still just connect the battery directly to the vIn and ground to power it?

title: Using an Arduino on a motorcycle

Answers: 2

body:
Accordly to Arduino Technical Specs:

-Input Voltage (recommended) 7-12V

-Input Voltage (limit) 6-20V

https://www.arduino.cc/en/main/arduinoBoardUno

Another Arduino thread:
https://forum.arduino.cc/index.php?topic=22676.0

I would say a better choice is to use another battery power supply just for Arduino. Is is easy to install, easier to handle and more verstile unless you really needs to use your motorcycle battery. And if you want or need to read your motorcycle battery just use a portable voltage meter plugged onto Arduino with no need to use your vehicle battery to power it.

body: Just add a rectifier diode or two before the vin input. This gives you a 0.7V drop per diode for large currents, for small currents the LDO won't overheat anyway...


body: During this week i purchased two hc-06 bluethoot module for arduino with the purpose of maintain a stable bluethoot connection between two arduino devices. Most people use hc-05 and hc-06 togheter so my question is if i can make a connection without hc-05 module.

title: HC-06 Bluethoot communication

Answers: 2

body:
No.

What you have is two slave devices and you need a master in order to initiate the Bluetooth communication with the slave. So, either you need two HC-05 Or 1* HC-05 and 1* HC-06.

body:
You have purchased two slave modules (HC-06). Actually, you have to use a master module (HC-05) in order to initiate the Bluetooth communication.

Therefore, the answer to your question is NO ,  can not make a connection without HC-05 module, unless you provide any other master module.


body:
I'm writing a helper class to manage timers, and I'm writing a lot of code like

    if (timer == 1)
   ICR1 = icr;
  else if (timer == 3)
   ICR3 = icr;
  else if (timer == 4)
   ICR4 = icr;
  else if (timer == 5)
   ICR5 = icr;

Is there a better way to store these registers?
e.g. an array

    timers {
    { ICR1, TCCR1A, OCR1A, OCR1B },
    { ICR2, TCCR2A, OCR2A, OCR2B }
etc.

to be accessed like

    timers[1][0]

for ICR1.

And ultimately, how would I assign a value? e.g.

    *timers[1][0] = 100;

**UPDATE:**

I solved the problem with

 volatile uint16_t* ICRs[5];
 ICRs[1] = &ICR1;
 ICRs[3] = &ICR3;
 ICRs[4] = &ICR4;
 ICRs[5] = &ICR5;

    *ICRs[1] = x;

title: Use registers as parameter?

Answers: 3

body:
You can better use a switch statement:

    switch (timer)
    {
    case 1:
        ICR1 = icr;
        break;

    case 3:
        ICR3 = icr;
        break;

    case 4:
        ICR4 = icr;
        break;

    case 5:
        ICR5 = icr;
        break;

    default:
        // Handle other cases
        break;
    }

About the variables:

You can make a 2 dimensional array:

    typedef enum
    {
       TYPE_ICR,   // Value 0
       TYPE_TCCRA, // Value 1
       TYPE_OCRA,  // Value 2
       TYPE_OCRB,  // Value 3
       TYPE_LAST,  // Value 4
    } EType;

    EType timers[TYPE_LAST][2];

You can access it by

    timers[(int) TYPE_OCRB][0] = 3;
    timers[(int) TYPE_OCRA][1] = 0;

Maybe the (int) cast is not needed.

You also can just iterate over the type:

    for (int type = 0; type < (int) TYPE_LAST; type++)
    {
        timers[type][0] = -1;
        timers[type][1] = -1;
    }

Note 1: if a cast is needed probably static_cast(...) is better to use.
Note 2: I haven't tested the code above

body:
registers are nothing but pointers to memory addresses. so the best way to "parameterize" them is to do so via pointers.

*assuming* that ICRi is of 8-bit types - they are NOT to be sure:

    uint8_t *ICRs[4];  //isr pointers

    //initialize the icrs
    ICRs[0]=(uint8_t *)&ICR0;
    ICRs[1]=(uint8_t *)&ICR1;
    ...

    *ICRs[i]=icr; //assign value to ICRi

*note:* that piece of code isn't operable in reality. The way to go is to use a pointer to void. But I'm sure you can figure that out.

body:
i would suggest creating macro definitions for the timers you want

Something along the lines of:

    #define OCR_BY_INDEX(i) OCR##i
    //...other code...
    OCR_BY_INDEX(1) = value;

and then have the indices in an array


body:
I'm trying to connect two Arduinos according to the example in [Example][1]

I added a bit of debug prints so the code looks like:

    #include <Wire.h>

    // Include the required Wire library for I2C<br>#include <Wire.h>
    int LED = 13;
    int x = 0;
    void setup() {
      // Define the LED pin as Output
      pinMode (LED, OUTPUT);
      // Start the I2C Bus as Slave on address 9
      Wire.begin(9);
      // Attach a function to trigger when something is received.
      Wire.onReceive(receiveEvent);
      Serial.begin(9600);
    }
    void receiveEvent(int bytes) {
      x = Wire.read();    // read one character from the I2C
      Serial.println(x);
    }

    void loop() {
      //If value received is 0 blink LED for 200 ms
      Serial.print("x = '");
      Serial.print(x);
      Serial.println("'");
      if (x == '0') {
        Serial.println("Do 0");
        digitalWrite(LED, HIGH);
        delay(200);
        digitalWrite(LED, LOW);
        delay(200);
      }
      //If value received is 3 blink LED for 400 ms
      if (x == '3') {
        Serial.println("Do 3");
        digitalWrite(LED, HIGH);
        delay(400);
        digitalWrite(LED, LOW);
        delay(400);
      }
    }

The strange thing is, the terminal gives the following information:

    ...
    x = '2'
    x = '2'
    x = '2'
    x = '2'
    x = '2'
    x3= '3'
    x = '3'
    x = '3'
    x = '3'
    x = '3'
    ...

However, I never see the expected "Do 3" lines. Why is that? I assume if (x == '3) would return true when x = '3'?

Also I see the x3 = '3'instead of x = '3'... now I print x also while an event is received, but are those in two different threads since the expected text would be "3x = '3'")  or "x = '3'3"

  [1]: https://www.instructables.com/id/I2C-between-Arduinos/step1

title: if condition does not work

Answers: 1

body:
Following code is printing value of integer as string.

    int x = 0;
    ...
    Serial.print("x = '");
    Serial.print(x);
    Serial.println("'");

It prints `x = '3'` for numeric value 3. But ASCII value for character '3' is actually 51.

And about the second issue - `reveiveEvent` is called from receive ISR asynchronously, so it's completely random when the main code gets interrupted. Btw printing anything inside of ISR is quite tricky. If the output buffer is full or will be filled up inside of ISR, everything gets deadlocked as it needs ISRs enabled.


body:
Today I got my clone Arduino and connected it to my real Arduino and they both work. (UPDATE: The Arduino noted as real Arduino probably also is not a real Arduino; however both work fine).

However, I see some differences and wonder if these are good or bad:

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

My questions

1) At number 1 there is on the clone arduino a 12 MHz oscillator? What does it do? And since there is also the regular 16 MHz oscillator I wonder why there are two.

2) At number 2 are 4 holes without any explanation. What is the function?

3) At 3 there are 12 holes (sorry that only 9 are visible, under the blue/black cable are 4 more holes with silver square around them.

4) At 4 there is a SCL and SDA which are used for SPI I think, but these are not on the original Arduino. But the original Arduino has 6 pins at the same location and 4 holes (where 2 of them are marked as JP2).

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

title: Differences between a real and clone Arduino uno?

Answers: 1

body:
The best help is the [schematics][1] for the clone.

[![enter image description here][2]][2]

> 1) At number 1 there is on the clone arduino a 12 MHz oscillator? What does it do? And since there is also the regular 16 MHz oscillator I wonder why there are two.

Lower left on the schematics is the 12 MHz crystal. It is for the CH340G (USB-UART chip).

> 2) At number 2 are 4 holes without any explanation. What is the function?

Lower middle is the pins X1. They are extra signals from the USB-UART chip (CTS, DSR, R and DCD).

> 3) At 3 there are 12 holes (sorry that only 9 are visible, under the blue/black cable are 4 more holes with silver square around them.

Upper right on the schematics are the extra pins. This might be handy.

> 4) At 4 there is a SCL and SDA which are used for SPI I think, but these are not on the original Arduino. But the original Arduino has 6 pins at the same location and 4 holes (where 2 of them are marked as JP2).

The original has an extra ISP pins (ICSP1) for the ATmega16U2. See the [schematics][3]. The clone has the new layout I2C signals extending beyond pin 13.

  [1]: http://jarick.com.ua/все-остальное/25-схема-клона-arduino-uno-r3-на-atmega328-и-ch340g.html
  [2]: https://i.stack.imgur.com/pZnla.jpg
  [3]: https://www.arduino.cc/en/uploads/Main/Arduino_Uno_Rev3-schematic.pdf


body:
I'm transmitting this program over an NRF24l01, data from mpu, and I'm getting a FIFO overflow. Im not sure what the problem is but it gives me a lag when I put it on processing so I know the problem is in the code. I posted the code the below. Pleas help find the issue.

    // Include libraries necessary for the radios
    #include <SPI.h>
    #include <nRF24L01.h>
    #include <RF24.h>

    RF24 radio(7, 8);

    #include "I2Cdev.h"
    #include "MPU6050_6Axis_MotionApps20.h"

        #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
            #include "Wire.h"
        #endif

        MPU6050 mpu;

        #define OUTPUT_TEAPOT

        #define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6)
        bool blinkState = false;
        // MPU control/status vars
        bool dmpReady = false;  // set true if DMP init was successful
        uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
        uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
        uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
        uint16_t fifoCount;     // count of all bytes currently in FIFO
        uint8_t fifoBuffer[64]; // FIFO storage buffer
        // orientation/motion vars
        Quaternion q;           // [w, x, y, z]         quaternion container
        VectorFloat gravity;    // [x, y, z]            gravity vector
        float euler[3];         // [psi, theta, phi]    Euler angle container
        float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector
        // packet structure for InvenSense teapot demo
        uint8_t teapotPacket[14] = { '$', 0x02, 0,0, 0,0, 0,0, 0,0, 0x00, 0x00, '\r', '\n' };

        // ================================================================
        // ===               INTERRUPT DETECTION ROUTINE                ===
        // ================================================================
        volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
        void dmpDataReady() {
            mpuInterrupt = true;
        }
        // ================================================================
        // ===                      INITIAL SETUP                       ===
        // ================================================================
        void setup() {
            // join I2C bus (I2Cdev library doesn't do this automatically)
            #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
                Wire.begin();
              //TWBR = 8; // 400kHz I2C clock (200kHz if CPU is 8MHz). Comment this line if having compilation difficulties with TWBR.

            #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
                Fastwire::setup(400, true);
            #endif

            radio.begin();

            radio.setRetries(15, 15);
            radio.openWritingPipe(0xF0F0F0F0A1LL);

            radio.stopListening();
            Serial.begin(115200);

            // load and configure the DMP
            Serial.println(F("Initializing DMP..."));
            devStatus = mpu.dmpInitialize();

            mpu.setXGyroOffset(54);
            mpu.setYGyroOffset(15);
            mpu.setZGyroOffset(33);
            mpu.setZAccelOffset(1613); // 1688 factory default for my test chip
            mpu.setXAccelOffset(-4009);
            mpu.setYAccelOffset(332);

            // make sure it worked (returns 0 if so)
            if (devStatus == 0) {
                // turn on the DMP, now that it's ready
                Serial.println(F("Enabling DMP..."));
                mpu.setDMPEnabled(true);

                Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
                attachInterrupt(0, dmpDataReady, RISING);
                mpuIntStatus = mpu.getIntStatus();

                Serial.println(F("DMP ready! Waiting for first interrupt..."));
                dmpReady = true;
                // get expected DMP packet size for later comparison
                packetSize = mpu.dmpGetFIFOPacketSize();
            } else {

                Serial.print(F("DMP Initialization failed (code "));
                Serial.print(devStatus);
                Serial.println(F(")"));
            }
            // configure LED for output
            pinMode(LED_PIN, OUTPUT);
        }
        // ================================================================
        // ===                    MAIN PROGRAM LOOP                     ===
        // ================================================================
        void loop() {
            // if programming failed, don't try to do anything
            if (!dmpReady) return;
            // wait for MPU interrupt or extra packet(s) available
            while (!mpuInterrupt && fifoCount < packetSize) {

              /*Do some computational stuff here*/

            }

            // reset interrupt flag and get INT_STATUS byte
            mpuInterrupt = false;
            mpuIntStatus = mpu.getIntStatus();
            // get current FIFO count
            fifoCount = mpu.getFIFOCount();
            // check for overflow (this should never happen unless our code is too inefficient)
            if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
                // reset so we can continue cleanly
                mpu.resetFIFO();

                Serial.println(F("FIFO overflow!"));
            // otherwise, check for DMP data ready interrupt (this should happen frequently)
            } else if (mpuIntStatus & 0x02) {

                // wait for correct available data length, should be a VERY short wait
                while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();
                // read a packet from FIFO
                mpu.getFIFOBytes(fifoBuffer, packetSize);

                fifoCount -= packetSize;

                    /*Object to Transmit Yaw, Pitch, and Roll*/
                    typedef struct YPR_TX {
                      int y;
                      int p;
                      int r;

                    } YPR_TX;

                    YPR_TX ypr_tx;

                 //   ypr_tx = calcYPR(ypr_tx.y, ypr_tx.p, ypr_tx.r);

                    ypr_tx.y = ypr[0] * 180/M_PI;
                    ypr_tx.p = ypr[1] * 180/M_PI;
                    ypr_tx.r = ypr[2] * 180/M_PI;

                #ifdef OUTPUT_TEAPOT
                    // display quaternion values in InvenSense Teapot demo format:
                    teapotPacket[2] = fifoBuffer[0];
                    teapotPacket[3] = fifoBuffer[1];
                    teapotPacket[4] = fifoBuffer[4];
                    teapotPacket[5] = fifoBuffer[5];
                    teapotPacket[6] = fifoBuffer[8];
                    teapotPacket[7] = fifoBuffer[9];
                    teapotPacket[8] = fifoBuffer[12];
                    teapotPacket[9] = fifoBuffer[13];

                    Serial.print("teapotPacket/t");
                    Serial.print("\t");
                    Serial.print(teapotPacket[2]);
                    Serial.print("\t");
                    Serial.print(teapotPacket[3]);
                    Serial.print("\t");
                    Serial.print(teapotPacket[4]);
                    Serial.print("\t");
                    Serial.print(teapotPacket[5]);
                    Serial.print("\t");
                    Serial.print(teapotPacket[6]);
                    Serial.print("\t");
                    Serial.print(teapotPacket[7]);
                    Serial.print("\t");
                    Serial.print(teapotPacket[8]);
                    Serial.print("\t");
                    Serial.println(teapotPacket[9]);
                   // radio.getDataRate();

                    radio.write(&teapotPacket, sizeof(teapotPacket));

                #endif

                // blink LED to indicate activity
                blinkState = !blinkState;
                digitalWrite(LED_PIN, blinkState);
            }

        }

title: Why does this sketch give MPU FIFO overflows?

Answers: 2

body:
You are declaring a FIFO overflow every time the mpu sends interrupt 0x10.  Is that correct?

You are using the value in fifoCount before you have set it to a value.  Now with the Arduino IDE you are OK doing that, but its not a good practice.

You are checking that the fifoCount is exactly 1024. It might be better to check if it is >1023 because that will handle the case when it is 1025.

Is there a reason why you have chosen 1024?  Since the packet size defaults to 42 that's 24.3 packets.

Around

    while (!mpuInterrupt && fifoCount < packetSize) {
You never get the fifoCount again, so `fifoCount < packetSize` is always true, therefore you wait until there is an interrupt.  If there first time there is an interrupt is to tell you 0x10 (which I guess is) fifo full from the MPU's perspective) then that will be the reason it is always full.

       // wait for MPU interrupt or extra packet(s) available
        while (!mpuInterrupt && fifoCount < packetSize) {

          /*Do some computational stuff here*/
          fifoCount = mpu.getFIFOCount(); // Don't forget to get the latest fifo size.
        }

body:
I have been playing around with the MPU6050 with DMP library too. I see you have used Jeff's example code (as have I). I was getting a lot of FIFO overflows too, but that was because my "do computational stuff here" was taking too long (code with delay()) and the FIFO on the DMP was filling up. Perhaps your radio.write() is taking too long?

The code as written by Jeff is really quite robust, but perhaps not what is necessary in all cases. I have put an extra mpu.resetFIFO() below the Serial.println's. Kind of a hack, but it works. I found the suggestion here:

https://arduino.stackexchange.com/questions/10308/how-to-clear-fifo-buffer-on-mpu6050

Also check on Jeff's own suggestion of lowering the data rate on the DMP by altering the header file:

https://www.i2cdevlib.com/forums/topic/27-fifo-overflow/#comment-99

Hope this helps.


body:
I'm outputting an analog voltage by setting an 8-bit duty cycle using `analogWrite`. Once set, I'd like a way to read back this duty cycle. I've managed to read the duty cycle back from the `OCR4D` register, which matches the value set, e.g.:

    pinMode(6, OUTPUT);
    analogWrite(6, 123);
    Serial.print(OCR4D);   // 123

However, when setting the duty cycle to `0` or `255`, `OCR4D` is not actually set at all; instead `analogWrite` calls `digitalWrite` behind the scenes and the pin is digitally set to `LOW` or `HIGH`. This is seen in the source for `analogWrite`:

    if (val == 0)
 {
  digitalWrite(pin, LOW);
 }
 else if (val == 255)
 {
  digitalWrite(pin, HIGH);
 }
 else
 {
    // set PWM duty cycle as normal...

The problem with this is that `OCR4D` is simply left at its previous value, so it's not always possible to tell the actual output by reading `OCR4D` alone. In other words there is no way to tell the difference between:
- PWM is active and `OCR4D` reflects the duty cycle
- PWM is disabled and `OCR4D` reflects a previous duty cycle (which is not useful)

Which register(s) can I read to crosscheck the PWM is active?

I'm also aware of the `pulseIn` function, but would rather read the PWM register directly.

title: Directly read analog voltage using PWM duty cycle timer registers

Answers: 1

body:
In the end I managed to do this by reading the timer/counter control register relevant to pin 6:

    // read the voltage on an analog output pin
    int analogReadOutput(int pin) {
        switch(digitalPinToTimer(pin)) {
            case TIMER4D:
                if (TCCR4C & (1 << COM4D1)) {   // PWM active
                    return OCR4D;
                } else {                        // PWM not active
                    return 255 * digitalRead(pin);
                }
            case TIMER4A:
                if (TCCR4A & (1 << COM4A1)) {   // PWM active
                    return OCR4A;
                } else {                        // PWM not active
                    return 255 * digitalRead(pin);
                }
            default:
                return -1;
        }
    }

Note that this assumes two things that possibly aren't always true (outside of my simple program):

- `COM4D1` bit is a reliable way of telling if PWM is enabled,
- duty cycle value is 8 bit with a max of 255.


body:
I am working on a class project where I am using a Teensy 3.5 with a Prop Shield with sensor attached that will be loaded into a rocket that I will launch and gather data from the altitude, pressure and temperature sensors and then read into an array and then dump at the peak of the height and when it hits the ground. I believe I have everything working when I test the code but when I open up the txt file I get what looks to be ASCII code but I don't know how to fix it.

Below is the code:

    //import statements
    #include <SD.h>
    #include <SPI.h>
    #include <Wire.h>
    #include <Adafruit_MPL3115A2.h>

    // global variable declarations
    Adafruit_MPL3115A2 baro = Adafruit_MPL3115A2();

    int seconds = 0;
    int secondsPerTick = 0;
    int counter = 0;
    double pressure[15];
    double heightA[15];
    double temperature[15];
    File myFile;
    int tempNum;
    const int chipSelect = BUILTIN_SDCARD;

    //test to make sure program uploaded
    void setup() {
      Serial.begin(9600);
      Serial.println("Adafruit_MPL3115A2 test!");
      while (!Serial){
    }

      if (! baro.begin()) {
        Serial.println("Couldnt find sensor");
       return;
      }

    if (!SD.begin(chipSelect)) {
        Serial.println("initialization failed!");
        return;
      }

    while ( seconds < 5 ){

                  double pascals = baro.getPressure();
                  pressure[counter] = pascals;
                  Serial.print(pascals/3377); Serial.println(" Inches (Hg)");

                 double altm = baro.getAltitude();
                  heightA[counter] = altm;
                  Serial.print(altm); Serial.println(" meters");

                 double tempC = baro.getTemperature();
                  temperature[counter] = tempC;
                  Serial.print(tempC); Serial.println(" *C");
                  tempNum ++;

                  secondsPerTick++; //increments seconds per tick
                  if(secondsPerTick == 3){  //if its 3 reset "secondspertick" and increments "seconds"
                    secondsPerTick = 0;
                    seconds++;
                  }
                  counter++;

     }

    myFile = SD.open("Sensor4.txt", FILE_WRITE);

       if(myFile) {
        Serial.print("Writing to file...");

        //cycle through the array and store it in the SD card
        myFile.write("Pressure Recordings(going up): ");
        for(int i=0; i< 15; i++){
          myFile.write(pressure[i]);
          }
        Serial.println('\n');

           //header for the height sensor recordings
       myFile.write("Height Recordings(going up): ");
        //cycle through the array and store it in the SD card
        for (int j = 0; j <15; j ++){
         myFile.write(heightA[j]);
        }
        Serial.println('\n');

        //header for the temperature sensor recordings
        myFile.write("Temperature Recordings(going up): ");
        Serial.println('\n');
        //cycle through the array and store it in the SD card
        for (int k = 0; k <15; k++){
         myFile.write(temperature[k]);
        Serial.println('\n');
       }

        // close the file:
        myFile.close();
        Serial.println("done.");
        }
       else {
        // if the file didn't open, print an error:
        Serial.println("error opening sensor_recordings.txt");
      }

         //as the rocket descends
    while ( seconds > 5 ){

                  double pascals = baro.getPressure();
                  pressure[counter] = pascals;
                  Serial.print(pascals/3377); Serial.println(" Inches (Hg)");

                  myFile.write(pressure[counter]);

                 double altm = baro.getAltitude();
                  heightA[counter] = altm;
                  Serial.print(altm); Serial.println(" meters");

                 double tempC = baro.getTemperature();
                  temperature[counter] = tempC;
                  Serial.print(tempC); Serial.println(" *C");
                  tempNum ++;

                  secondsPerTick++; //increments seconds per tick
                  if(secondsPerTick == 3){  //if its 3 reset "secondspertick" and increments "seconds"
                    secondsPerTick = 0;
                    seconds++;
                  }
                  counter++;

     }

    myFile = SD.open("Sensor4.txt", FILE_WRITE);

       if(myFile) {
        Serial.print("Writing to file...");

        //cycle through the array and store it in the SD card
        myFile.write("Pressure Recordings(going down): ");
        for(int i=0; i< 15; i++){
          myFile.write(pressure[i]);
          }
        Serial.println('\n');

           //header for the height sensor recordings
       myFile.write("Height Recordings(going down): ");
        //cycle through the array and store it in the SD card
        for (int j = 0; j <15; j ++){
         myFile.write(heightA[j]);
        }
        Serial.println('\n');

        //header for the temperature sensor recordings
        myFile.write("Temperature Recordings(going down): ");
        Serial.println('\n');

        //cycle through the array and store it in the SD card
        for (int k = 0; k <15; k++){
         myFile.write(temperature[k]);
        Serial.println('\n');
       }

        // close the file:
        myFile.close();
        Serial.println("done.");
        }
       else {
        // if the file didn't open, print an error:
        Serial.println("error opening sensor_recordings.txt");
      }
     }

    void loop() {

Here is what gets printed to the txt file:

>
 €€€ƒ€ƒ‚ƒ€€„~ƒ‚€€€€ƒ€ƒ‚ƒ€€„~ƒ‚€ƒ‚‚‚„‡€„ƒ„……ƒ‚ƒ„Pressure Recordings: ƒ‚‚‚„‡€„ƒ„……ƒ‚ƒ„
Height Recordings: 10010110010101111000Temperature
Recordings: Å……ƒƒ…€€ƒ‡‚w
Pressure Recordings: Å……ƒƒ…€€ƒ‡‚w
Height Recordings: 000010100010111     Temperature Recordings:      Pressure Recordings: Å……ƒƒ…€€ƒ‡‚w     Height Recordings: 000010100010111     Temperature Recordings:      Pressure Recordings: Ã‡…„†…„…„ˆ†„„€†     Height Recordings: 000000000000000     Temperature Recordings:      Pressure Recordings: Ã‡…„†…„…„ˆ†„„€†     Height Recordings: 000000000000000     Temperature Recordings:      Pressure Recordings: Â†‰†‡…††‰…‰ˆˆ…ˆ Height Recordings: 000000000000000     Temperature Recordings:      Pressure Recordings: Â†‰†‡…††‰…‰ˆˆ…ˆ Height Recordings: 000000000000000     Temperature Recordings:      Pressure Recordings(going up): ÀŽ‘ŽŒŽŽHeight Recordings(going up): ///000/0/0/0///Temperature Recordings(going up): Pressure Recordings(going down): ÀŽ‘ŽŒŽŽHeight Recordings(going down): ///000/0/0/0///Temperature Recordings(going down): Pressure Recordings(going up): ½–™––•˜–••š™š—™Height Recordings(going up): ///////////////Temperature Recordings(going up): Pressure Recordings(going down): ½–™––•˜–••š™š—™Height Recordings(going down): ///////////////Temperature Recordings(going down):

I also don't know how I can get the data to be formatted to where it reads like:

Pressure(going up):----

Altitude(going up):---

Temperature(going up):---

Pressure(going down):----

Altitude(going down):---

Temperature(going down):---

title: When writing to SD card the file has all gibberish how do I fix it?

Answers: 1

body:
You should convert double to String with this kind of code:

    char[9] stringval;
    dtostrf(doubleval, 8, 4, stringval);

where 8 is presicion and 4 is number of digits after point.

More info: http://forum.arduino.cc/index.php?topic=282250.0


body:
I want to know if it is possible to put a boundary or limit to the volume that passes through a water flow sensor, and close the pipe using a solenoid valve.

Example: I only want 400 ml of water to pass, so when the water flow sensor reads how much water has passed in the pipe, if 400 is reached, the solenoid will close the pipe.

Sorry for my bad English, it is not my first language. I'm hopping that someone can help me out.

title: How to code water flow sensor and solenoid valve?

Answers: 2

body:
Using a YF201 you cannot measure less than 1 litre / minute or more than 30 l/m.
(ref http://www.bc-robotics.com/tutorials/using-a-flow-sensor-with-arduino/)

The device sends a pulse for every 2.25ml that flows through it.  All you needs to do is take the amount you want to let through (400ml) and divide that by 2.25ml and you get 177.8 pulses.  So once your Arduino counts 178 pulses then you trigger the valve to close.

Its not going to be very accurate, because unless the valve closes instantly there will be a bit of an overshoot.  and you have to measure in units of 2.25ml.

body:
hello @kaisar Great you have not mentioned which flow sensor are you using. I am assuming that you are using flow sensor YF-S201 or YF-S401(Hall Effect).You have to do Little calculation for measuring water flow.
In order to measure the quantity of water being passed in particular time through the water flow sensor it was first passed through the water flow sensor which was taken as input interface in the flow. Formulas are applied in order to measure the number of rotations/pulses in a minute of rotation.

Here I have determined flow rate by change in velocity of water. Velocity depends on the pressure that forces the through pipelines. As the pipe’s cross-sectional area is known and remains constant, the average velocity is an indication of the flow rate. The basis relationship for determining the liquid’s flow rate in such cases is

**Q=VxA**, where **Q** is flow rate/total flow of water through the pipe, **V** is average velocity of the flow and A is the cross-sectional area of the pipe

**Calibration Factor** = *The hall-effect flow sensor outputs pulses per second per litre/minute of flow.(check your datasheet) here I have taken 4.5.*

**Flow Rate(litres/minute)** = *((1000.0 / Total time) x Pulse Count) / calibration Factor*

**Flow Rate(MilliLitres/Second)** = *(Flow Rate / 60) x 1000*

There you have to calculate the total water flow in a given time by adding flow rate for each second.
There after you have check your set point value(400ml)..if condition satisfied you you can turn off your Solenoid valve.

and the code is

    int sensorInterrupt = 0;  // interrupt 0
    int sensorPin       = 2; //Digital Pin 2
    int solenoidValve = 5; // Digital pin 5
    unsigned int SetPoint = 400; //400 milileter

    /*The hall-effect flow sensor outputs pulses per second per litre/minute of flow.*/
    float calibrationFactor = 4.5; //You can change according to your datasheet

    volatile byte pulseCount =0;

    float flowRate = 0.0;
    unsigned int flowMilliLitres =0;
    unsigned long totalMilliLitres = 0;

    unsigned long oldTime = 0;

    void setup()
    {

      // Initialize a serial connection for reporting values to the host
      Serial.begin(9600);
      pinMode(solenoidValve , OUTPUT);
      pinMode(sensorPin, INPUT);
      digitalWrite(sensorPin, HIGH);

      /*The Hall-effect sensor is connected to pin 2 which uses interrupt 0. Configured to trigger on a FALLING state change (transition from HIGH
      (state to LOW state)*/
      attachInterrupt(sensorInterrupt, pulseCounter, FALLING); //you can use Rising or Falling
    }

    void loop()
    {

       if((millis() - oldTime) > 1000)    // Only process counters once per second
      {
        // Disable the interrupt while calculating flow rate and sending the value to the host
        detachInterrupt(sensorInterrupt);

        // Because this loop may not complete in exactly 1 second intervals we calculate the number of milliseconds that have passed since the last execution and use that to scale the output. We also apply the calibrationFactor to scale the output based on the number of pulses per second per units of measure (litres/minute in this case) coming from the sensor.
        flowRate = ((1000.0 / (millis() - oldTime)) * pulseCount) / calibrationFactor;

        // Note the time this processing pass was executed. Note that because we've
        // disabled interrupts the millis() function won't actually be incrementing right
        // at this point, but it will still return the value it was set to just before
        // interrupts went away.
        oldTime = millis();

        // Divide the flow rate in litres/minute by 60 to determine how many litres have
        // passed through the sensor in this 1 second interval, then multiply by 1000 to
        // convert to millilitres.
        flowMilliLitres = (flowRate / 60) * 1000;

        // Add the millilitres passed in this second to the cumulative total
        totalMilliLitres += flowMilliLitres;

        unsigned int frac;

        // Print the flow rate for this second in litres / minute
        Serial.print("Flow rate: ");
        Serial.print(flowMilliLitres, DEC);  // Print the integer part of the variable
        Serial.print("mL/Second");
        Serial.print("\t");

        // Print the cumulative total of litres flowed since starting
        Serial.print("Output Liquid Quantity: ");
        Serial.print(totalMilliLitres,DEC);
        Serial.println("mL");
        Serial.print("\t");
        If (totalMilliLitres =< 400)
        {
          SetSolinoidValveON();
        }
        else{
          SetSolinoidValveOFF();
            }

    // Reset the pulse counter so we can start incrementing again
        pulseCount = 0;

        // Enable the interrupt again now that we've finished sending output
        attachInterrupt(sensorInterrupt, pulseCounter, FALLING);
      }
    }

    //Insterrupt Service Routine

    void pulseCounter()
    {
      // Increment the pulse counter
      pulseCount++;
    }

    void SetSolinoidValveON()
    {
      digitalWrite(solenoidValve, HIGH);
    }
    void SetSolinoidValveOFF()
    {
      digitalWrite(solenoidValve, LOW);
    }


body:
You know , a simple arduino sketch has no main function , no include preprocess cmds,so I just want to know how arduino IDE convert a sketch to normal C/C++ source code,and what is the source code looks like.

If possible,I also want to use cmd like  *g++ -E*   to see the .i file genetated after preprocess.How to do it?

ps: my English is poor.

title: How Arduino IDE works?

Answers: 2

body:
I'm not entirely sure what the `arduino-builder` does, but it should be similar to the traditional method.

Given the "bare minimum" sketch of:

    void setup() {
    }

    void loop() {
    }

First the IDE combines all `.ino` and `.pde` files together into one large one. I believe the order of concatenation is:

1. Start with the "main" INO file (the one named the same as the folder it's in).
2. Append to that each other `.ino` or `.pde` file in alphabetical order.

Then the IDE will add the required `#include <Arduino.h>` and function prototypes for any functions found - so it would end up as:

    #include <Arduino.h>

    void setup();
    void loop();

    void setup() {
    }

    void loop() {
    }

Finally it runs normal `gcc` and `g++` commands on the generated file(s).  You can find the generated file(s) in the *build* folder. Where that is depends on the operating system you are using.  Turn on *verbose compilation* in the preferences and you can see the `gcc` and `g++` commands that are being executed, and as well the paths for the files involved, which lets you then see where the preprocessed files are stored.

Another important step the IDE performs, which doesn't modify the files themselves, is to look for any `#include` entries that match libraries and add `-I <path>` to the compilation commands for those libraries. It also then finds any source files associated with those libraries and compiles them. It also compiles all the *core* source files, which is where the `main()` functions is (see [@jantje's answer](https://arduino.stackexchange.com/a/36485/4143) for details on how the `main()` function is formed).

Once the IDE has finished with its parsing and processing it's all standard `gcc` and `g++`.

body:
You can turn on verbose compiling.
This will show all the compiler commands used by Arduino IDE.

The ino file is converted to a .cpp file (which you can see in the verbose output). Basically the conversion is as follows:

 1. merge all .ino files into one big .ino file with the [project].ino
    file first
 2. Add arduino.h
 3. Add all function declarations of methods defined in the .ino files
 4. Save as .cpp file

As to the lack of main method.
The core contains a main.cpp file which defines main in avr world this looks like

    int main(void)
    {
     init();

     initVariant();

    #if defined(USBCON)
     USBDevice.attach();
    #endif

     setup();

     for (;;) {
      loop();
      if (serialEventRun) serialEventRun();
     }

     return 0;
    }


body:
I have just bought arduino nano board. when i connect the board via usb, system detects the new device but i am not able to select port in arduino ide for writing any code on board. I checked my device manager it says

> The drivers for this device are not installed. (Code 28)
>
> There are no compatible drivers for this device.

I have also updated my board and library list in arduino ide.

please help me out?

title: Arduino nano select port option is blurred | Driver issue

Answers: 1

body:
on my nano board CH340G USB<-->uart chip was present, so i installed driver for that chip and everything works fine now. :P

link for the driver (windows 8,10): http://www.arduined.eu/ch340-windows-8-driver-download/


body:
I have an LDR/Photocell which sends a value 1 or 0 (depending on the value) to a text file on my web address. The code works for a few seconds then prints out `No Socket available`.

Any help will be appreciated; code below.

 #include <SPI.h>
 #include <WiFi.h>

 int LDR = A0;
 int LED = 11;
 char ssid[] = "SSID";
 char password[] = "password";
 int status = WL_IDLE_STATUS;

 char server[] = "www.example.com";
 int value;

 void setup() {
   Serial.begin(9600);
   pinMode(LDR, INPUT);
   pinMode(LED, OUTPUT);
   connectWifi();
   printWifiStatus();
   // postData();
 }

 void loop() {
   value = analogRead(LDR);
   postData();

   delay(10000);
 }

 void connectWifi() {
   while (status != WL_CONNECTED) {
     Serial.print("Attempting to connect to ");
     Serial.println(ssid);
     status = WiFi.begin(ssid, password);
     delay(500);
   }
 }

 void printWifiStatus() {
   // Print the SSID of the network you're attached to
   Serial.print("SSID: ");
   Serial.println(WiFi.SSID());

   // Print your WiFi shield's IP address
   IPAddress ip = WiFi.localIP();
   Serial.print("IP Address: ");
   Serial.println(ip);

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

 void postData() {
   WiFiClient client;
   if (client.connect(server, 80)) {
     Serial.println("Connecting...");
     if (value > 350) {
       Serial.println("0");
       digitalWrite(LED, LOW);
       String data = "value=0";
       client.print("GET /example/client.php?");
       client.print(data);
       client.println(" HTTP/1.1");
       client.println("Host: www.example.com");
       client.println("Connection: close");
       client.println(); client.println();
       //client.stop();
     } else {
       Serial.println("1");
       digitalWrite(LED, HIGH);
       String data = "value=1";
       client.print("GET /example/client.php?");
       client.print(data);
       client.println(" HTTP/1.1");
       client.println("Host: www.example.com");
       client.println("Connection: close");
       client.println(); client.println();
       //client.stop();
     }
   } else {
     Serial.println("Connection failed");
     client.stop();
   }

 }

Output:

 Attempting to connect to SSID
 SSID: SSID
 IP Address: 255.255.255.255
 signal strength (RSSI):-47 dBm
 Connecting...
 1
 Connecting...
 0
 Connecting...
 0
 Connecting...
 0
 No Socket available
 Connection failed
 No Socket available
 Connection failed
 No Socket available
 Connection failed
 No Socket available

Actual web address omitted.

title: "No Socket available" for WiFiClient

Answers: 1

body:
I guess you have commented the command:
 //client.stop();

If you allow it, I guess you will have your code running


body: I have to drive two switches one at a duty cycle of 60% and the other at a duty cycle of 66% simultaneously at 50khz frequency. I am using an Arduino Uno ATmega 328.

title: How to generate two pulses one with 60 and other 66 duty cycle at same instant in 2 pins?

Answers: 1

body:
I proposed a few approaches in generating 100kha pwm pulse trains here in response to someone's ask a couple of days ago. The identical code would work for your purpose as well.

It should come up quickly if you do a scan of topics here.

edit: to make it a little bit easier, here is the code I used to generate 50Khz pulse train with 60% and 66% duty cycles.

    void setup() {
      // put your setup code here, to run once:
      //pinMode(led1, OUTPUT);      //led1 as output
      //pinMode(led2, OUTPUT);      //led2 as output
      pwm1topr(F_CPU / F_PWM);      //set tmr1/pwm frequency to F_PWM
      analogWrite(led1, F_CPU / F_PWM * 60 / 100); //led1 @ 60% duty cycle
      analogWrite(led2, F_CPU / F_PWM * 66 / 100); //led2 @ 66% duty cycle
    }

    void loop() {
      // put your main code here, to run repeatedly:
        //digitalWrite(led, HIGH);  // turn the LED on (HIGH is the voltage level)
        //delay(100);               // wait for a second
        //digitalWrite(led, LOW);   // turn the LED off by making the voltage LOW
        //delay(100);               // wait for a second
    }

and a quick sim confirms its functionality.

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

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

enjoy.


body:
I am trying to send a lot of serial commands really fast. I basically need to change color of my LED strip many times per second (10 times per second should really be enough). If I do this over WiFi, it will eventually clutter up and make the ESP8266 unresponsive. I need to send the colors as hex, then convert them into usable values (HEX to RGB). Something tells me that's going to cost a lot of resources and the MCU is therefore spending a lot of time just converting the colors into RGB values. Here's a pseudo code example of what I am trying to achieve:

    void loop() {
        if(Serial.available()) {
            if(Serial.read().first(8) == "0xABCDEF") {
                //0xABCDEF is basically my indicator saying "this is for individual LEDs"
                //Serial.read() can now be something like 0xABCDEF FF0000 00FF00 0000FF FFFFFF 000000
                char* colors[] = Serial.read().split(" ");
                colorLED(colors);

            }
        }
    }

    void colorLED(colors) {
        for(i = 1; i < colors.length; i++) {
            strip.SetPixelColor(i, color[i]);
        }
    }

I hope this example makes sense. I can send a serial command like `0xABCDEF FF0000 00FF00 0000FF FFFFFF 000000`. 5 colors in HEX.

My real question is: How do I take a lot of inputs like above (or another way) and turn them into strings, so I can convert them to RGB? Is there a better way to send commands (like pure RGB values? but remember I need to send many)?. Here is how I convert my colors into RGB:

    //hexColor can be "FF0000"
    int number = (int)strtol(&hexColor[0], NULL, 16);

    int r = number >> 16;
    int g = number >> 8 & 0xFF;
    int b = number & 0xFF;

title: Fastest way to send serial commands and do something

Answers: 2

body:
Simple answer: don't.

Don't even consider strings in any form. Instead you want a state machine.

In pseudocode:

1. Start with an invalid count number (-1)
2. Read a character.
3. If that character is `x` then set your counter to 0.
4. Otherwise, if counter is 0 or more, convert the character to a number and place it into the right byte depending on the value of your counter
5. Increment counter
6. If counter is 6 then set your LED colours and set the counter to "invalid".
7. Return to start.

Or, in untested C:

    static int8_t counter = -1;
    static uint8_t r = 0;
    static uint8_t g = 0;
    static uint8_t b = 0;

    if (Serial.available()) {
        char c = Serial.read();
        if (c == 'x') {
            counter = 0;
        } else {
            if (c > 0x39) c -= 7;
            uint8_t v = c & 0x0f;
            switch (counter) {
                case 0: r = v << 4; break;
                case 1: r |= v;
                case 2: g = v << 4; break;
                case 3: g |= v;
                case 4: b = v << 4; break;
                case 5: b |= v;
            }
            counter++;
            if (counter == 6) {
                counter = -1;
                analogWrite(3, r);
                analogWrite(5, g);
                analogWrite(6, b);
            }
        }
    }

The "clever" bit that may confuse you is:

    if (c > 0x39) c -= 7;
    uint8_t v = c & 0x0f;

That is, if the character is greater than a "9" (character 0x39) then it *should* be a-f. Subtracting 7 from it converts ASCII HEX from `0123456789ABCDEF` to `0123456789:;<=>?`.  If you then mask it with 0x0F you end up with a number between 0 and 15, or 0-F in hex.

The rest just takes each nibble and places it into the right half of the right colour variable.

body:
Since Majenko is convinced that using binary is far too complicated here's how to do it in binary sending 32 bits per color.

The start of strip marker is any 4 non-zero bytes in a row e.g 0x01010101

Each LED is then sent as four binary bytes: 0x00, 0xRR, 0xGG, 0xBB

In the unlikely event that a byte is lost in transmission then it will re-sync at the start of the next update, depending upon the pattern there is a fair chance that lost data will be noticed and the incorrect colors not get displayed on the strip.

    loop() {
      static color_t color;
      static int8_t counter = -1;
      static int ledIndex = 0;
      static bool aligned= false;

      if (Serial.available()) {
        if (aligned) {
        switch (counter) {
          case 0: color.r=Serial.read(); break;
          case 1: color.g=Serial.read(); break;
          case 2: color.b=Serial.read();
                  strip.SetPixelColor(ledIndex, color);
                  ledIndex++;
                  break;
          case 3: // first byte of next data, should always be 0
                  // only not 0 if we've lost a byte or want to restart the strip
                  if (Serial.read() != 0) {
                    aligned=false;
                    counter = 0;
                  } else
                    counter = -1;
                  break;
          default: break;
        }
        counter++;
      } else { // not aligned
        ledIndex = 0;
        if (Serial.read() != 0) // count non-zeros
          counter++;
        else {
          if (counter >= 4)     // had a start marker, next byte is r
            aligned = true;
          counter = 0;
        }
      }
    }

Is it worth doing it in binary? It gives a 50% decrease in RS232 data which if serial data rate is an issue will be a big help. It also gives a decrease in required calculations, if you look at the code there are virtually no mathematical operations beyond increasing counters.

Personally I prefer this method because it just seems more efficient and cleaner to transfer numbers as numbers rather than converting them to text and back but ultimately if you don't need every last bit of performance then it comes down to what you feel most comfortable with.


body:
I'm trying to control some RGB LEDs with ESP8266. I have built an HTML page to set the color and send the RGB color code to the ESP using HTTP get request. Everything works as expected. I just want to send an HTTP get request to the ESP and ask what the current color is. But after a couple of hours of searching and trying I don't know how to send data in response to get request, I just can send HTTP ok code. I'm using jquery to send get command as below

    $.get("http://192.168.4.1/rgb(120,50,60)", function(data,status){
        //I don't know how to send data fram ESP get it here.
    });

this is the corresponding ESP response code written in Arduini IDE

    WiFiClient client = server.available();
       if (client) {
      String req = client.readStringUntil('\r');
      client.print("HTTP/1.1 200 OK\r\n");
      client.print("Access-Control-Allow-Origin: *");
    .
    .
    .

This is the HTTP header, How do I send some data(text)?

title: How to send data in response to HTTP get request from ESP8266?

Answers: 1

body:
@Gerben answered my question in a comment all credit goes to him. I retype it here maybe it helps someone in the future.

I had to send two new line after setting up the header

    //header
    client.print("\r\n\r\n");
    clinet.print("Hello, I'm comming from ESP!!");

And in jQuery I get it like this:

    $.get("http://192.168.4.1/rgb(120,50,60)", function(data,status){
        var receivedData=data;  //=Hello, I'm comming from ESP!!
    });

It is simple but it may help some newbie like me.


body:
I spent an afternoon researching this, and read a lot of material, but with no successful results.  [I really thought this would be a trivial task.]

Is this problem Windows, or WIN10, specific, as the extended characters all seem non-displayable? Regardless, is there a solution?

title: How to display extended ASCII characters, e.g., the standard degree symbol, DEC 167, on the Serial Monitor [not LCD]?

Answers: 1

body:
The Arduino serial monitor uses UTF-8, per the discussion at http://forum.arduino.cc/index.php?topic=172814.0 --

For the U+00B0 degree symbol, you'd send the bytes UTF8 `0xC2 0xB0` like this:

    Serial.print("°");


body:
So I am trying to use [this](http://www.mouser.com/Search/m_ProductDetail.aspx?TE-Connectivity-Holsworthy/LT300014T2610KJ/&qs=HLeXuo0aL2oWuH78WH79GQ==) thermistor to measure temperature and with this code below it always puts the same value (2147483647).  I used [this](https://learn.adafruit.com/thermistor/using-a-thermistor) tutorial to do the wiring and coding.  I don't think the wiring is the problem but think the problem is somewhere in my code or perhaps I am using a wrong type of thermistor?  Am I missing something?  Any help is greatly appreciated.

I am only using a 1k resistor in series with the thermistor but don't think that would be a problem, right?

Edit: I should have mentioned I'm using the adafruit huzzah esp8266 so there are a few pins.

    #include <DHT.h>
    #include <ESP8266WiFi.h>
    #include <Phant.h>
    #include <ESP.h>

    #define DHTPIN 2
    #define DHTTYPE DHT22
    #define THERMISTORPIN 4

    DHT dht(DHTPIN, DHTTYPE);

    const char* ssid = "xxxx";
    const char* password = "yyyyyy";
    const char* host = "data.sparkfun.com";
    const String publickey = "uuuuuu";
    const String privatekey = "ttttttt";
    const byte NUM_FIELDS = 5;
    const String fieldNames[NUM_FIELDS] = {"ghumidity", "gtemp", "light", "otemp", "wtemp"};
    String fieldData[NUM_FIELDS];

    //thermistor variables
    const int thermresistor = 987; //value of resistor in series with thermistor
    int thermtemp = 0;
    uint8_t i;
    uint8_t numsamples = 5;
    uint8_t To = 25;
    const int B = 3950;

    void setup(){
        Serial.begin(115200);
        delay(10);
        WiFi.begin(ssid, password);

        while (WiFi.status() != WL_CONNECTED) {
      delay(500);
    }

        fieldData[0] = 1; //humidity
        fieldData[1] = 2; //garden temp
        fieldData[2] = 3; //light
        fieldData[3] = 4; //outside temp
        fieldData[4] = 8; //water temp

    //turnpumpon();
    posttophant();
    //turnpumpoff();
    ESP.deepSleep(1200000000, WAKE_RF_DEFAULT);

    }

    void posttophant()
    {
        fieldData[0] = dht.readHumidity();
        fieldData[1] = dht.readTemperature(true);

        //read outside temp (otemp) data and convert to a temp
        for (i=0; i<numsamples; i++){
          thermtemp = analogRead(THERMISTORPIN);
          thermtemp += thermtemp;
          delay(10);
        }

        //take the sum of all the readings and divide by # of samples to get avg.
        thermtemp = thermtemp / numsamples;

        #voltage divider equation
        thermtemp = thermresistor / (1023 / thermtemp - 1);

        //Steinhart eqn.
        thermtemp = 1 / (log(thermtemp / thermresistor) / B + (1 / (To + 273))) - 273;
        fieldData[3] = String(thermtemp);

        WiFiClient client;

        const int httpPort = 80;
    if (!client.connect (host, httpPort)){
      return;
    }

        client.print("POST /input/");
        client.print(publickey);
        client.print("?private_key=");
        client.print(privatekey);
        for (int i=0; i<NUM_FIELDS; i++)
        {
          client.print("&");
          client.print(fieldNames[i]);
          client.print("=");
          client.print(fieldData[i]);
        }
        client.println(" HTTP/1.1");
        client.print("Host: ");
        client.println(host);
        client.println("Connection: close");
        client.println();
    }

title: Help using thermistor with esp8266

Answers: 3

body:
**Considerations about the ESP8266 analog pin**

The ESP8266 has only one pin that allows analog read. This pin is call A0 on the NodeMCU module or A on the ESP8266 Huzzah (some other ESP module don't expose that pad - for example ESP8266-01) or might label it differently - check the documentation of your ESP module.
Following your edit: make sure that you connect your thermistor to the A pin of the Huzzah ESP8266 module.

You should keep in mind that this analog pin is a 10bit ADC with in principle limited input voltage range.

To read an external voltage applied to the ADC pin, use `analogRead(A0)`. Unless you are using a board specially design to increase its range, the input voltage range is 0 — 1.0V. As @dandavis pointed out some boards (Node MCU e.g.) include a voltage divider on board to give you a full 0 - 3.3V input range.

**Thermistor equations**

The datasheet of your thermistor states that the TCR coefficient is 3000ppm/%C and has a 10K value [note that the manufacturer doesn't provide you with the temperature at which R = 10K]. The equation of the resistance variation ∆R with temperature variation ∆T is given by:

`∆R = ∆T*10k*3000ppm = 30*∆T`

So if T_0 is the temperature where R = 10k, the equation of the resistance value is given by:

`R = 10k + (T-T_0)*30`

I am assuming that you are using the 3.3V supply of your ESP and creating a voltage divider using the 1K resistor and the thermistor.
There are two ways to do this divider:

*1. Voltage divider option 1*

<!-- 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/svVYG.png)

<!-- End schematic -->

[Note that the thermistor needs to be connected to the A pin of your ESP8266.]

 *2. Voltage divider option 2*

<!-- 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/a9gbQ.png)

<!-- End schematic -->

**Equation of voltage at node A**

For both case here is the voltage V_A seen at node A:

 *1. Voltage divider option 1*

`V_A = R_series *3.3 / (R_th + R_series)`

 *2. Voltage divider option 2*

`V_A = R_th *3.3 / (R_th + R_series)`

**Analysis of the variations of V_A with temperature**

Lets look at the difference between the 2 formulas above:

 *1. Voltage divider option 1*

The numerator is a constant with temperature while the denominator changes with T. You will get a strong variation.

 *2. Voltage divider option 2*

Both the numerator and denominator increase with temperature. You won't get a lot of variation on V_A with temperature. *You should avoid this configuration.*

**Analysis of the maximum allowed value of R_series**

The important consideration is that for your ESP module V_A cannot be higher than 1V.

 *1. Voltage divider option 1*

Increasing R_series will increase V_A so we compute a **maximum** value:
`1V = 3.3V*R_series_max/(R_series_max+10K)`

That gives you: `R_series_max = 4300Ohms`

 *2. Voltage divider option 2*

Increasing R_series will decrease V_A so we compute a **minimum** value:
`1V = 3.3V*10k/(R_series_min+10K)`

That gives you: `R_series_min = 23kOhms`

This is the reason why it was suggested to you using a 30k resistor in that case.

**Considerations about temperature measurement precision**

The voltage variation `∆V` on the node `A` of the ESP between temperature T1 and T2 can be computed as follow:
`∆V = 3.3 *1K/(1k + 10k + 30*T1) - 3.3 *1K/(1k +10k+ 30*T2)`

If we assume that the thermistor is 10K for ambient temperatures the baseline voltage measured on the `A` pin is:
`3.3V*1K/11k = 0.3V`

For a 0 to 1V 10bit DAC of the ESP8266 that is around: 2^10*0.3 = 307

A change of 10C would lead to a variation of voltage of:
`∆V = 0.3 - 3.3 *1K/(11k + 300) = 8mV ~8ADC code`

The equation of ∆T vs ∆V is not linear but for small variation of temperature with your current setup you get ~1ADC code per degree.

Depending of your application this might not be enough for you. As suggested in several comment you could:

 - Add more thermistors in parallel
 - Increase the 1K series resistor (but not too much or you will saturate the ADC).
 - Change the architecture of the measuring circuit (RC oscillator using the thermistor and interrupt counter in the ESP, 555 timer circuit loaded with the thermistor and interrupt counter, ...)
 - Or since you want to do humidity and temperature measurement why don't you get the BME280 module. It can be read over I2C and libraries are readily available to read it with the ESP8266.

body:
Re “the problem is somewhere in my code”, lots of places in the code have problems.

• The following loop does not add up readings; it takes a bunch of readings and throws them away, then doubles the last one.  For example, if the five readings in a row are 300, 400, 500, 600, and 100, `thermtemp` is 200 after the loop.  To see this, try it out – mentally simulate what the code does, writing down the value of `thermtemp` after each step.

    for (i=0; i<numsamples; i++) {
       thermtemp = analogRead(THERMISTORPIN);
       thermtemp += thermtemp;
       delay(10);
    }

• Your “voltage divider equation” (below) has a form like that shown in [the Adafruit tutorial](https://learn.adafruit.com/thermistor/using-a-thermistor), but because *your* `thermtemp` is declared as an `int` (vs Adafruit's `float`), integer division with truncation will be used, producing inaccuracy.

    thermtemp = thermresistor / (1023 / thermtemp - 1);

• Your Steinhart-Hart equation is miscoded.  At that step, the fixed resistor's value, `thermresistor`, is no longer relevant.  The relevant value is the ADC reading as converted to thermistor resistance.

• In your Steinhart-Hart misimplementation, `log(thermtemp / thermresistor)` takes log of zero because in integer arithmetic, `thermtemp / thermresistor` is zero.

• The expression `1 / (To + 273)` is zero in integer arithmetic.

body:
There are a few possible issues you're having:

First off, from what I understand, the ESP8266 ADC only reads up to 1V. If wired per the Arduino example you cited, and using 1K, you'll have VCC->1K->THERMISTOR->GND. At room temp the thermistor is 10K, so the voltage at the ADC will be 3.3*(10K/(1K+10K)), so pretty close to 3.3V. I don't know the behavior of the ADC when overrange, but I'd assume you'd just get 0xFFFF. You'll probably want >30K in series with the thermistor to get it into a usable range.

I also see a subtle error(I think) in your code:

    //read outside temp (otemp) data and convert to a temp
    for (i=0; i<numsamples; i++){
      thermtemp = analogRead(THERMISTORPIN);
      thermtemp += thermtemp;
      delay(10);
    }

Should be:

    //read outside temp (otemp) data and convert to a temp
    thermtemp = 0
    for (i=0; i<numsamples; i++){
      thermtemp += analogRead(THERMISTORPIN);
      delay(10);
    }

Otherwise thermtemp is just the last reading added to itself.

Lastly, I would probably make the part of the code that posts the result to a function and call it throughout your calculations of the temp, to see if anything weird happening.

Hope this helps.


body:
I am trying to set up an LCD screen without using a resistor or a potentiometer for an Arduino project. This is the LCD I am using: [Basic 20x4 Character LCD][1].

But when I connect to +5V on the Arduino board, my Arduino board turns off. This is how I have the LCD connected to the Arduino on a breadboard.

[![enter image description here][2]][2]

Connections:

LCD RS pin to digital pin 12

LCD Enable pin to digital pin 11

Data:

• LCD D4 pin to digital pin 5

• LCD D5 pin to digital pin 4

• LCD D6 pin to digital pin 3

• LCD D7 pin to digital pin 2

LCD R/W pin to ground

LCD VSS pin to ground

LCD Cathode pin to ground

LCD Anode pin to digital pin 9

LCD VCC pin to 5V

Code:

    // include the library code:
    include <LiquidCrystal.h>
    // initialize the library with the numbers of the interface pins
    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

    void setup() {
      analogWrite(6,20);
      // set up the LCD's number of columns and rows:
      lcd.begin(20, 4);
      // Print a message to the LCD.
      lcd.print("hello, world!");
    }

    void loop() {
      // set the cursor to column 0, line 1
      // (note: line 1 is the second row, since counting begins with 0):
      lcd.setCursor(0, 1);
      // print the number of seconds since reset:
      lcd.print(millis() / 1000);
    }

  [1]: https://www.sparkfun.com/products/256
  [2]: https://i.stack.imgur.com/vtHxq.jpg

title: Arduino board is turning off when I connect to +5V

Answers: 2

body:
Try out this connection. It will helpful.

[![LCD Connection][1]][1]

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

body:
Looking at your picture, it seems that you're powering everything through a USB cable. USB 1.x and 2.0 can supply up to to 500 mA **AFTER** the port is enumerated, otherwise the current is limited to 100 mA.

A quick current consumption budget:

 - LED backlight of your LCD module: typ **240 mA**
 - Arduino Mega2560: min **70 mA**
 - MIDI shield: some **15-35 mA**

That's just 325-350 mA to begin with, and probably higher than that. It's still safely within the 500 mA limit, but as I said some computers will provide 500 mA only after successful enumeration of the device connected to the USB port.

My recommendation for you would be to power your Arduino + MIDI shield + LCD through a wall adapter > 7V. If it works, then the problem is your USB port being unable to supply the required current right from the start.


body:
Can I burn my Arduino Code into this:

http://www.microchip.com/wwwproducts/en/ATSAM3A4C

or something similar by just using just the Arduino ISP?

title: Programming Micro controllers using Arduino ISP

Answers: 2

body:
Page does nog exist (404).

Also, to run actual Arduino code on it, you'll most likely have to port the Arduino library, if this hasn't been done before.

You may opt for something as easy as a teensy 3.2, they probably meet your requirements and work well in combination with Arduino.
Or fetch one of the newer Arduino models that have comparable microcontrollers

If you still want an M3 (without development board?) you'll be entering a somewhat advanced usecase, in which you probably don't even want to rely on or use Arduino. There are far better IDE's.

body: I don't know about that chip I think this one also can be done as some of the other chips can be programmed using the Arduino ISP  I think it can be even done for this one. This [one](http://www.ladyada.net/learn/avr/programming.html) uses an AVR ISP Programmer while we are using the Arduino one but as they have similar working It is maybe possible. For example this [one](http://www.ladyada.net/learn/avr/programming.html)