message:
Pushing sketches to pro mini with Uno 101

So I just bought a Pro Mini the other day, however, I didn't get an FTDI cable or a USB/Serial converter board.
From what I understand from this [article][1] I can use my Arduino Uno 101 to push sketches onto the Pro Mini.

The wires are all hooked up (grounded reset on the Uno) and I have uploaded the sketch to disable the serial communication port on the Uno, however, when I try to push a sketch to the Mini it errors out with the following message

    Arduino: 1.8.3 (Windows Store 1.8.6.0) (Windows 10), Board: "Arduino Pro or Pro Mini,
    ATmega328 (5V, 16 MHz)"

    Sketch uses 928 bytes (3%) of program storage space. Maximum is 30720 bytes.
    Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for
    local variables. Maximum is 2048 bytes.
    avrdude: ser_open(): can't open device "\\.\COM3": The system cannot find the
    file specified.

    Problem uploading to board.
    See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

    This report would have more information with
    "Show verbose output during compilation"
    option enabled in File -> Preferences.

The only part of the suggested troubleshooting guide that maybe applicable is the drivers section.

>Drivers
>
>The Arduino Uno and Mega 2560 use standard drivers (USB CDC) provided by the operating system to communicate with the ATmega8U2 on the board. Other Arduino boards use FTDI drivers to communicate with the FTDI chip on the board (or in the USB-serial convertor).

I could be wrong but to me it doesn't seem like the second sentence applies to this situation since the the Uno sits between the pc and the mini. However, when I check the windows device manager I can see that the Uno is connected on a COM port, but nothing about the Mini. Though I am not sure that it should show up.

I am using the IDE(1.8.3) to program and "Arduino Pro or Pro Mini" as the board. Though Tools>Port is greyed out when I have this board selected.

[1]: http://www.instructables.com/id/Uploading-sketches-to-Pro-Mini-using-Arduino-UNO-b/

body:
There is no "Arduino Uno 101" there are only ["Arduino Uno"][1] and ["Arduino 101"][2].

101 uses completely different hardware, and tricks to use an Uno as an USB to UART adapter won't work on an 101.

101 has also separate serial interfaces for USB serial (`Serial`) and hardware serial (`Serial1`).

If you have have an Arduino 101 you can solve this by software means.
The board needs to be able to change the baud rate and use DTR for reset.

There is a [sketch from PaulStoffregen][3] on GitHub that does that.

    /* USB to Serial - Teensy becomes a USB to Serial converter
       http://dorkbotpdx.org/blog/paul/teensy_as_benito_at_57600_baud

       You must select Serial from the "Tools > USB Type" menu

       This example code is in the public domain.
    */

    // set this to the hardware serial port you wish to use
    #define HWSERIAL Serial1

    unsigned long baud = 19200;
    const int reset_pin = 4;
    const int led_pin = 13;  // 13 = Teensy 3.X & LC
                             // 11 = Teensy 2.0
                             //  6 = Teensy++ 2.0
    void setup()
    {
      pinMode(led_pin, OUTPUT);
      digitalWrite(led_pin, LOW);
      digitalWrite(reset_pin, HIGH);
      pinMode(reset_pin, OUTPUT);
      Serial.begin(baud);       // USB, communication to PC or Mac
      HWSERIAL.begin(baud);     // communication to hardware serial
    }

    long led_on_time=0;
    byte buffer[80];
    unsigned char prev_dtr = 0;

    void loop()
    {
      unsigned char dtr;
      int rd, wr, n;

      // check if any data has arrived on the USB virtual serial port
      rd = Serial.available();
      if (rd > 0) {
        // check if the hardware serial port is ready to transmit
        wr = HWSERIAL.availableForWrite();
        if (wr > 0) {
          // compute how much data to move, the smallest
          // of rd, wr and the buffer size
          if (rd > wr) rd = wr;
          if (rd > 80) rd = 80;
          // read data from the USB port
          n = Serial.readBytes((char *)buffer, rd);
          // write it to the hardware serial port
          HWSERIAL.write(buffer, n);
          // turn on the LED to indicate activity
          digitalWrite(led_pin, HIGH);
          led_on_time = millis();
        }
      }

      // check if any data has arrived on the hardware serial port
      rd = HWSERIAL.available();
      if (rd > 0) {
        // check if the USB virtual serial port is ready to transmit
        wr = Serial.availableForWrite();
        if (wr > 0) {
          // compute how much data to move, the smallest
          // of rd, wr and the buffer size
          if (rd > wr) rd = wr;
          if (rd > 80) rd = 80;
          // read data from the hardware serial port
          n = HWSERIAL.readBytes((char *)buffer, rd);
          // write it to the USB port
          Serial.write(buffer, n);
          // turn on the LED to indicate activity
          digitalWrite(led_pin, HIGH);
          led_on_time = millis();
        }
      }

      // check if the USB virtual serial port has raised DTR
      dtr = Serial.dtr();
      if (dtr && !prev_dtr) {
        digitalWrite(reset_pin, LOW);
        delayMicroseconds(250);
        digitalWrite(reset_pin, HIGH);
      }
      prev_dtr = dtr;

      // if the LED has been left on without more activity, turn it off
      if (millis() - led_on_time > 3) {
        digitalWrite(led_pin, LOW);
      }

      // check if the USB virtual serial wants a new baud rate
      if (Serial.baud() != baud) {
        baud = Serial.baud();
        if (baud == 57600) {
          // This ugly hack is necessary for talking
          // to the arduino bootloader, which actually
          // communicates at 58824 baud (+2.1% error).
          // Teensyduino will configure the UART for
          // the closest baud rate, which is 57143
          // baud (-0.8% error).  Serial communication
          // can tolerate about 2.5% error, so the
          // combined error is too large.  Simply
          // setting the baud rate to the same as
          // arduino's actual baud rate works.
          HWSERIAL.begin(58824);
        } else {
          HWSERIAL.begin(baud);
        }
      }
    }

Then you need to connect:

<!-- language: none -->

    Arduino 101  |  Arduino Pro Mini
    -------------+------------------
    VCC          |  VCC
    GND          |  GND
    TX           |  RX
    RX           |  TX
    PIN 4        |  DTR

After that you can use the port as a Arduino Pro Mini programmer.

  [1]: https://www.arduino.cc/en/Main/ArduinoBoardUno
  [2]: https://www.arduino.cc/en/Main/ArduinoBoard101
  [3]: https://github.com/arduino/Arduino/pull/3343#issuecomment-115045979


sender: user

message:
Trying to map a room with Arduino controlled bot

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

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

What you see above is a map of my room. The boxes in black are obstacles and the box in red is my bot.

Now I want my bot to go around the room, avoiding all obstacles, but at the same time, covering the entire floor. Think of it like the robot is painting the floor and it has to paint the entire floor avoiding all obstacles.

Now my first approach was to put 3 HC-SR ultrasonic sensors on 3 sides and listen to them in a sequence, deciding which path is best and then going there. But this method leaves out quite a lot of floor area uncovered.

So how can I cover the entire floor area here?
 Presently I am working with Arduino UNO and HC-SR04 but wouldn't hesitate to throw my Pi3 or a few more sensors in there...-

sender: assistant

body:
This is actually quite a complex thing to achieve. I'll give some suggestions, though this is not something I have attempted (yet).

The main thing to do is divide the room up into a grid. The resolution you choose (X and Y dimensions) depends on how small your robot is, how big the room is, and how much memory your have available (on an Uno that's not much at all).

The second thing you need to do is work out a way of determining exactly where in the room you are. That could be done by trying to get as close to the bottom-left corner as possible before starting to map.

Now you can work from square to square (you could do with some encoders to know how far you have driven, and a magnetometer so you know which direction you are facing) using whatever method you like to decide which way to go, and in each square you look to see which of the squares around you are accessible. From that you can work out which way you can go from that square.

As you go you maintain a map in memory of all the squares you have been to, and the squares that you cannot get to. Note that it may not be enough to say "You can't get to square 4,3" - instead you may to keep a more detailed list (depending on what your obstacles are). "You can't get to square 4,3 from square 4,2, nor 3,3, but you can get to it from square 5,3" for example (e.g., a thin obstacle that only blocks entry to that square from certain sides).

Since your sensors cover longer ranges than just one square (unless you have big squares) you can work out how far away an obstacle is, and mark the square it's in before you even get close to it. The square immediately preceding it on a path between it and you would be the "you can't get there from here" square.

Now you can work out paths and routes to get to the squares you need to so you can cover all the available floor.


message:
Avoid a Pro Micro waking up a PC?

I have an Arduino Pro Micro mimicking as a HID, connected to a PC.

The PC BIOS is configured to wake from keyboard events - it is switched on by hitting a key on the regular keyboard. This is a wanted feature and should stay.

Unfortunately, it also wakes when the Arduino sends HID events, which is understandable and pretty obvious, but to be avoided.

Is there something in the USB protocoll, or even in the Arduino HID libraries, that lets me tell the chip to either not wake up the host (unlikely, I guess); or so that I can detect when the PC has shut down, so I can tell the Arduino to go sleeping as well until the PC wakes up again?

EDIT: I am using the "HID-project" USB library (HID 2.4.3) from https://github.com/NicoHood/HID.

body: Assuming you are using windows, on the device manager you can access each device's properties (power management tab), where you can allow or not each device to wake your system up.


body:
Check your BIOS for an option to wake up on a particular key combination, rather than "any key".

Another option is to configure a particular USB port to be powered down when the computer is asleep (or discover which ports are powered down if no such option is available). If that doesn't help, you can try to put a USB hub between the Arduino and the PC: many hubs don't cope with sleep modes very well, so there's a chance they won't re-transmit anything your Arduino is sending unless the PC wakes up. If your computer has USB3, you can try a USB3 hub, which has an even higher chance of exhibiting this behavior since BIOS often lacks USB3 hub support.


message:
Error using Crypto Library for Arduino: Speck

I'm trying to encrypt a string in my Arduino Uno using the following library:

https://github.com/rweather/arduinolibs/tree/master/libraries/Crypto

And I'm getting this error:

> In function 'void setup()':
>
> TESTING_SPECK_LIB:27: error: request for member 'setKey' in
> '*(byte*)(& cipher)', which is of non-class type 'byte {aka unsigned
> char}'
>
>    cipher->setKey(*key,keySize);
>
> exit status 1 request for member 'setKey' in '*(byte*)(& cipher)',
> which is of non-class type 'byte {aka unsigned char}'

This is the code I'm using:

    #include <Crypto.h>
    #include <Speck.h>
    #include <SpeckSmall.h>
    #include <SpeckTiny.h>
    #include <string.h>

    Speck speck;
    SpeckSmall speckSmall;
    SpeckTiny speckTiny;

    byte buffer[16];
    byte cipher[16];
    size_t keySize = 32;

    void setup() {

      const uint8_t key[32]={0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08,
                        0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00};
      byte plaintext[16]={0x6c, 0x61, 0x76, 0x69, 0x75, 0x71, 0x65, 0x20,
                        0x74, 0x69, 0x20, 0x65, 0x64, 0x61, 0x6d, 0x20};
      byte ciphertext[16]={0xa6, 0x5d, 0x98, 0x51, 0x79, 0x78, 0x32, 0x65,
                        0x78, 0x60, 0xfe, 0xdf, 0x5c, 0x57, 0x0d, 0x18};

      Serial.begin(9600);

      cipher->setKey(*key,keySize);
      cipher->encryptBlock(buffer, plaintext);

    }

    void loop() {

    }

I know that I'm doing something wrong, but I don't understand what the error means, someone knows what it means and how to fix it?

body:
`byte cipher[16];` declares `cipher` as an array of 16 bytes.  As such, `cipher` has no methods, much less ones called `setKey()` or `encryptBlock()`.

Note, `setKey()` and `encryptBlock()` look like method names one would find in `Crypto` or `Speck` library code; however, I don't find them in the `Crypto` and `Speck` headers I looked at on github sites.  Also, `buffer`, `cipher`, and `keySize` look like variables and parameters one would use in creating an object for use with encryption methods.

In short, it appears your code fails to set up an appropriate class of objects that have `setKey()` and `encryptBlock()` methods.

Note, while I am not familiar with their details, I question whether all of the header files `Speck.h`, `SpeckSmall.h`, and `SpeckTiny.h` should be included in your code.  It seems more likely that you would choose one of them as appropriate to your needs.

---

*Edit 1:*  Looking at [`TestSpeck.ino`](https://github.com/rweather/arduinolibs/blob/master/libraries/Crypto/examples/TestSpeck/TestSpeck.ino) as mentioned in `per1234 6`'s comment, one sees a function `perfCipher()`, with its first argument declared as `BlockCipher *cipher`.  That is, `cipher` is declared as an object of a class that has `setKey()` and `encryptBlock()` methods.

The `TestSpeck.ino` sketch includes all three of the header files `Speck.h`, `SpeckSmall.h`, and `SpeckTiny.h` because it runs performance tests that compare results using different `Speck` implementations.  In practice you usually won't need more than one of those headers.


message:
Arduino autorestarts when powered externally

I'm trying to finish  building an alarm system with relays, leds  and bluetooth. I finally made it working but when externally powered (12v source) after about 10 seconds it starts to reboot continuously.
This issue comes with no pc connection.

body:
https://www.arduino.cc/en/Main/ArduinoBoardUno

Majenko has a good lead,

12V is just within spec of the voltage regulator.

Though this may be different per manufacturer or different in your environment.

To battle overheating you can:

- Create beter airflow

- Add a heatsink

- Draw less current

But you should try a 9V source, that can deliver enough current (not the 9V "block" batteries).

Also check if the system draws excessive current, maybe the circuit has a low resistance or power hungry part (on the 5V rail)

If nothing works, you could try and use another Arduino board, maybe the regulator is faulty/damaged.


message:
No code, but Fatal exception (0): epc1=0x402066ac, epc2=0x00000000, epc3=0x00000000, excvaddr=0x00000000, depc=0x00000000 in Serial Monitor

I have a Wemos d1 mini, and when I upload nothing or anything to it, the built-in LED always lights up and the serial monitor gets a lot of garbage at every baudrate.  I have supplied it with 4 AA batteries and the board has a built in voltage regulator of 3.3V at the 5V pin.  [![enter image description here][1]][1]

The Wemos d1 mini contains the esp8266 chip.

Please help me!  I have searched everywhere.  This just happened all of a sudden, the board was working perfectly fine before too.

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

body:
Three words.  "You Bricked it"
Before you go surfing on the web for days and days, I'm just going to say the module is bricked.  I've been there and found out that you should never use these devices on breadboards and with funky power sources.  There is this chip within the module called **eFuse**,  which is basically an electronic fuse that's really easy to destroy.  Just use the Arduino YUN or other certified or Chinese clonable modules. Those Italians are smarter than you think. That's probably more reliable because you won't have any power issues or frying issues.

I'm also assuming that you are getting a fatal exception (0) in the Serial Monitor.  In that case, your module's death sentence is officially sealed.

Congrats. :(


message:
Accidentally plugged in Arduino Uno before installing software, now it's not recognized by Windows 10, only powered by usb port

Just got a new Arduino Uno, accidentally plugged it in before installing the IDE and windows installed its drivers and had it under ports as a generic device on COM3 (it wasn't named Arduino Uno on device manager).

When I installed the IDE, I couldn't upload sketches to the board because it wasn't recognized. So I uninstalled the device from device manager and also the IDE. I pressed the reset button on the Uno, restarted my PC, reinstalled the IDE, then plugged in the Uno. Since then however, the device isn't read by Windows at all; device manager doesn't show it anywhere, nor does it even refresh when plugged in.

I tried this restarting/reinstalling process multiple times, it's also not a cable issue because I checked for that as well. The power LED is still on, and the pin 13 LED is blinking, but the Arduino isn't being recognized.

I've also tried using the Hardware Install Wizard, but that gives me

> This Device Cannot Start (Code 10)

 I've been trying to run this for a while now.

body:
You do not need to install drivers in Windows 10 (unless you have a CH340G based Chinese clone, in which case it wouldn't have detected before installing the drivers).

Windows 10 has its own CDC/ACM drivers built in - something every other operating system has had for years and Windows has only just caught up with them. That is why it detected COM3 fine before.

It should have worked fine without installing drivers. It may have been the IDE with the wrong port selected or something else interfering with the port that was stopping you using it.

Uninstall the Arduino drivers and revert to using the Windows built-in ones and work on diagnosing why it wasn't working with those.


body: You can always remove a unknown device in device manager (yellow exclamation point), reinstall the software, then plug the device in.


body: If you go to device manager and right-click the Arduino (it will probably have a yellow exclamation mark next to it). You can click update drivers. This fixed the problem for me.


message:
How to read Negative number with serial.read

how i can read negative number with command Serial.read()?
beacouse i with  this

        char tmpChar = Serial.read(); //read incoming character from serial port
        if (isDigit(tmpChar)) { //check if the in character it's a number
            setpoint =  (setpoint  * 10 ) + tmpChar - '0'; // convert from ascii code to it's corresponding number; '0' == DEC 48
          }
    if (tmpChar == '\n' || tmpChar == '\r') { //if CR or LF was received
        if (setpoint > 0) {
          tmpChar = "";
          Serial.print(setpoint);
          Serial.println(" NUMERO STEP IN AVANTI");

        }

im using an encoder motor, i want to move for N steps the motor forward (positive number) or backward (negative number) , i insert the number of step in serial input

i can read only positive number. Thanks for help

how suggest Majenko i made a partial solution :

    char buf[8];
    int valore = 0;

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
    }

    void loop() {
      if (Serial.available() >= 8) {
        for (int i = 0; i < 8; i++) {
          buf[i] = Serial.read();

        }
        String str();
        if (buf[0] == "-") {
          valore = (atoi(buf)) * -1;
          Serial.println(valore);

        }
        else {
          valore =  atoi(buf);
          Serial.println(valore);
        }
      }
    }

but the problem now it's the static array ,
unpleasant to use

body:
You could do something like this:

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

    static int setpoint;      // the partially read setpoint
    static bool isNegative;   // whether it should be negative
    void applySetpoint(int);  // apply the setpoint when fully read

    char tmpChar = Serial.read();
    if (isDigit(tmpChar)) {
        setpoint =  (setpoint  * 10 ) + tmpChar - '0';
    } else if (tmpChar == '-') {  // minus sign
        isNegative = true;
    } else if (tmpChar == '\r') {  // line terminator
        if (isNegative) {
            setpoint = -setpoint;
            isNegative = false;  // reset for next read
        }
        applySetpoint(setpoint);
    }

Note that this is not very robust: it will happily interpret "3-2" as
meaning "-32". Note also that I assumed your terminator to be '\r', you
may be using another one.


body:
The [`parseInt`][1] can read negative numbers (I think it does, the reference is very cryptic). The `parseInt` has a [`timeout`][2] so it does not wait forever.

Can you tell what kind of data you are reading ? Is it part of more data ?

  [1]: https://www.arduino.cc/en/Reference/ParseInt
  [2]: https://www.arduino.cc/en/Serial/SetTimeout


body:
Personally I would read the data into a char array then use either `atoi()` or `strtol()` to convert that char array into a number.

Using those functions is more robust that parsing the data yourself since they identify where the number ends and discards any trailing garbage. It also skips any white space before the number. For instance it will interpret all these as the number `-32`: `"     -32"`, `"-32 Degrees"`, `"   -32+4  "` and `"-32-2"`.

`strtol()` has the additional advantage that it can work in other bases than 10, so you could interpret hexadecimal data, binary data, sexagesimal data, etc.

`atoi()` and `strtol()` are standard C functions.

E.g.:

    int val = atoi(mycharbuffer);

or

    long val = strtol(mycharbuffer, NULL, 10);


message:
How to pulse a signal at 100ms to 500ms?

Based on [this PDF](http://img.banggood.com/file/products/20150922040956Joyhonest 2210M Camera datasheet from Wind.pdf) I need to pulse between 100ms and 500ms to record a video (the description is apparently wrong according to [this guy](https://www.youtube.com/watch?v=SyYe1y7kBek&ab_channel=Vortecks)). How would I generate such a pulse? The small module has 3 wires I can use, which are positive, ground, and a yellow wire. I assume I need to pulse the yellow wire.

I don't want to hook anything up wrong, but my guess would be using [`pulseIn()`](https://www.arduino.cc/en/Reference/PulseIn). However, I am not sure at all. Any help appreciated.

body:
Okay, so pulsing is apparently easy enough. If I just do:

    digitalWrite(13, HIGH);
    delay(1000);
    digitalWrite(13, LOW);
    delay(1000);

It will start recording, then turn off about a second later, start again about a second later, and then repeat. I somehow managed to get a 5 second recording as well. I'm not really sure how this is supposed to work. I need to test some more.

EDIT: Turns out the schematics were right. If I do something as simple as:

    digitalWrite(13, HIGH);
    delay(500);
    digitalWrite(13, LOW);
    delay(1000);

It will turn on the video recording and turn off whenever it gets HIGH again.


message:
Where to declare timer interrupt variables?

I have a situation where the majority of the code is residing inside timer interrupt functions.

Setup() does what it has, loop() basically reads ADCs and then all the code is inside timer interrupts.

    void loop()
    {
      //Read the ADCs
      while((ADC->ADC_ISR & 0x1CC0)!=0x1CC0);   // wait for ADC 0, 1, 8, 9, 10 conversion complete.
      in_ADC0=ADC->ADC_CDR[7];               // read data from ADC0
      in_ADC1=ADC->ADC_CDR[6];               // read data from ADC1
      POT0=ADC->ADC_CDR[10];                   // read data from ADC8
      POT1=ADC->ADC_CDR[11];                    // read data from ADC9
      POT2=ADC->ADC_CDR[12];                    // read data from ADC10
    }

    void TC4_Handler()
    {
     if (effect==0)       {/*HERE THE CODE FOR EFFECT 0*/}
      else if (effect==1)  {/*HERE THE CODE FOR EFFECT 1*/}
        else if (effect==2){/*HERE THE CODE FOR EFFECT 2*/}
          else             {/*HERE THE CODE FOR EFFECT 3*/}

      // We need to get the status to clear it and allow the interrupt to fire again
      TC_GetStatus(TC1, 1);
    }

The user selects the effect he wants via a button and a hardware interrupt.

What happens when the timer interrupt function ends? Do we go back to loop(), or the timer function is re-run?
In this example, all the vars needed inside each functino of the timer interrupt are declared globally.

I was considering if i can declare variables inside each function in the Timer Interrupt function.
Therefore, we would save space, by not declaring variables that are not run at the moment. And we would only initialize variables for the effect we want.

Is this possible? Because if the effect i have just selected just re-loops, maybe its not wise for vars to get re-initialized  (and their values re-set) each and every time it is looped.

So ultimately, variables taht will be used inside a timer interrupt function, globally or locally?

body: If they are only used in the interrupt then yes they can be declared in the interrupt. If you want them to retain their value from one call to another they must be declared `static`, and then they will be the same as global variables as far as memory allocation is concerned.


message:
How to create a library from scratch?

Good morning. I have a problem that I hope you understand. I'm trying to create a library from scratch. I've read and watched most videos and documentation that are on the internet. I can not understand and I'm not able to make one.

I hope someone can help me create a library that only shows a message that says "Hello World" in the serial port and give me the code if they are so kind. Also, it would be good if they could explain it to me.

I insist I know of many programming languages and realize this has made me a problem. I just need the code of the 3 parts so I can analyze it and understand it. I wait for your help.

body:
A simple example...

Create a folder named My_Library, and place it in the Arduino/libraries folder

Create a sketch named My_Library.h and add the following:

    #ifndef __My_Library_H__
    #define __My_Library_H__
    #include "Arduino.h"

    //example 1
    #define myhello1() ( { \
       Serial.println(F("Hello World"); \
    Serial.println(F("Hello World again"); \
    } )

    //example2
    void myhello2() {
     Serial.println(F("another Hello World");
    Serial.println(F("another Hello World again");
    }

    #endif

Place the the sketch in the "My_Library" folder

In the beginning of your sketch, add

    #include <My_Library.h>

Then, wherever you want, add the following:

    //example 1
    myhello1();

    //example2
    myhello2();

I have not tested the above, but it should work fine.  Regardless, this gives you a reasonable starting point.

For your last question concerning word colour, research "Arduino Libraries" regarding the "keywords.txt" file.


message:
Simple 2 Servo Synch

I have two servos connected to an Arduino, They work fine if i write to them one by one so the wiring is all correct. I have seen a lot of examples here but none are facing the same issue. I have a simple for loop with Servo.write() on two servos (Facing each other) one going clockwise and the other going counterclockwise. I just want them to rotate at the same time and i cannot connect them to the same signal line since their movement is opposite.
My Code Is:

     for(int pos = 0; pos < 90; pos += 2)
     {
         delay(200);
         int pos7 = 90-pos;
         pos7 = pos7*(-1);
         myservo6.write(pos);
         myservo7.write(pos7);
     }

**What Is Happening**
Both the servos go to the "same position" (if one is at 90 the other is at 0 etc.. ) Yet one goes there slow and the other goes super fast(not affected by delay). Even though my delay should affect both servos.

If i remove the delay they both go to the same position yet very fast. **What i need is for them to move together slowly to the position.**

body:
The Arduino Servo class is intended to accept *positive* values only, in the range of 0-180.

In addition to reversing the values for one servo by subtracting from 90, your code is also negating the values by multiplying by negative one.

That results in an invalid argument to the Servo function.  It's unclear exactly what happens, but likely possibilities include an invalid pulse, or no pulse at all.

At the end of your for loop, you subtract 90 from 90 producing zero, and invert it to still zero.  Zero is a valid input to the Servo function, so a valid output is produced and the "reversed" servo finally has a position it can seek to.


message:
Communicating with I2C DAC (LTC2631)

Firstly, let me say that I'm new to using I2C devices, especially with Arduino. I have an 8-bit DAC (LTC2631) that I'm trying to control with an Arduino Uno. I thought I would be able to use the standard Wire library protocol to talk to it, but I'm not getting any response. Here's what I've tried:

    #include <Wire.h>

    void setup() {

        Wire.begin();
    }

    void loop() {
        Wire.beginTransmission(0x11); //specify device's address

        Wire.write(150); //send a test value

        Wire.endTransmission();
    }

Am I missing something obvious? Or are not all I2C devices compatible with  Wire?

body:
Software:  Wire should be fine.  Of course, you usually will want libraries for each device.  This particular ADC is designed for automotive use and I could not find a specific library for it so you are correct that you will need to speak with it directly.  Here is the [DATASHEET][1]

I2C Hardware:  On the Arduino Uno, SDA is A4 and SCL is A5.

One thing you almost always have to do with I2C is to provide a 10K pull-up to +5 on each pin (SDA and SCL) - I use a small breadboard whenever I use I2C, so I have power, ground, A4 and A5 available for pullups and multiple devices.

The reason for this is that the I2C bus is active-low.   It signals by pulling the pins low in sequence to communicate.

If you already had the DS3231 RTC module on the same bus, which apparently you do not or you would not be asking this question, then you do not need your own pull-ups because the RTC includes them internally.

--------

It might be easier for you to use a different I2C ADC such as the [ADS1115][2].

Here is a generic search that shows the module:

https://smile.amazon.com/s/ref=nb_sb_noss_2?url=search-alias=aps&field-keywords=i2c+adc[![enter image description here][3]][3]

Here is a generic search which shows the software side:

https://www.google.com/search?q=arduino+ads1115+ADC+library+download

  [1]: http://www.linear.com/product/LTC2631
  [2]: https://learn.adafruit.com/raspberry-pi-analog-to-digital-converters/ads1015-slash-ads1115
  [3]: https://i.stack.imgur.com/gfqt3.jpg


message:
Hardware interrupts for buttons not directly assigned to pins

The Adafruit LCD shield offers an LCD and access to 4 button, using only a two wire connection with the Arduino.
This is achieved with the MCP23017 I2C port expander IC.

These buttons are not directly assigned to pins, since only two pins are required for the whole communication, via the I2C protocol.

Can i use a hardware interrupt with any of the 4 buttons?
If not, is there any workaround to trigger an interrupt when one of these buttons is pressed?

PS: I am using Arduino Due

body:
No, you can not while keeping the shield intact but it's possible I think.

https://learn.adafruit.com/rgb-lcd-shield/downloads

Here if you see the schematic and fabrication print, you will see that buttons are connected to MCP23017 I/O port. Now if you can connect to the MCP23017 pin corresponding to button you may detect the voltage change. This can be used to trigger interrupt.


body: The MCP23017 has two interrupt outputs. The Adafruit shield however doesn't bring out either of those two pins. You could solder a wire between one of these pins and one of the unused arduino-header pins.


message:
Using ESP8266 to send email. However "HELO" responds with "ERROR". Possible cause?

I am developing a sketch that uses an Uno and an ESP8266 to send email via smtp2go.  However "HELO" responds with "ERROR".  What might be the source of the problem?

To explore this, I created another sketch that simply sends commands to the ESP8266, and displays the results.
The wifi connection seems fine, as does the SMTP Server connect to mail.smtp2go.com.
However, the next command issued "HELO 10.1.0.35" provides a response of "ERROR".

The ESP8266 is  mounted on an ESP-01 board, and set @ 9600 baud.  have tested with different chip sets.
I have also tried using Gmail [smtp.gmail.com,465 ], but results are the same.

[I know that an ESP8266 can be used stand-alone.  However the final sketch requires 13 data pins.]

Output from sketch:

    "ESP8266_ATcmdtest", compiled on: Jun  8 2017 at 17:58:18
    Running on: Arduino UNO: ATmega328P

    __________[ Disable echo (Echo sends back received command before response) ]__________
    __________[ ATE0 ]__________
    Response buffer:
    OK

    __________[ Delete server ]__________
    __________[ AT+CIPSERVER=0 ]__________
    Response buffer:
    no change
    OK

    __________[ Restart the module ]__________
    __________[ AT+RST ]__________
    Response buffer:
    OK
    0,CLOSED
    WIFI DISCONNECT
    bB׆QR⸮⸮⸮ȤRN⸮ɥRL⸮H⸮⸮N⸮⸮d#@⸮⸮
    WIFI CONNECTED

    __________[ Check Firmware type [Responds with: AT version:1.2.0.0(Jul  1 2016 20:04:45) ]__________
    __________[ AT+GMR ]__________
    Response buffer:
    AT+GMR
    AT version:1.2.0.0(Jul  1 2016 20:04:45)
    SDK version:WIFI GOT IP

    __________[ Lists available APs ]__________
    __________[ AT+CWLAP ]__________
    Response buffer:
    AT+CWLAP

    +CWLAP:(0,"KCTcircuit2",-47,"08:bd:43:ff:6a:0c",1,21,0)
    +CWLAP:(3,"49KHC",-88,"70:f1:96:66:29:ef",1,11,0)
    +CWLAP:(3,"KCTstudy",-49,"04:a1:51:bf:6b:30",5,-11,0)
    +CWLAP:(3,"Linksys05761",-75,"b4:75:0
    e:64:54:b1",11,21,0)
    +CWLAP:(3,"Pccd_main",-91,"14:91:82:83:f8

    __________[ Get local IP address, e.g., 192.168.4.1 ]__________
    __________[ AT+CIFSR ]__________
    Response buffer:
    AT+CIFSR
    +CIFSR:STAIP,"10.0.0.4"
    +CIFSR:STAMAC,"5c:cf:7f:34:

    __________[ Set Station mode ]__________
    __________[ AT+CWMODE=1 ]__________
    Response buffer:
    AT+CWMODE=1
    OK

    __________[ Set current multiplex mode ]__________
    __________[ AT+CIPMUX=1 ]__________
    Response buffer:
    AT+CIPMUX=1

    OK

    __________[ Connect to AP ]__________
    __________[ AT+CWJAP="KCTstudy","[pw redacted]" ]__________
    Response buffer:
    AT+CWJAP="KCTstudy","[pw redacted]"
    WIFI DISCONNECT
    WIFI CONNECTED

    __________[ Prints the SSID of Access Point ESP8266 is connected to. ]__________
    __________[ AT+CWJAP? ]__________
    Response buffer:
    AT+CWJAP?
    busy p...
    WIFI GOT IP

    OK

    __________[ Get IP address of ESP8266 station, e.g., 10.0.0.4 ]__________
    __________[ AT+CIPSTA? ]__________
    Response buffer:
    AT+CIPSTA?
    +CIPSTA:ip:"10.0.0.4"
    +CIPSTA:gateway:"10.0.0.1"

    __________[ SMTPServer connect ]__________
    __________[ AT+CIPSTART=0,"TCP","mail.smtp2go.com",2525 ]__________
    Response buffer:
    AT+CIPSTART=0,"TCP","mail.smtp2go.com",2525
    0,CONNECT

    OK

    +IPD,0,70:220 mail.smtp2go.com ESMTP Exim 4.87 Fri, 09 Jun 2017 00:59:07 +0000

    __________[ Get information about connection ]__________
    Response format  is:
    STATUS:stat [ 2: Got IP, 3: Connected, 4: Disconnected]
    +CIPSTATUS:id,type,addr,port,tetype [type: TCP, addr: IP address]
    OK
    __________[ AT+CIPSTATUS ]__________
    Response buffer:
    AT+CIPSTATUS
    STATUS:3
    +CIPSTATUS:0,"TCP","173.255.233.87",25

    __________[ HELO ]__________
    __________[ HELO 10.0.0.8 ]__________
    Response buffer:
    HELO 10.0.0.4
    ERROR

__________________

Sketch code

    #include <SoftwareSerial.h>

    // _______________________________
    #define sendit(x) ( { \
        Serial.print(F("__________[ ")); \
        Serial.print(x); \
        Serial.println(F(" ]__________")); \
         esp8266.write(x); \
       esp8266.write("\r\n"); \
         delay(300); \
         Serial.println(F("Response buffer: ")); \
         for (int i=0; i <= 99; i++) { \
             memset(buffer, 0, sizeof(buffer)); \
             delay(10); \
           bcount = esp8266.readBytes(buffer, sizeof(buffer)); \
               if (bcount == 0)  i = 100; \
               else { \
        if (bcount > 1) Serial.println(buffer); \
        delay(300); \
          } \
        } \
      } )

    // _______________________________
    #define desc(x) ( { \
        Serial.println(); \
        Serial.print(F("__________[ ")); \
        Serial.print(F(x)); \
        Serial.println(F(" ]__________")); \
      } )

    // _______________________________
    SoftwareSerial esp8266(11, 12); // RX, TX
    char buffer[200];
    String SerialReadBuffer = "";
    char SerialByteIn; // Temporary variable
    boolean SerialEnd = false;
    int bcount;

    // _______________________________
    void setup()
    {
        Initialise();
    }

    // _______________________________
    void loop()
    {
    }

    // ____________________________________________________________________________________________________
    void Initialise()
    {
        SerialReadBuffer.reserve(64);
        esp8266.begin(9600);
            // esp8266.begin(115200);
        Serial.begin(9600);
        CommandList2();
    }

    // ____________________________________________________________________________________________________
    void CommandList2()
    {
        desc("Disable echo (Echo sends back received command before response)");
        sendit("ATE0");
        desc("Delete server");
        sendit("AT+CIPSERVER=0");
        desc("Restart the module");
        sendit("AT+RST");
        desc("Check Firmware type [Responds with: AT version:1.2.0.0(Jul  1 2016 20:04:45)");
        sendit("AT+GMR");
        desc("Lists available APs");
        sendit("AT+CWLAP");
        desc("Get local IP address, e.g., 192.168.4.1");
        sendit("AT+CIFSR");
        desc("Set Station mode");
        sendit("AT+CWMODE=1");
        desc("Set current multiplex mode");
        sendit("AT+CIPMUX=1");
        desc("Connect to AP");
        sendit("AT+CWJAP=\"KCTstudy\",\"[pw redacted]\"");
        desc("Prints the SSID of Access Point ESP8266 is connected to.");
        sendit("AT+CWJAP?");
        desc("Get IP address of ESP8266 station, e.g., 10.0.0.4");
        sendit("AT+CIPSTA?");
        desc("SMTPServer connect");
        sendit("AT+CIPSTART=0,\"TCP\",\"mail.smtp2go.com\",25");
        desc("Get information about connection");
        Serial.println(F("Response format  is: "));
        Serial.println(F("STATUS:stat [ 2: Got IP, 3: Connected, 4: Disconnected]"));
        Serial.println(F("+CIPSTATUS:id,type,addr,port,tetype [type: TCP, addr: IP address]"));
        Serial.println(F("OK"));
        sendit("AT+CIPSTATUS");
        //
        // Problems start here
        //
        desc("HELO");
        sendit("HELO 10.0.0.4");
        Serial.println(F("__________________"));
    }

body:
You're sending the word "HELO" to the ESP8266 and the ESP8266 is, quite rightly, saying "What?!?! I don't know the command HELO!"

You have opened a connection in *multiple connection* mode with ID 0. You then have to *send* data through that connection.  For instance:

    AT+CIPSTART=0,"TCP\","mail.smtp2go.com",2525
    OK
    AT+CIPSEND=0,15
    > HELO 10.0.0.4<CR><LF>
    SEND OK

Using a protocol like SMTP in this mode is not easy. Better would be to use "unvarnished" mode:

    AT+CIPSTART="TCP","mail.smtp2go.com",2525
    OK
    Linked
    AT+CIPMODE=1
    OK
    AT+CIPSEND
    > HELO 10.0.0.4<CR><LF>
    250 mail.smtp2go.com Hello 10.0.0.4 [23.114.28.226]
    MAIL FROM: "Foo Bar" <foo@bar.com>
    250 OK
    ... etc ...
    QUIT
    221 mail.smtp2go.com closing connection

Note that just sending commands and blindly printing the responses isn't really the best way to go about it. You should be actively interpreting the responses that you get back and making decisions based upon them. Especially when you're in SEND mode. The SMTP protocol is two-way. You need to know what the responses are saying and what that means for your SMTP session.


body:
Before sending "HELO 10.0.0.4" ... you should send a CIPsend command with the length of your sentence + 2

Here is the right command sequence:

    AT+CIPSEND=4,15
    HELO 10.0.0.4

Best regards


message:
DHT11 not giving correct value if I attaching a servo motor

So I am using a servo motor and 2 DHT11s in my Uno, when I attach them separately it works well. But when I try to attach both, servo working correctly but DHT11 giving weird number(DHT11 was side by side, one gives 22oC and another gives 30oC sometimes -999).

I am powering both devices by using 5V and GND from arduino to a breadboard and then DHT11 and Servo power pin to the breadboard. All signal pin are direct from devices to arduino.

Am I power both devices wrong? or is there's a way to solve this?

Thanks

EDIT:
this is the code

    #include <Servo.h>
    #include <dht.h>

    dht DHT;

    #define DHT11_PIN 7
    #define DHT11_PIN2 6
    Servo myservo;  // create servo object to control a servo
    // twelve servo objects can be created on most boards

    int pos = 0;    // variable to store the servo position

    void setup() {
      Serial.begin(9600);
      myservo.attach(9);  // attaches the servo on pin 9 to the servo object
    }

    void loop() {
      for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
        // in steps of 1 degree
        myservo.write(pos);              // tell servo to go to position in variable 'pos'
        delay(15);                       // waits 15ms for the servo to reach the position
      }
      for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
        myservo.write(pos);              // tell servo to go to position in variable 'pos'
        delay(15);                       // waits 15ms for the servo to reach the position
      }

      int chk = DHT.read11(DHT11_PIN);
      Serial.print("Temperature = ");
      Serial.println(DHT.temperature);
      Serial.print("Humidity = ");
      Serial.println(DHT.humidity);
      int chk2 = DHT.read11(DHT11_PIN2);
      Serial.print("Temperature = ");
      Serial.println(DHT.temperature);
      Serial.print("Humidity = ");
      Serial.println(DHT.humidity);
      delay(1000);
    }

For the servo, I used GWServo S03N STD.

body:
Your code looks like there is no bug in there.  You might want to look at using a library that lets you assign a pin in the constructor, so you don't need to read from a specific pin.  There might be something internal going on that you don't know (or want to know) about.  As for the movement of the servos do you realise you a rotating 181 degrees `int p = 0; p <= 180` is 181 degrees, drop the `=` if you wanted 180.  Also `pos++` is the same as `pos += 1` but requires less of those tiring key presses :)

You say that the DHT11s work on their own.  The servo works on its own.  So it not a hardware fault.  I assume its not a wiring fault, but please double check.  That means it has to be something to do with the power.  If you are powering the servo from a digital pin then this is unlikely to work, try powering it from the 5V output pin on the other side of the board.

However if you are powering it from the 5V output pin and it doesn't work then you need to power it from a external source, a mobile phone charger will do (if you have one you can chop the plug off).  The problem with using external PSU is you must tie the grounds together.  Doing this means the Arduino and the external device agree what zero volts is and things work.  This is easily done by taking the gnd of the PSU and putting it in the GND connector of the Arduino and the taking the GND for the servo from the other GND on the Arduino.

I hope that all makes sense, if not tell me what you need clarifying.


message:
PCA9685: how "unset" PWM signal?

I use my Arduino with Adafruit PCA9685 servo controller. To set PWM signals I use the provided library: https://github.com/adafruit/Adafruit-PWM-Servo-Driver-Library

It allows easily set PMM signal and works good. But how can I "unset" PWM signal for a certain pin?

If a PWM siganl is active, the servo stucks on the current position and can't be moved by hand, but only by setting other pulse length. So I need to move servo and then "free" it.

body:
You could try changing the corresponding pin from output to input.
To be sure not to disturb other comfigurations you could do direct port manipulation.

    void servo_off() {
      DDRD &= ~(1<<PD5);
    }

    void servo_on() {
      DDRD |= (1<<PD5);
    }

This assumes you use pin PD5 for the pwm signal. Adjust the "D" in DDR**D** and P**D**5 so it matches the port in use as well as the pin number.

Of course, you need some additional user input like a button to trigger calls to those functions.


body:
You can try to send no "ON" time to your output pin on the PCA9685.
So, you start the "ON" at 0 and stop the "OFF" at 0.

    void freeServo(uint8_t servoIdx)
    {
      pwm.setPWM(servoIdx, 0, 0 );
    }


body:
Are your servo's control pins active high or active low?

From the library code at https://github.com/adafruit/Adafruit-PWM-Servo-Driver-Library/blob/d265f74fc0e66632e6dafc787c95b008f3245550/Adafruit_PWMServoDriver.cpp#L242  it looks like there are special on&off values of `setPWM(pin,on,off)` that turn the servo fully on or fully off, and how they work they depends on whether the servo pin is active high or active low.

    unsigned byte idle = CertainPin;

    servoController01.setPWM(idle, 0, 4096); // fully off Active high
    // servoController01.setPWM(idle, 4096, 0); // fully off Active low

or with the better documented `setPin()`:

    servoController01.setPin(idle,0,false); // Active high
    //servoController01.setPin(idle,0,true); // Active low


message:
Compilation issues on Arduino Due

I wrote an code on Arduino and I getting compilation errors. I am using Arduino Due . I wrote the following code :

    void setup() {
      Serial.begin(9600);
      analogWriteResolution(12);  // set the analog output resolution to 12 bit (4096 levels)
      analogReadResolution(12);   // set the analog input resolution to 12 bit

    }

    void loop() {

      // code
    }

But compiler gave me the following errors :

    'analogReadResolution’ was not declared in this scope
    ‘analogWriteResolution’ was not declared in this scope
    ‘DAC0’ was not declared in this scope

I'm using Arduino 2:1.0.5 (on Linux). The board list doesn't show Arduino Due (USB programmable).And I don't have Board Manager option. How do I install Arduino SAM Board to compile the program ?

body:
According to the [Arduino - ReleaseNotes][1],

> ARDUINO 1.5 BETA - 2012.10.22
>
> * First release for the unified IDE for both AVR 8-bit and ARM 32-bit   (SAM3 CPUs) architectures.
> * This release include the SAM Arduino Core used in the Arduino Due   Board.

So your 1.0.5 version does not allow for Due compilation. [Download][2] the most up-to-date version and you will be fine (you will be able to install SAM support).

Then you will be able to at least compile. If you have other problems with your code, please open another question here (in order to keep the one-question-per-post behavior of this website).

Don't install arduino from the debian repository, since that version is not updated regularly. Use the website version

  [1]: https://www.arduino.cc/en/Main/ReleaseNotes
  [2]: https://www.arduino.cc/en/Main/Software


message:
Differential voltage measurement with Arduino UNO

**EDITED:**
I bought a very sensitive (and expensive) pressure sensor which requires differential analog measurement. I am an amateur hobbyst and a total beginner in Arduino so I would like to ask some advice on how to connect the device so nothing would be damaged.

In the figure below is the scheme which I've got form the manufacturer along with schematic on how I am going to connect that:

- the wire colours are as in the provided device,
- the symbols are as they were attached to the wires,
- the resistor was provided and connected by the manufacturer.

As far as I understood the sensor manual I should connect the device to analog pins as in the schematic below, and read the A0 and A1 and subtract the signal values. Is that fine? Should I connect the wire going to A1 to Arduino GND as well?

[![Corrected schematic][1]][1]

Or should I connect the GND instead of A0 line in the image below?
[![Or should I connect the GND instead of A0?][2]][2]

EDIT: Original connection scheme from the DS and [link to the CL1A sensor www](http://www.zepwn.com.pl/en/offer/index,13,76,,pressure-transducers.html#main) and  [link to the sensor datasheet (only in Polish)](http://cms.zepwn.com.pl/zepwn/_media/products/pdf-pl/karta_cl1a_2013_09_25.pdf)
Yeah, possibly I misunderstood something.

[![enter image description here][3]][3]

  [1]: https://i.stack.imgur.com/9zlo7.png
  [2]: https://i.stack.imgur.com/7FFwk.png
  [3]: https://i.stack.imgur.com/b1lhl.jpg

body:
According to the update, which shows the datasheet, you have one BIG mistake and one smaller mistake.

The big mistake is that you inverted the polarity! Look carefully. The +24V wire goes to the + pin of the supply, while the ground to the - pin.

Moreover the DAQ board has a differential one, but one of them is tied to ground.

So I suggest you to attach the wires in this way:

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

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


body:
You do not need to do any kind of differential measurement here. The
Arduino analog input measures voltages relative to ground. Then, as long
as the Arduino and the power supply share a common ground, you should be
fine.

On the other hand, you may need a voltage divider. I have seen a few
sensors interfaced the same way (GND, +24V and signal), which output a
voltage between 0 and +10 V. That could fry the Arduin, and maybe
also the sensor. Check the datasheet to see the maximum voltage the
sensor can output, and use a voltage divider to get that safely into the
0 – +5 V range.


body:
The output of that sensor is an industry standard "4-20mA" (known as a *current loop*). That means that the current output from the `+S` wire varies between 4mA and 20mA depending on the pressure. You need to convert that current into a voltage so that the Arduino can sample it.

Note that your attempt at a schematic is completely backwards. You must connect the +24V pin to +24V on a power supply. GND must be connected to GND on the power supply, and also GND on the Arduino.

Now for the signal. Yes, a resistor is the simplest way of converting a current into a voltage. Simply pass the current through the resistor to ground and a voltage will be dropped across it.

According to Ohm's Law, V=IR. Or, to turn it around, R=V/I.

Your maximum current is 20mA (0.02A) and your desired maximum voltage is 5V. So you can put those values into Ohm's Law and get a resistance:

* R=V/I = 5/0.02 = 250Ω.

Now 250Ω resistors aren't that common, but 220Ω ones are. So what would that give us?

* V = IR = 0.02 * 220 = 4.4V

Perfect. And at the lower (4mA) end of the range?

* V = IR = 0.004 * 220 = 0.88V.

So with a 220Ω resistor you would get a voltage reading of between 0.88 and 4.4V on the Arduino.

(Note: the datasheet recommended 100Ω would be more suitable for a 3.3V Arduino - it would give between 0.4V and 2V).

For safety I would also include a small inline current limiting resistor and 5.1V zener diode. If the 220Ω resistor should fail or become disconnected you would get the full 24V (or somewhere about there) across the Arduino's A0 pin. It's limited to 20mA so may not be a problem, but you can't be sure, so best to add that to clamp the voltage to a maximum of 5.1V. After all, a zener diode is cheaper than a new Arduino.

And to clarify - the schematic:

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

<!-- End schematic -->


message:
Creating Sine wave with DAC and feeding it back

I want to produce Digital Sine wave send it to DAC0 and then receive it back as input on A0 and plot the graph. I am using Arduino Due. I wrote the following code:
<!-- language-all: lang-cpp -->

    #define maxSamplesNum 120
    #define Sample 50000000/maxSamplesNum  // sample for the 50Hz signal expressed in microseconds

    static int Table[maxSamplesNum] =                        // lookup table  for sine wave table

      {
        0x7ff, 0x86a, 0x8d5, 0x93f, 0x9a9, 0xa11, 0xa78, 0xadd, 0xb40, 0xba1,
        0xbff, 0xc5a, 0xcb2, 0xd08, 0xd59, 0xda7, 0xdf1, 0xe36, 0xe77, 0xeb4,
        0xeec, 0xf1f, 0xf4d, 0xf77, 0xf9a, 0xfb9, 0xfd2, 0xfe5, 0xff3, 0xffc,
        0xfff, 0xffc, 0xff3, 0xfe5, 0xfd2, 0xfb9, 0xf9a, 0xf77, 0xf4d, 0xf1f,
        0xeec, 0xeb4, 0xe77, 0xe36, 0xdf1, 0xda7, 0xd59, 0xd08, 0xcb2, 0xc5a,
        0xbff, 0xba1, 0xb40, 0xadd, 0xa78, 0xa11, 0x9a9, 0x93f, 0x8d5, 0x86a,
        0x7ff, 0x794, 0x729, 0x6bf, 0x655, 0x5ed, 0x586, 0x521, 0x4be, 0x45d,
        0x3ff, 0x3a4, 0x34c, 0x2f6, 0x2a5, 0x257, 0x20d, 0x1c8, 0x187, 0x14a,
        0x112, 0xdf, 0xb1, 0x87, 0x64, 0x45, 0x2c, 0x19, 0xb, 0x2,
        0x0, 0x2, 0xb, 0x19, 0x2c, 0x45, 0x64, 0x87, 0xb1, 0xdf,
        0x112, 0x14a, 0x187, 0x1c8, 0x20d, 0x257, 0x2a5, 0x2f6, 0x34c, 0x3a4,
        0x3ff, 0x45d, 0x4be, 0x521, 0x586, 0x5ed, 0x655, 0x6bf, 0x729, 0x794
      };

    int i = 0;
    int sample;
    int sensorPin = A0;
    int sensorValue = 0;

    void setup() {
      Serial.begin(9600);
      analogWriteResolution(12);  // set the analog output resolution to 12 bit (4096 levels)
      analogReadResolution(12);   // set the analog input resolution to 12 bit

    }

    void loop() {

      sample = 50;

      analogWrite(DAC0, Table[i]);  // write the selected waveform on DAC0

      i++;
      if(i == maxSamplesNum)  // Reset the counter to repeat the wave
        i = 0;

      delayMicroseconds(sample);  // Hold the sample value for the sample time
      sensorValue = analogRead(sensorPin);
    }

I want to create 3.3V (P-P) sine wave but I don't how to set the amplitude in this wave.

Also I would like to redirect the sine wave output from DAC0 to A0 Pin and plot the graph to check if the sine wave generated was successful.
How do I plot the graph ?

**Update** : I uploaded the program but there was no result. I tried to read data from A0 but there wasn't any output. What am I doing wrong ?

body:
I ran your code unmodified and plugged in an oscilloscope to look at DAC0 (looks an OK sine wave) and A0 (looks flatline). Hope this helps.

[![A0 Screenshot][1]][1]
[![DAC0 Sceenshot][2]][2]

  [1]: https://i.stack.imgur.com/9v0OU.png
  [2]: https://i.stack.imgur.com/DfGYM.png


message:
Wiring an IR blaster+receiver board

I've salvaged this small IR blaster+receiver board from an old computer toy:

[![board front][1]][1]
[![board back][2]][2]

As you can see the board was connected to the main unit via a 4-wire cable labelled like this:

 - LED (yellow) (I guess this is the IR LED/blaster)
 - IR (white) (I guess this is the IR receiver)
 - VCC (red)
 - GND (black)

I'd like to use this board with an [Arduino library like IRremote][3], but I am not sure about the VCC voltage and whether I need to add more components on the Arduino side.

UPDATE:
I've checked the LED with a multimeter and indeed it is a visible bicolor LED, so there is no IR blaster in this board. At this point, is there any good reason to keep the IR receiver on the board rather than just cutting it and reusing as a standalone component?

  [1]: https://i.stack.imgur.com/kBkGr.jpg
  [2]: https://i.stack.imgur.com/YRfyI.jpg
  [3]: https://circuitdigest.com/microcontroller-projects/universal-ir-remote-control-using-arduino-android

body:
You solved your problem.

You said

> I checked the LED with a multimeter and indeed it is a visible bicolor
> LED, so there is no IR blaster in this board.

So, be kind, accept this answer so we can close your question.

I'm posting, not comment, only to get this out of the "unanswered".


message:
Bootloader and Boards Definition for Atmega2560V-8AU at 8 MHz / 3.3v

I am working on a home made project,where i am using Atmega2560V-8AU **(note the suffix, this part has an 8 MHz maximum clock rate)** as my main controller, supplying 3.3V to this chip.

I want this controller to work exactly same as standard Atmega2560-16AU like on Arduino Mega(perhaps at a slower baud rate on account of the slower clock)

Does there already exist a suitable bootloader image and board definition for an ATmega2560 operating from an 8 MHz crystal?

If not, what changes would need to be made to the usual 16 MHz bootloader and boards definition to support 8 MHz operation, both for the bootloader and for correct time functions and serial buad rates in sketches?

body: I have used megacore bootloaders, and it solved the problem


message:
Arduino Controlling a stepper motor

How can I get an Arduino to do the following to a Stepper Motor installed on a "Lead-screw" attached to my table-saw's Fence?

1. Turn the "lead-screw" clockwise when I press a given button, UNTIL I release the button.

2. Turn the same "lead-screw" counter-clockwise, when I press another button, UNTIL I release the button.

3. Adjust a "speed" knob, to control the motor's speed when the fence is moving; from very fast to very slow; and even stop when the control is completely counter-clockwise.

4. Turn a switch off, which will remove all control to the motor; so I can turn the shaft manually without resistance, whenever I do not want the fence to be under control of the motor.

That is ALL I need.

It is that simple. So what do I need? What do I need to purchase? I am a novice.

body:
We can't tell you what to buy. We can help you understand how it will work, though, and what you should look for.

First off you need a suitable stepper motor. We can't help you with that. You need one that will a) connect to your lead screw in some way, and b) have enough power to drive the screw.  Maybe the [robotics stack-exchange](https://robotics.stackexchange.com/) can help you better with that.

Once you have identified your stepper motor you need a driver that can control it. There's two kinds of stepper motor - "unipolar" and "bipolar" and the type of stepper motor you have chosen will determine the type of driver you need. Suffice it to say if you have a "unipolar" stepper motor you need a "unipolar" driver.

In brief: a bipolar stepper motor usually has 4 wires and needs a pair of H-bridges to drive it. A unipolar stepper driver normally has 5 or 6 wires and just needs beefy MOSFETs to drive it.

Your driver will, of course, need to be able to provide enough current to drive your stepper motor. For the finer details of the driver the [electronics stack-exchange](https://electronics.stackexchange.com/) will most likely have the most expertise.

One further thing you will need is a potentiometer (and fancy knob etc) to set the speed.

Then it's just a matter of "gluing" everything together through the Arduino and writing the software.

How you write the software for the Arduino depends on  the driver for your stepper motor. There are libraries with examples for most types. Adding in an `analogRead(...)` and `map(...)` to convert the voltage from the potentiometer into a speed should be simple enough.


body:
I've got to ask here.  Why use a stepper?
This would be fairly easy with two button switches and a regular DC motor.  One switch provides power to drive the motor CW the 2nd motor drives it CCW.

You would still need to choose a motor with the right torque but IMHO this method would be WAY easier than using a stepper, and arduino, writing code, etc.


message:
Reducing noise and finding sampling rate

I have Arduino Due R3 (84MHz) and I am trying to find the mean of value from AnalogRead. I have to set the sampling rate of 8000 samples/second with 4 channels. I tried using `for` loop for this purpose.

    #include <LiquidCrystal.h>

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

    int i = 0;
    int sensorPin = A0;
    int sensorValue = 0;
    int highest=0;
    int lowest=0;
    float mean=0;

    void setup()
    {
      Serial.begin(9600);
      analogWriteResolution(12);  // set the analog output resolution to 12 bit (4096 levels)
      analogReadResolution(12);   // set the analog input resolution to 12 bit
      // set up the LCD's number of columns and rows:
      lcd.begin(16, 2);

      lcd.print("Hello");

    }

    void loop()
    {

      for(;;)
      {
        mean=0;
        for(i=0;i<8000;i++)
        {
           sensorValue = analogRead(sensorPin);
         highest=max(highest,sensorValue);
         lowest=min(lowest,sensorValue);
         mean = mean + (highest-lowest);
        }
        mean = mean/8000;
        delay(10);
        lcd.setCursor(0, 1);
        lcd.print(mean);
      }

Will this set sampling rate to 8000 samples/sec ?

Also I was receiving  a lot of noise at *A0* which often led to the lowest value to be 0. In the image : The  red wave is a constant dc voltage of 2.7 V from power supply.
[![The  red wave is constant dc voltage of 2.7V ][1]][1]
How do I overcome this noise so that mean value is accurate and precise ?

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

body:
> Will this set sampling rate to 8000 samples/sec ?

No, that will make it perform a block of 8000 samples as fast as it can. There's absolutely nothing in there that has anything to do with time, so how can "seconds" be included in the description of it?

> How do I overcome this noise so that mean value is accurate and precise ?

That depends on where the noise is coming from. Maybe if you slowed down your sampling you wouldn't get the noise. Maybe if you made a better connection to whatever it is you're sampling you'd get less noise. Maybe if you added some external filtering you'd get less noise. Maybe if you used a different mathematical model for determining what your average value is you'd not care about the noise.


body:
Just to as a complement to Majenko's answer (which I second), there are
a couple of flaws in your program that may be related to your problem:

* `lowest` is always zero, as it is initialized to 0 and cannot increase
* your computation of the mean is incorrect: the mean is the sum of the
  readings divided by their number
* you fail to reset `lowest` and `highest` between consecutive runs of
  8000 samples
* there is no point in putting all of `loop()` inside an infinite loop.

Assuming you really intend to print summary statistics on runs of
8000 samples, as your code suggests, I would write it like this:

    const int SENSOR_PIN = A0;
    const int SAMPLE_COUNT = 8000;
    const uint32_t SAMPLE_PERIOD = 125;  // 125 us

    void loop()
    {
        long sum = 0;
        int lowest = INT_MAX, highest = 0;

        uint32_t lastTime = micros();
        for (int i = 0; i < SAMPLE_COUNT; i++) {

            // Wait until it's time.
            while (micros() - lastTime < SAMPLE_PERIOD) ;
            lastTime += SAMPLE_PERIOD;

            // Take and process the sample.
            int sensorValue = analogRead(SENSOR_PIN);
            sum += sensorValue;
            highest = max(highest, sensorValue);
            lowest = min(lowest, sensorValue);
        }
        float mean = (float) sum / SAMPLE_COUNT;
        Serial.print("mean: "); Serial.print(mean);
        Serial.print(", minimum: "); Serial.print(lowest);
        Serial.print(", maximum: "); Serial.println(highest);
        Serial.flush();
    }

------------------------------------------------------------------------

**Edit**: I changed the code in order to keep a roughly constant
sampling rate of 8000 samp/s. The main change is that, before
taking a reading, we wait until it's time to do so (until
`micros() - lastTime >= SAMPLE_PERIOD`).

Note that `lastTime` could be updated with `lastTime = micros()`, in
which case it would have hold the time we last took a sample. By
updating it with `lastTime += SAMPLE_PERIOD` it instead holds the time
we _shoud have taken_ the last sample. This is the right choice for
enforcing a given _average_ sampling rate.

**Running on an Uno**: I have no experience with the Due, but here are
some remarks that would apply to an Uno, or any other AVR-based Arduino:

* `analogRead()` takes about 110 µs, which means we cannot sample
  more than one channel, and we only have about 15 µs to process
  the sample. Here the processing is simple enough that the Arduino can
  do it in this limited time.
* There is some jitter in the sampling, because `micros()` has a limited
  resolution of 4 µs, because of the timer interrupt kicking in
  from time to time, and because the `while` loop takes a finite amount
  of time.

If I were to do something similar on an Uno, I would forgo
`analogRead()`, configure the ADC to be triggered by a timer, and set
the timer to trigger the DC every 125 µs. Not only would this get
rid of the jitter, it would also allow the CPU to do its job in parallel
with the ADC, instead of just sitting idle and waiting until the ADC is
done. This would allow for more complex per-sample processing.

**About the Due**: As I said, I have no experience with this board. It
has a more capable processor, but this tells you nothing about the speed
of its ADC. I would expect to face the same issues as with the Uno,
though maybe to a lesser degree. I _guess_ it should be possible to
trigger the ADC from a timer, but I have no idea how to do so.


message:
Compiling source with Arduino.h with avr-g++

How should I include the Arduino libraries when I'm compiling from the the command line? I tried to do it like this:

    avr-g++ -g -Os -Wall -mcall-prologues -mmcu=atmega328p -fno-exceptions -o blink.obj blink.cpp -L. -lutil -I"C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" -I"C:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" -I"D:\Projects\Arduino" -I"C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores"

but it returns `undefined reference` to the function that I am trying to use.

*Arduino version: 1.8.2*

body:
You need to do a whole lot more than just run the one command.

You need to compile each individual source file for the libraries you want (using `-c` to just compile and not link), then (ideally) archive them into a library file. Do the same for the core. Then you need to add paths to your sketch compilation command pointing to where the header files are for those libraries, and compile the sketch to an object file (again with `-c`). Finally you need to link everything together into an ELF file, and convert that to a HEX file.

TBH you're best off using an already-existing Makefile project, or arduino-builder.


message:
Decoding 2.4G RF remote controller?

There is tons of information on how IR remote controls work and how to use an Arduino to decode those signals and use any IR remote to suit your project. But I couldn't find much info about 2.4G RF remotes.

I want to control a string of addressable LEDs and cycle through different patterns using one of these [2.4G RF remotes][1]

[![2.4G RF RGB LED controller][2]][2]

Is it possible to use these remotes with Arduino? If yes, how can I read the signals and assign tasks to different buttons on the remote?

  [1]: https://www.banggood.com/2_4G-RF-RGBW-4-Zone-Touch-Remote-Control-For-RGBWRGBWW-LED-light-Bulb-p-967534.html
  [2]: https://i.stack.imgur.com/qMcCo.jpg

body:
If it is based on the nRF24L01+ (or the nRF31512C SoC, which is a combined MCU and nRF24L01+ in one chip, and used in most wireless mice and keyboards) then it [may be possible to sniff the signal](http://hackaday.com/2014/08/05/sniffing-nrf24l01-traffic-with-wireshark/). If not, you're probably not going to have much luck.

You'd be better off trying to hack the existing receiver that is paired with the remote to get usable signals out of it.


body:
The usual approach for 2.4 GHz is to open the product, identify the radio chip, and use a USB logic analyzer on the SPI bus that usually connects it to the MCU to capture the configuration and data traffic, and figure out what the configuration register accesses mean from the radio chip data sheet.

The occasional appearance of combined MCU/radio parts prevents that approach, but often that is only used on one end of the link and the other will still have a distinct MCU and radio with an SPI bus in between.

This is heavily practiced in the radio control community, as people want to use their nice transmitters to fly cheap toys.  And there is code out there to transmit compatibly with some of the odder chips like the X297, using more common ones like the NRF24L01 or its workalikes from Beken, etc.

A key advantage of SPI sniffing versus over-the-air sniffing is that the usually implemented channel-hopping doesn't mean you loose the signal ever time it moves to a new channel - and you actually get to the see the frequency registers being written.  To capture a hopping scheme over the air, you would need something more like a spectrum analyzer to figure out the sequence, and then have software track the signal while you attempt to figure out the data.  However, a remote which only sends occasional button presses may not use hopping in the way something sending data continuously (like an R/C set, or possibly a keyboard/mouse) would.


body:
I was having same issue and at the end of the day I have made it working. For the communication I have used [openmili][1] library  ([project][2] started by Henryk Plötz who has reverse engineered protocol for communication of these remotes). This didn't work with new remotes as they have changed couple of things:

 - Listens on a different channelset (this was true of different bulb types among the old bulbs too). The new bulbs use channels 8, 39, and 70.
 - Different PL1167 syncword. It uses 0x7236 , 0x1809 .
 - Packets have 9 bytes instead of 7.
 - Packets are scrambled. The same command can look completely different.

(information taken from [Chris Mullins blog][3])

Confirmation of these info I have found in [ESP8266 Milight hub project][4] where I have found config for remotes (https://github.com/sidoh/esp8266_milight_hub/blob/master/lib/Radio/MiLightRadioConfig.cpp)

In my case I was using rgb+cct remote so it tells me that I should use `0x7236, 0x1809` as syncwords, packet length `9` and channels `8, 39, 70`.

Applying those changes I was able to get data from the remote. One more usefull [link][5].

  [1]: https://github.com/henryk/openmili
  [2]: https://hackaday.io/project/5888-reverse-engineering-the-milight-on-air-protocol
  [3]: https://blog.christophermullins.com/2017/03/18/reverse-engineering-the-new-milightlimitlessled-2-4-ghz-protocol/
  [4]: https://github.com/sidoh/esp8266_milight_hub
  [5]: http://arduino-projects4u.com/milight-new-protocol/


message:
How do I connect through a HC-05 to PS4 Controller?

Searching for Arduino and PS4 on google, I find always the same construction using a USB host shield and a [Bluetooth dongle][1].

But I'd like to connect a PS4 Controller to a HC-05 device. Is it possible? If not, why not?

  [1]: https://www.circuitsathome.com/mcu/arduino/ps4-controller-support-for-the-usb-host-library/

body:
The HC-05 uses the Bluetooth Serial Port profile (SPP). The PS4 controller doesn't.

Hence you need something that is capable of using the same profile that the PS4 controller uses (HID?). And to that end you need something a little more configurable than a simple HC-05. One option is, as most people use, a USB Host shield with a Bluetooth dongle that can then be configured to communicate using the right profile.


message:
Searching for a good keypad

I'm wanting to make a keypad for my gragedoor. I found one like [this][1] but i don't think it is very waterproof.

Now i'm wondering if someone of you know a good keypad that can be used outdoors and can be connected to a arduino (preferably arduino nano).

Hope you can help.

Edit if found this keypad will i be able to program this one with a arduino?
[link][2]

  [1]: https://www.aliexpress.com/item/New-4-4-Matrix-Array-Matrix-Keyboard-16-Key-Membrane-Switch-Keypad-for-arduino/32380198303.html?spm=2114.01020208.3.1.r4kyIB&s=p&ws_ab_test=searchweb0_0,searchweb201602_3_10152_10065_10151_10068_5030016_10084_10083_10080_10082_10081_10177_10110_10136_10137_519_10111_10060_10112_10113_10155_10062_10114_437_10154_10056_10055_10054_10182_10059_303_100031_10099_10078_10079_10103_10073_10102_10096_10123_10189_10052_10053_10142_10107_142_10050_10051,searchweb201603_13,ppcSwitch_5_ppcChannel&btsid=ab793dc3-ba22-4c7e-af4e-fdfb3d180a73
  [2]: https://www.aliexpress.com/item/Pin-Pad-with-Waterproof-terminal-keyboards-ATM-keypads-military-keyboards-IP65-keyboards-weatherproof-keypads-matrix-keypads/32809794485.html?spm=2114.01020208.3.1.8EOZFx&ws_ab_test=searchweb0_0,searchweb201602_3_10152_10065_10151_10068_5030016_10084_10083_10080_10082_10081_10177_10110_10136_10137_519_10111_10060_10112_10113_10155_10062_10114_437_10154_10056_10055_10054_10182_10059_303_100031_10099_10078_10079_10103_10073_10102_10096_10123_10189_10052_10053_10142_10107_142_10050_10051,searchweb201603_13,ppcSwitch_5_ppcChannel&btsid=490d3b4c-247a-4c78-915a-374ded012e1b&algo_expid=34319a55-04ea-4a5a-b49b-8f921178f0f7-0&algo_pvid=34319a55-04ea-4a5a-b49b-8f921178f0f7

body:
The membrane keyboard you have linked (first link) in your question should be water resistant, if not water proof.

We use something similar at my work. You can have the keypad stuck to the outside of the enclosure and then have a rubber seal (or silastic) sealing where the ribbon cable enters the enclosure.

[![4x4 membrane keyboard][1]][1]

You will notice that the ribbon cable pretty much exits the bottom of the keypad. The better ones to get, if you can find them, are the ones where the ribbon cable exits the keypad further away from the edge (see example image below). That way the adhesive backing of the keypad seals the cable entry into the enclosure.

[![rear membrane keypad][2]][2]

As far as hooking it up to an Arduino - no problems at all. A 16 key matrix keyboard has 8 connections, 4 for each row and 4 for each column. Every time you press a key, the row and column are shorted together.

[![internal circuit][3]][3]

The way I would connect it up is to have the rows connected as inputs and the columns as outputs. One by one I would turn one of the columns on (HIGH) and see which input(s) are reading a HIGH. If it is I know that that key (row and column) is pressed. This method will handle multiple keys pressed at once.

There is an [walk-through tutorial][4] posted at instructables.com.

The more expensive keypad in your second link and [this one][6] both have the option of connecting by PS2. There is an Arduino page on connecting and controlling a PS2 keyboard [here][5].

  [1]: https://i.stack.imgur.com/i97nX.jpg
  [2]: https://i.stack.imgur.com/dP3qd.jpg
  [3]: https://i.stack.imgur.com/YBfGt.jpg
  [4]: http://www.instructables.com/id/Connecting-a-4-x-4-Membrane-Keypad-to-an-Arduino/
  [5]: http://playground.arduino.cc/Main/PS2Keyboard
  [6]: https://www.aliexpress.com/item/3-4-Matrix-rugged-USB-Numeric-IP65-Waterproof-panel-mount-brushed-Metal-Keypad-with-12-full/32293102143.html?spm=2114.40010708.4.6.02kkHy


message:
New Microcontroller - programmer is not responding -

I got an Arduino and after I was playing with it, I noticed that its internal micro controller si removable and decided to buy another micro controller. After I got the new one (atmega328P) and replaced with the original which came with the Arduino, I started to upload a sketch but it does not work.

I get the following:

    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding

If I use the Original MC which came with the Arduino works fine, but with the new one it does not.

Did I buyed a bad/wrong MC, or I need to make something else?
Both have the same name :

    ATMEGA328P-PU

The new micro controller has already a boot loader installed.

body:
I managed to fix the problem by downloading [the latest version](https://www.arduino.cc/en/Main/Software) of the Arduino IDE from their website and works fine now.

I use Linux mint 18 and installed Arduino via `apt` and I really do not know why I managed to install the boot loader, but failed with uploading the Sketches.


message:
Air quality sensor reading meaning

So I got this air quality sensor running, and it's outputting some numbers.
I've read some tutorial online and it looks like the smaller the number the better the air quality.
But I don't understand what is the meaning of those number. Like what is the unit of measurement? For example, the temperature sensor gives you numbers in Celcius degree.

http://wiki.seeed.cc/Grove-Air_Quality_Sensor_v1.3/

body:
One of those [MQ gas sensors][1] ? They are electrochemical sensors. They can be calibrated more or less with a known concentration of a certain gas. But since the are often sensitive to a number of gasses, you do not know the concentration of that specific gas that was used for calibration.

A number that is going up and down is what you have. You can make a graph with it to show the value for each hour or each day.

The MQ gas sensors have a "preheat" or "burn-in" time. It is often 24 hours. Keep the sensor on for 24 hours to get more stable output values.

A temperature sensor is completely different, it contains electronics inside and has been calibrated at the factory. The MQ gas sensors are just a few wires, a heater and some chemicals.

[**ADDED**]
That is a module with the MP503 gas sensor. It just like the MQ sensors a electrochemical gas sensor. According to the datasheet it is sensitive for alcohol and smoke and the "preheat" or "burn-in" is called "aging time" and can be up to one week! The module has a amplifier.

The detection of gasses is according to a certain curve. To calculate the concentration of gasses a calculation is needed (and a calibrated sensor). I don't see that calculation in the supplied library. So all you have is numbers that change according to the air quality. That's all. And that is normal for these sensors.

Read the information and pdf files on that seeed page about this Grove module. It clearly says that you can't measure the concentration of gas (not "quantitatively"), you can only tell if the air quality gets better or worse (qualitative).

  [1]: https://playground.arduino.cc/Main/MQGasSensors


message:
Raspberry Pi Outputting Signal to arduino

I have been trying to get my raspberry pi to output a signal of High or Low, which is then picked up by digital pin 4 on my arduino.

On the raspberry pi, I have connected the output to GPIO 24 and have set up a simple to circuit with an led and 220 ohm resistor in series to check if there was any output. I did manage to get the led to turn on and off due to typing commands into the console on the raspberry pi, so that can't be the problem.

For the raspberry pi side of things, I have installed the WiringPi library and typed these commands:

    gpio -g mode 24 out

This set up the GPIO pin and then to turn them off, I used these independently.

    gpio -g write 24 1
    gpio -g write 24 0

For my code on my arduino, I have adapted a rtc with stepper motor piece of code that I am working on to go with this sub project.

    #include <DS3231.h>
    #include <Stepper.h>

    //---( Number of steps per revolution of INTERNAL motor in 4-step mode )---
    #define STEPS_PER_MOTOR_REVOLUTION 32

    //---( Steps per OUTPUT SHAFT of gear reduction )---
    #define STEPS_PER_OUTPUT_REVOLUTION 32 * 64  // 2048

    // Init the stepper object with sequence 1-3-2-4 for proper sequencing
    Stepper small_stepper(STEPS_PER_MOTOR_REVOLUTION, 8, 10, 9, 11);

    // Init the DS3231 using the hardware interface
    DS3231 rtc(SDA, SCL);

    const int raspiPin = 4;
    int raspiSwitch = 0;

    int  Steps2Take;

    void setup()
    {
      // Setup Serial connection
      Serial.begin(115200);
      pinMode(raspiPin, INPUT);

      // Initialize the rtc object
      rtc.begin();

      // The following lines can be uncommented to set the date and time
      // rtc.setDOW(SATURDAY);     // Set Day-of-Week to SUNDAY
      // rtc.setTime(22, 32, 50);     // Set the time to 12:00:00 (24hr format)
      // rtc.setDate(3, 6, 2017);   // Set the date to January 1st, 2014
    }

    void loop()
    {
      // Read the state from the raspi
      raspiSwitch = digitalRead(raspiPin);

      // Send Day-of-Week
      Serial.print(rtc.getDOWStr());
      Serial.print(" ");

      // Send date
      Serial.print(rtc.getDateStr());
      Serial.print(" -- ");

      // Send time
      Serial.println(rtc.getTimeStr());

      // Declare variable for later testing against
      String myTime = rtc.getTimeStr();

      if (myTime == "17:00:00") {

        Serial.println("Rotating stepper motor at " + myTime + ".");

        Steps2Take  =  STEPS_PER_OUTPUT_REVOLUTION / 2;  // Rotate CW 1 turn
        small_stepper.setSpeed(500);
        small_stepper.step(Steps2Take);
        delay(1000);

        Steps2Take  =  STEPS_PER_OUTPUT_REVOLUTION / 2;  // Rotate CW 1 turn
        small_stepper.setSpeed(500);
        small_stepper.step(Steps2Take);
        delay(1000);

      } else if (myTime == "08:00:00") {

        Serial.println("Rotating stepper motor at " + myTime + ".");

        Steps2Take  =  STEPS_PER_OUTPUT_REVOLUTION / 2;  // Rotate CW 1 turn
        small_stepper.setSpeed(500);
        small_stepper.step(Steps2Take);
        delay(1000);

        Steps2Take  =  STEPS_PER_OUTPUT_REVOLUTION / 2;  // Rotate CW 1 turn
        small_stepper.setSpeed(500);
        small_stepper.step(Steps2Take);
        delay(1000);

      } else if (raspiSwitch == 1) {

        Steps2Take  =  STEPS_PER_OUTPUT_REVOLUTION / 2;  // Rotate CW 1 turn
        small_stepper.setSpeed(500);
        small_stepper.step(Steps2Take);
        delay(1000);

        Steps2Take  =  STEPS_PER_OUTPUT_REVOLUTION / 2;  // Rotate CW 1 turn
        small_stepper.setSpeed(500);
        small_stepper.step(Steps2Take);
        delay(1000);

      }

      delay (1000);

    }

When I use the else if statement to turn the stepper motor if there is a high signal from the raspiPin, the motor will turn even when the signal is low.

I used Serial.println to output the state of the raspiSwitch variable to the serial output and for some reason, it changes by itself between 1 and 0. I do not know why and would like to resolve this so I can move onto the next stage of connecting it to the internet on a php webpage.

If anyone could help, I would greatly appreciated it

body: The Arduino and the Raspberry pi should have a common ground. Connect the ground pin of the Arduino to the Raspberry pi. Both boards should be powered by the same power source and connect a pull-down resistor from the digital pin of the Arduino to ground. about 10Kohms might be enough.


message:
Change Word Color

I tried to change the color of the words but nothing happens, I do not know what I'm doing wrong. I am using official Arduino editor of code with words.txt

    #######################################
    # Syntax Coloring Map For testing
    #######################################

    #######################################
    # Datatypes (KEYWORD1)
    #######################################

    Test KEYWORD1
    Diego   KEYWORD1
    Ulises  KEYWORD1
    PALMA   KEYWORD1

    #######################################
    # Methods and Functions (KEYWORD2)
    #######################################

    doSomething KEYWORD2
    Argentina  KEYWORD2
    Brasil   KEYWORD2
    Alemania  KEYWROD2
    Chile   KEYWORD2

    #######################################
    # Instances (KEYWORD2)
    #######################################

    #######################################
    # Constants (LITERAL1)
    #######################################

body:
The question's reference to “official Arduino with words.txt” is rather ambiguous.  So far there has not been any clarification whether the question refers to the usual *Arduino IDE* environment.

However, supposing the question intended to refer to the usual environment, note that the [Library Tutorial](https://www.arduino.cc/en/Hacking/LibraryTutorial) document at arduino.cc says to do the following to set up a list of highlighted keywords:

>Create a file called **keywords.txt** in the [library] directory

Thus, renaming your *words.txt* to *keywords.txt* may solve the problem.


message:
Error 400. The request has an invalid header name ESP8266 (HTTP-POST)

I'm trying to send a http post to my server from an esp8266-Wifi (I use the ESP8266 library)

I check all my http post format, and I guess is okay... but at the response, the monitor serial **answer** me like this:

    Requesting POST: HTTP/1.1 400 Bad Request
    Content-Type: text/html; charset=us-ascii
    Server: Microsoft-HTTPAPI/2.0
    Date: Sat, 10 Jun 2017 23:12:48 GMT
    Connection: close
    Content-Length: 339

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
    <TITLE>Bad Request</TITLE>
    <META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii">

Bad Request - Invalid Header

HTTP Error 400. The request has an invalid header name.

    closing connection

and this is my code:

    #include <ESP8266WiFi.h>
    const char* ssid     = "Putostodosmenosyo";
    const char* password = "CetriX.2016%Gdl";

    const char* host = "187.201.44.110";

    const String Cadenadatos = "info=Micanton|2017-06-09 12:00|25" ;
    //const String Tamano = String(Cadenadatos.length()) ;
    const String postiu = "POST /wsCo2Keellingv1002/wsCo2Keelling.asmx/GuardaInfoArduino HTTP/1.1\r\nHost:187.201.44.110:80\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length:144\r\n\r\n?info="+String(Cadenadatos)+"\n" ;
    const String postam = String(postiu);

    void setup() {
      Serial.begin(9600);
      delay(100);

      // We start by connecting to a WiFi network
      Serial.println();
      Serial.println();
      Serial.print("Connecting to ");
      Serial.println(ssid);

      WiFi.begin(ssid, password);

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

      Serial.println("");
      Serial.println("WiFi connected");
      Serial.println("IP address: ");
      Serial.println(WiFi.localIP());
      delay(2000) ;
    }

    void loop() {

      WiFiClient client;
      const int httpPort = 80;
      if (!client.connect(host,httpPort)) {
        Serial.println("Conexion fallida");
        return;
      }

     //String data = "pst=temperature>" + String(random(0,100)) +"||humidity>" + String(random(0,100)) + "||data>text";

       Serial.print("Requesting POST: ");
       // Send request to the server:
       //client.println("POST /wsCo2Keellingv1002/wsCo2Keelling.asmx/GuardaInfoArduino HTTP/1.1");
       //client.println();
       //client.println("co2kelling.hopto.org") ;
       client.println("POST /wsCo2Keellingv1002/wsCo2Keelling.asmx/GuardaInfoArduino HTTP/1.1");
       client.println("Host: co2kelling.hopto.org");
       client.println("Content-Type: application/x-www-form-urlencoded");
       client.print("Content-length: ");
       client.print(postiu.length());
       client.println();
       client.print(String(Cadenadatos));
       while(client.connected())
       {
        while(client.available())
        //String line = client.readStringUntil('\r') ;
        Serial.write(client.read()) ;
       }

       /*delay(500); // Can be changed
      if (client.connected()) {
        client.stop();  // DISCONNECT FROM THE SERVER
      }*/
      Serial.println();
      Serial.println("closing connection");
      delay(5000);
    }

**NOTE**: this is my fixed url
*http://187.201.44.110/wsCo2Keellingv1002/wsCo2Keelling.asmx/GuardaInfoArduino?info=Micanton|2017-06-09 12:00|25*

**EDIT**

This is my Post format:

    POST /wsCo2Keellingv1002/wsCo2Keelling.asmx/GuardaInfoArduino HTTP/1.1
    Host: localhost
    Content-Type: application/x-www-form-urlencoded
    Content-Length: length
    info=string

body:
You are lacking the required blank line between the headers and the content. Also your content length is wrong.

Change

    client.print(postiu.length());

Into

    client.println(Cadenadatos.length());


message:
HMC5883L not working in continuous mode!

I'm just starting with the HMC5883L, I'm writing my code with C and also my own I2C library.

I noticed that the values on the Arduino IDE's serial monitor are constant.

Then I developed a function to read the mode register. So the value should be 0x00 for continuous mode.

But, what I get is that the device work in single mode which has the value 0x01 at first cycle of the program, then it goes to idle mode with the value 0x03.

So, why is that and what to do?

    #include <I2C.h>

    #define HMC5883L_read   0x3D
    #define HMC5883L_write  0x3C

    #define Configuration_Register_A    0x00  //Read/Write
    #define Configuration_Register_B    0x01  //Read/Write
    #define Mode_Register               0x02  //Read/Write
    #define Data_Output_X_MSB_Register  0x03  //Read
    #define Data_Output_X_LSB_Register  0x04  //Read
    #define Data_Output_Z_MSB_Register  0x05  //Read
    #define Data_Output_Z_LSB_Register  0x06  //Read
    #define Data_Output_Y_MSB_Register  0x07  //Read
    #define Data_Output_Y_LSB_Register  0x08  //Read
    #define Status_Register             0x09  //Read
    #define Identification_Register_A   0x10  //Read
    #define Identification_Register_B   0x11  //Read
    #define Identification_Register_C   0x12  //Read
    #define declination_angle 3.46

    void HMC5883L_init (void);
    int16_t data_read (int16_t *results);
    uint8_t HMC5883L_read_reg (uint8_t reg);

    int16_t results[3];
    float m_scale = 1.0;

    void setup() {
      // put your setup code here, to run once:
      I2C_init();
      Serial.begin(9600);
      HMC5883L_init();
      Serial.print("mode register ");
      HMC5883L_read_reg(Mode_Register);
      Serial.println();
    }

    void loop() {
      // put your main code here, to run repeatedly:
      data_read(results);
      Serial.print("x-axis = ");
      Serial.println(results[0]);
      Serial.print("z-axis = ");
      Serial.println(results[1]);
      Serial.print("y-axis = ");
      Serial.println(results[2]);
      Serial.println();
      Serial.print("mode register ");
      HMC5883L_read_reg(Mode_Register);
      Serial.println();
    _delay_ms(500);
    }

    void HMC5883L_init (void)
    {
      I2C_start(HMC5883L_write);
      I2C_tx(Configuration_Register_A);
      I2C_tx(0x07);
      I2C_tx(Configuration_Register_B);
      I2C_tx(0x01);
      I2C_tx(Mode_Register);
      I2C_tx(0x00);
      I2C_stop();
    }

    int16_t data_read (int16_t *results)
    {
      uint16_t lsb,msb;
      int16_t status_of_process = 0;
      I2C_start(HMC5883L_write);
      I2C_tx(Data_Output_X_MSB_Register);
      I2C_start(HMC5883L_read);

      msb = I2C_rx();
      lsb = I2C_rx();
      results[0] = msb << 8 | lsb;

      msb = I2C_rx();
      lsb = I2C_rx();
      results[1] = msb << 8 | lsb;

      msb = I2C_rx();
      lsb = I2C_rx();
      results[2] = msb << 8 | lsb;

      I2C_stop();

      return status_of_process;
    }

    uint8_t HMC5883L_read_reg (uint8_t reg)
    {
      uint8_t reg_dat;
      I2C_start(HMC5883L_write);
      I2C_tx(reg);
      I2C_start(HMC5883L_read);
      reg_dat = I2C_rx();
      Serial.println(reg_dat);
    }

Regards,

body:
The problem stems from this function:

    void HMC5883L_init (void)
    {
      I2C_start(HMC5883L_write);
      I2C_tx(Configuration_Register_A);
      I2C_tx(0x07);
      I2C_tx(Configuration_Register_B);
      I2C_tx(0x01);
      I2C_tx(Mode_Register);
      I2C_tx(0x00);
      I2C_stop();
    }

The way I2C in most chips work, when writing, is that the first byte defines the register to write to. All subsequent bytes are the data to write into that register and successive registers.

> To minimize the communication between the master and this device, the address pointer updated automatically without
master intervention. This automatic address pointer update has two additional features. First when address 12 or higher
is accessed the pointer updates to address 00 and secondly when address 08 is reached, the pointer rolls back to
address 03.

So you are actually writing:

    REG  CONTENT
    0x00 0x07
    0x01 Configuration_Register_B (0x01)
    0x02 0x01
    0x03 Mode_Register (0x02)
    0x04 0x00

You need to either start a new transaction for each register you want to set a value in (*explicit* setting) or rely on the address pointer increment to move to the right register for you (*implicit* setting).

So either:

    void HMC5883L_init (void)
    {
      I2C_start(HMC5883L_write);
      I2C_tx(Configuration_Register_A);
      I2C_tx(0x07);
      I2C_stop();

      I2C_start(HMC5883L_write);
      I2C_tx(Configuration_Register_B);
      I2C_tx(0x01);
      I2C_stop();

      I2C_start(HMC5883L_write);
      I2C_tx(Mode_Register);
      I2C_tx(0x00);
      I2C_stop();
    }

Or, since the registers are in sequence in the address space:

    void HMC5883L_init (void)
    {
      I2C_start(HMC5883L_write);
      I2C_tx(Configuration_Register_A);
      I2C_tx(0x07);
      I2C_tx(0x01);
      I2C_tx(0x00);
      I2C_stop();
    }

Oh, and don't forget to have an `I2C_stop()` after reading your register in:

    uint8_t HMC5883L_read_reg (uint8_t reg)
    {
      uint8_t reg_dat;
      I2C_start(HMC5883L_write);
      I2C_tx(reg);
      I2C_start(HMC5883L_read);
      reg_dat = I2C_rx();
      I2C_stop(); // <----- MISSING
      Serial.println(reg_dat);
    }