text:
RFID Code (and setup) works on an UNO but not on the Yun
We're using two RDM6300 RFID readers for this, and the code works when plugged into an UNO, but not when connected to the Yun. We have one of the rfids plugged into the rx pin (0 on the digital side) and the other plugged into pin 2 (same exact way we had it working on the UNO). Anyway, is there something majorly different between working with just sketches on Yun vs UNO? This code doesn't even involve using the Linux side yet as we couldn't get this major part figured out. Any help would be appreciated
#include <SoftwareSerial.h>

    //2nd RFID using SoftwareSerial
    SoftwareSerial RFID(2, 3); // RX and TX

    // define constants for pins
    int UNLOCK = 8;

    // variables to keep state
    int readVal = 0; // individual character read from serial
    unsigned int readData[10]; // data read from serial
    int counter = -1; // counter to keep position in the buffer
    char tagId[11]; // final tag ID converted to a string

    char* authorizedTags[4]; // array to hold the list of authorized tags

    // fills the list of authorzied tags
    void initAuthorizedTags() {
      //tags
      authorizedTags[0] = "02006750B7";
      authorizedTags[1] = "02006750B1";
      authorizedTags[2] = "02006750B2";
      authorizedTags[3] = "02006750B3";
      authorizedTags[4] = "02006750B4";
    }

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

      //start serial to RFID reader2
      RFID.begin(9600);

      pinMode(UNLOCK, OUTPUT);
    //  pinMode(SUCCESS, OUTPUT);
    //  pinMode(ERROR, OUTPUT);
      initAuthorizedTags();
    }

    // check if the tag ID we just read is any of the authorized tags
    int checkTag() {
      int i;

      for (i = 0; i < 4; ++i) {
        if (strcmp(authorizedTags[i], tagId) == 0) {
          return 1;
        }
      }
      return 0;
    }

    // convert the int values read from serial to ASCII chars
    void parseTag() {
      int i;
      for (i = 0; i < 10; ++i) {
        tagId[i] = readData[i];
      }
      tagId[10] = 0;
    }

    // once a whole tag is read, process it
    void processTag() {
      // convert id to a string
      parseTag();

      // print it
      printTag();

      // check if the tag is authorized
      if (checkTag() == 1) {
        tagSuccess(); // unlock solenoid
      } else {
        tagFailed();
      }
    }

    void printTag() {
      Serial.print("Tag value: ");
      Serial.println(tagId);
    }

    // perform an action when an authorized tag was read
    void tagSuccess() {
      Serial.println("Tag authorized.");

      //activate solenoid,
      digitalWrite(8, HIGH);
      delay(3000);
      digitalWrite(8, LOW);
    }

    // inform the user that the tag is not authorized
    void tagFailed() {
      Serial.println("Unauthorized access!");

    }

    // this function clears the rest of data on the serial, to prevent multiple scans
    void clearSerial() {
      while (Serial.read() >= 0) {
        ; // do nothing
      }
    }

    void loop() {

    //RFID 1
      if (Serial.available() > 0) {

        // read the incoming byte:
        readVal = Serial.read();

        // a "2" signals the beginning of a tag
        if (readVal == 2) {
          counter = 0; // start reading
        }
        // a "3" signals the end of a tag
        else if (readVal == 3) {
          // process the tag we just read
          processTag();

          // clear serial to prevent multiple reads
          clearSerial();

          // reset reading state
          counter = -1;
        }
        // if we are in the middle of reading a tag
        else if (counter >= 0) {
          // save valuee
          readData[counter] = readVal;

          // increment counter
          ++counter;
        }
      }

    if (RFID.available() > 0)
    {
        // read the incoming byte:
        readVal = RFID.read();

        // a "2" signals the beginning of a tag
        if (readVal == 2) {
          counter = 0; // start reading
        }
        // a "3" signals the end of a tag
        else if (readVal == 3) {
          // process the tag we just read
          processTag();

          // clear serial to prevent multiple reads
          clearSerial();

          // reset reading state
          counter = -1;
        }
        // if we are in the middle of reading a tag
        else if (counter >= 0) {
          // save valuee
          readData[counter] = readVal;

          // increment counter
          ++counter;
        }
    }

    }

Does it work for one reader?

Nope. Please don't tell me it's incompatible with the Yun...

I doubt that. Its a basic serial device. Have you communicated with anything over serial with the Yun?

Are you using the Yun over WiFi?

it does have wifi access currently, but it's not in use. When we present the project it will be connected via ethernet. And I have not, this was the only thing I've tried using serial with it.

If you're using it over USB then, try communicating with your PC with a simple sketch to print something to Serial

yep, Serial.prinltn("whatever"); works

From what I found, Serial is reserved for comms between the atmega32u4 and the PC, while Serial1 (on pins 0 and 1) is reserved for comms btw the Arduino and Linux parts of the Yun. You have to use 2 SoftwareSerial ports for your project; and it seems even that option is buggy on the Yun. But try with one reader anyways; disconnect the other from pins 0 and 1 and try printing whatever you read from the SoftSerial reader to the PC; keep the sketch simple

Okay so, I was already using the SoftwareSerial for the second (and tested it when testing one or the other) and it didn't work on pin 2,3. So I searched that issue and apparently you can't use pins below 8 for rx/tx so I moved it to 8,9 and now works. http://forum.arduino.cc/index.php?topic=228470.0  But now the issue will be to use two software serials as I hear that's annoying too, but that's also a different question I guess

You'll just have to call listen() whenever you want to read from a particular reader. You're already reading them in order in your code, so it shouldnt be too much trouble, to call listen() and then prompt a user to present a card for reading


text:
No response from device when trying to communicate with it via RS-232
I have an Arduino Uno with an RS-232 shield, and a servo drive that communicates via CAN or RS-232. I'm trying to communicate with this drive using an RS-232 cable, but I'm getting no response. I'm using the SoftwareSerial library on the Arduino to use digital pins 3 and 2 as rx and tx. Only pins 2 (RxD), 3 (TxD), and 5 (GND) of RS-232 are used to communicate with the drive. 19,200 is the default baud rate for the drive. The drive is powered with a dedicated power supply. The drive is supposed to echo every character received back to the sender.
I've had success using a simple Java program to communicate with the drive using the same kind of cable (although with a USB-to-serial converter). The drive echos all characters back, and the motor responds to the commands sent to the drive. The cable used has a female DB9 connector on one end (to communicate with the desktop) and a custom 3 pin connector on the other (to communicate with the drive).
I've also had success with the same Java program communicating with the Arduino (also with the converter). This cable has a female DB9 connector on one end (to communicate with the desktop) and a male DB9 connector on the other (to communicate with the Arduino).
But I've had no success exchanging data between the Arduino and the drive. There is no response back from the drive nor does the motor respond to any commands. The cable used for this has a male DB9 connector on one end (to communicate with the Arduino) and a custom 3 pin connector on the other (to communicate with the drive).
Each cable has been tested with a voltmeter to confirm that pins on one end are connected to the correct pins on the other end.
I'm at a loss here. Is there something I'm missing?
For your consideration, here is the Arduino code. It is the same whether it is connected to the desktop or the drive.
#include <SoftwareSerial.h>
#include <SPI.h>

const int rx = 3;               // software serial receive pin
const int tx = 2;               // software serial transmit pin
const int baudRate = 19200;     // 19,200 bits per second for read and write serial functions

SoftwareSerial serial(rx, tx);

/*
 * Initial, one-time setup
 */
void setup()
{
    Serial.begin(baudRate);     // open hardware serial communications
    serial.begin(baudRate);     // open software serial communications

    serial.println("MO=1;");      // start motor
    serial.println("JV=30000;");  // set velocity to 30,000 counts/second
    serial.println("BG;");        // begin movement
}

/*
 * Executes every tick
 */
void loop()
{
    if (serial.available())
    {
        Serial.write(serial.read());
    }

    if (Serial.available())
    {
        serial.write(Serial.read());
    }
}

Also, here is the Java code.
import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;

import java.io.FileDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class TwoWaySerialComm
{
    public TwoWaySerialComm()
    {
        super();
    }

    void connect(String portName) throws Exception
    {
        CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
        if (portIdentifier.isCurrentlyOwned())
        {
            System.out.println("Error: Port is currently in use");
        }
        else
        {
            CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000);

            if (commPort instanceof SerialPort)
            {
                SerialPort serialPort = (SerialPort)commPort;
                serialPort.setSerialPortParams(19200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

                InputStream in = serialPort.getInputStream();
                OutputStream out = serialPort.getOutputStream();

                (new Thread(new SerialReader(in))).start();
                (new Thread(new SerialWriter(out))).start();

            }
            else
            {
                System.out.println("Error: Only serial ports are handled by this example.");
            }
        }
    }

    /** */
    public static class SerialReader implements Runnable
    {
        InputStream in;

        public SerialReader(InputStream in)
        {
            this.in = in;
        }

        public void run()
        {
            byte[] buffer = new byte[1024];
            int len = -1;
            try
            {
                while ((len = this.in.read(buffer)) > -1)
                {
                    System.out.print(new String(buffer, 0, len));
                }
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }

    /** */
    public static class SerialWriter implements Runnable
    {
        OutputStream out;

        public SerialWriter(OutputStream out)
        {
            this.out = out;
        }

        public void run()
        {
            try
            {
                int c = 0;
                while ((c = System.in.read()) > -1)
                {
                    //System.out.print(c);
                    this.out.write(c);
                }
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args)
    {
        try
        {
            (new TwoWaySerialComm()).connect("COM4");  // COM4 is port of USB-to-serial converter
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

I've found the issue. The serial cable I was using was too long, introducing resistance to the signal. That's it!

source: Stack Exchange

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

sort: votes


text:
No Response from ESP8266 WIFI
I am getting no response back from an ESP8266 WIFI with Arduino Mega using library ITEADLIB_Arduino_WeeESP8266.
//serial monitor response

setup begin

FW Version:

to station + softap ok

Join AP success

IP:

single ok

setup end

create tcp ok

release tcp ok

create tcp ok

Arduino Mega Code
#include "ESP8266.h"
#include <SoftwareSerial.h>

#define SSID        "atmel"
#define PASSWORD    "bets12345"
#define HOST_NAME   "www.google.com"
#define HOST_PORT   (80)

SoftwareSerial mySerial(10, 11); /* RX:D3, TX:D2 */ ESP8266 wifi(mySerial);

void setup(void) {
  Serial.begin(9600);
  Serial.print("setup begin\r\n");
  Serial.print("FW Version:");
  Serial.println(wifi.getVersion().c_str());
  if (wifi.setOprToStationSoftAP()) {
    Serial.print("to station + softap ok\r\n");
  } else {
    Serial.print("to station + softap err\r\n");
  }
  if (wifi.joinAP(SSID, PASSWORD)) {
    Serial.print("Join AP success\r\n");
    Serial.print("IP:");
    Serial.println( wifi.getLocalIP().c_str());
  } else {
    Serial.print("Join AP failure\r\n");
  }
  if (wifi.disableMUX()) {
    Serial.print("single ok\r\n");
  } else {
    Serial.print("single err\r\n");
  }
  Serial.print("setup end\r\n");
}

void loop(void) {
  uint8_t buffer[128] = {0};
  if (wifi.createTCP(HOST_NAME, HOST_PORT)) {
    Serial.print("create tcp ok\r\n");
  } else {
    Serial.print("create tcp err\r\n");
  }
  char *hello = "Hello, this is client!";
  wifi.send((const uint8_t*)hello, strlen(hello));
  uint32_t len = wifi.recv(buffer, sizeof(buffer), 10000);
  if (len > 0) {
    Serial.print("Received:[");
    for(uint32_t i = 0; i < len; i++) {
      Serial.print((char)buffer[i]);
    }
    Serial.print("]\r\n");
  }
  if (wifi.releaseTCP()) {
    Serial.print("release tcp ok\r\n");
  } else {
    Serial.print("release tcp err\r\n");
  }
  delay(5000);
}

Have you tried a hard reset?

Rx and Tx properly crossed - SwSerial Rx to ESP Tx and SwSerial Tx to ESP Rx? And the connections are sound? It wouldn't be the first time "someone" thought he'd killed an ESP, only to find a missing connection from its transmitter (not that I'd know anything about that ..... ;)

Have you remembered to logic shift the ESP8266 from 3.3v to 5v?
Any by no response, do you mean no response from your web server or the board itself?

ya 3.3 V is ok,AT command work fine,using library ITEADLIB_Arduino_WeeESP8266,no response print back in serial monitor.as describe above.

just like we want to get version of it.Serial.println(wifi.getVersion().c_str());,no response printed.

If you send it "AT+GMR", does it respond then?

If you look in the source code for the library, wifi.getVersion() sends AT+GMR and returns it. I think the GMR command was added in a firmware update, which could mean you are running an old firmware which does not support AT+GMR

If you are using an ESP-01 board (which is an ESP8266 based board)
You should try running the ESP8266 from an independent 3.3V power supply.
The Arduino Mega 3.3V pin only supplies up to 50mA, wheres as the ESP8266 requires up to 200mA.
Also, make sure the CH_PD and RESET pins are held high (connected to the 3.3V).
Because you're using an Arduino Mega, you might find it beneficial to use pins 16 and 17, and Serial2 instead of software serial.
Internet sources indicate that they are sometimes set up with a baud rate of either 9600, 57600 or 115200. I managed to get mine working with 115200, but software serial is limited to a baud rate of 19200.

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


text:
Parallel Chaining of APA102 LED matrices
I have four APA102 LED matrices (those flexible ones) and I want to connect them together to make a display for showing images. Now my problem is this:
Consider the coordinate system with four quadrants. I put one matrix in each of the quadrant and my target is to have a one single display as mentioned above. I connect like this: The input of matrix 1 is connected to Arduino, the output of matrix 1 to input of matrix 2, output of matrix 2 to input of matrix 3 (or can be input of 4 also ) and then finally output of 3 (or output of 4th matrix) is connected to input of 4th matrix (or input of 3rd matrix accordingly).
The problem with this is that although this might seem a big display from a distance with 4 matrices working in sync but actually its 4 matrices daisy chained and split into 2 rows. This would split my image if I were to display.
Question: Is it possible to parallel chain these APA102 matrices and thereby form one continuous display which can be controlled by FASTLED library?? I might be somehow able to address an individual LED in this type of weird pattern, but while displaying images, I am lost. Can't figure out how to do that? Realised that I need to have parallel chaining.....which I have no idea of.
Any help, guidance would be great!
Thanks

It's a problem that can easily be fixed in software. Some libraries support this kind of paneling out of the box.

@Gerben Thanks bro! I managed to do a very simple yet effective solution: I split the bitmap data depending on the total number of columns of those flexible matrix (continuous serpentine):P ...

How about write up an answer and share it with us?


text:
How much code can an Arduino board run?
I'm getting back up and running with microcontrollers after about 5 years of hibernation time, and I am trying to understand a lot of different things. I have been experimenting with Arduinos for the past few weeks and am having a ton of fun. I'm a software engineer by day and a hardware hacker / manufacturer by night. At my day job, I write scripts and applications that are thousands of lines long and highly complex, using external libraries of thousands more lines of code, etc. These are full-fledge, professional software applications.
So, here is my question. Is the Arduino capable of running full-fledged robotics and other large, complex hardware applications, or is it more of a tinkering, hobbyist tool?
How big of a project can be built using Arduino? Are there memory concerns? Can an Arduino run thousands and thousands of lines of code out of the box, and if not, is there a way to add more memory for larger, more complex projects?

There are several "Arduinos" with memory capacities ranging from slightly less than 32k/2k/16MHz (Flash/RAM/CPUClock) ("Uno") to 512k/96k/84MHz ("Due".)  In addition, there are "mostly compatible" boards that expand that range down to less than 8k/512/8MHz ("Gemma", "Digistump") and up to about 1M/256k/120MHz (TI "EK-TM4C1294XL Launchpad"), and "somewhat compatible" boards with 4G/1G/400MHz (Intel "Edison")
Whether these are sufficient for "full fledged robotics" depends on what you consider that to mean.  Edison is probably the only contender if you wanted to include computer vision, for example, and it probably doesn't do that very well. ("What did you expect at ONLY 1 core at 400MHz?!")
The small Arduinos probably do not support your "very large libraries", either.  For example, while the "Arduino Language" is technically C++, support for the C++ STL is not included due to limitations of the small CPUs used and their run-time environment.
32k of program memory (on the popular Uno) is sufficient for "thousands of lines of code", but I'd think robotics would tend to run toward much more than that.  The small amount of RAM available on most of the flash-based microcontrollers also tends to be a serious limitation when you start looking at standard data-intensive algorithms.  32k/2k disappears quite quickly if you start implementing an extensive user interface, networking, or graphics.  I would say that an Uno-class Arduino is suitable for implementing COMPONENTS of robotics systems (motor drivers, sensor management, etc), but probably not a whole robot.
A good example of large robotics-like software that runs on Arduino-class hardware can probably be found in the 3D Printer space.  "Marlin" firmware runs on an Arduino Mega or equivalent (256k/8k/16MHz) (with RAMPS shield), and there are alternative driver packages that run on smaller and larger arduino-like hardware.  Marlin is about 280k lines of code, according to cloc.
Most Arduino hardware does NOT have expandable memory.  The AVR cpus cannot run code except from their internal Flash, and few of the other boards have any sort of memory bus that could be used for expansion.

(Ahem) The Intel Edison is dual-core @ 500MHz...

Ah; it's the Galileo that is 400MHz...

These days the ESP8266 and ESP32 are more or less arduino compatible and they have huge amounts of RAM and storage. Consider these as well.

No accepted or up-voted answers, eh? I'll try my hand. :)

How big of a project can be built using Arduino?

Depends on the model. You can go from around 4 KB of programmable memory to 256 KB, and then get into the larger models like the Due (512 KB).

Are there memory concerns?

There are always memory concerns, however when you have gigabytes of RAM (like on your PC) you tend to ignore them.
These are microcontrollers, designed for embedded applications. You will find yourself probably wishing you had more of everything (RAM, PROGMEM and EEPROM). However for many applications what they have is absolutely fine.

Can an Arduino run thousands and thousands of lines of code out of the box

Probably not. Consider the Uno with 32 KB of program memory. At from two to four bytes per machine instruction (most are two bytes), you are probably going to fit at most:
32768 / 2 = 16384

... machine instructions. So no, not hundreds of thousands. The larger models, maybe.

and if not, is there a way to add more memory for larger, more complex projects?

The Atmega2560 has expandable RAM, for example here which adds 512 KB of RAM.

How big of a project can be built using Arduino?

I have quite a few around the place here doing their own things. One lets me know if I left the garage door open accidentally. I look upon them as being useful for "helper" applications. I wouldn't try to put my SQL database on one.

The AVR machine instructions are all two-byte long, except for jmp,call, lds and sts, which are 4 bytes each.

Ach, I was thinking of clock cycles, which are what is documented in the main datasheet. Thanks for the correction, I amended my answer.

@NickGammon "There are always memory concerns, however when you have gigabytes of RAM (like on your PC) you tend to ignore them." And alas, today's programmers (whippersnappers the lot of 'em!) have lost that realisation... If they could put a bit more effort in optimisation, they'd halve the size of many programs - if not more!

Well, I wasn't counting myself in that group *grin* - my first computer had 512 bytes of RAM (which was also used for code) so I had to program conservatively. I agree though, that thinking you have unlimited memory, and unlimited speed to spare, can lead to careless programming.

Although Arduino is more of a hobbyist electronics board, it can handle complex projects depending on which board you use. The Mega has 54 input pins, so can handle loads of devices and has much more memory and storage. See the Uno - Mega specs below

The ATmega328 chip found on the Uno has the following amounts of memory:
  Flash  32k bytes (of which .5k is used for the bootloader)
  SRAM   2k bytes
  EEPROM 1k byte
The ATmega2560 in the Mega2560 has larger memory space :
  Flash  256k bytes (of which 8k is used for the bootloader)
  SRAM   8k bytes
  EEPROM 4k byte


text:
Get MP3 play length
I'm creating a project where music gets played that is the same length or slightly shorter than the given time (minutes:seconds). For this I have a Sparkfun MP3 shield, which also has a microSD slot.
The issue is that I can't find a way to get the playtime of a given MP3 file. The only idea that I have is using the filesize and bitrate, but that would be horribly annoying for multiple bitrates.
Thanks in advance,
Michidez

You could try parsing the ID3 data of the MP3. Or just create a separate file containing the length. Or maybe encode the length in the filename (e.g. mozart-154s.mp3).


text:
What is a flag in programming Arduino?
I have seen many tutorials on programming an Arduino to control a HC-05 bluetooth module. In that I did not understand the term called 'flag'. What does that mean?

And what is the context of this word?

"Flag" is usually a feature that you can turn on or off. The "flag" is the variable that you need to use to do that. But as Majenko stated, with no context, it's just a guess I am taking here.

I've always used flag to indicate a boolean logic value. I would also suggest this is an archaic term.
Was going to come up with my own explanation but found the following at In C language, what does flag mean?:

A 'flag' is a variable that is supposed to signalize something. Think
  about the word itself - flags are used in sending signals. In our
  world of programming a basic boolean flag can either be "up" or
  "down", either true or false.


text:
Help! Interfacing LCD with Arduino using 8255A Intel peripherals
I'm new to all this stuff and for the past two days, I have been trying to interface a 16x2 LCD to an Arduino Uno using an Intel 8255A component without any luck. The problem is, how can I attach or set the LCD's pins <> to the unknown pins of the 8255A.
Is it even possible?
Thanks for any kind of help.

8255!!!! Where did you find it?!?!

haha from this https://www.google.com/search?q=8255A+intel&biw=1366&bih=640&source=lnms&tbm=isch&sa=X&ved=0ahUKEwjLp5aD3qLMAhXsJZoKHRJrBUMQ_AUICSgD#imgrc=KVpfZFZBqOuJlM%3A

What are unknowing pins?

i'm talking about the i/o of 8255 component, they are unknowing for Arduino IDE, how can i make them as inputs for LiquidCrystal lcd(12, 11, 5, 4, 3, 2),  this is my problem :/

@HamzaTST i meant where you found the actual component. I haven't seen one, much less used one, since 1985!

also, why are you bothering with the 8255 and not driving the display directly with the arduino pins? Do you plan to connect it on some other system, such as an intel 8085? :)

yes this is why, because i have much less pins to connect such LCD and some others component, you have an idea @JayEye ;)

I'd use something like a Teensy 3.2, it has 30+ gpio pins, and much easier to come by than the 8055 (again, unless you want to attach this to some retrocomputing project).

Thanks @JayEye for your advice, this is what im gonna do :)

You will not be able to use 8255 pins as parameters to the the LiquidCrystal library without making substantial changes to either the library or the Arduino core.
The reason is that to configure or change a pin on the 8255, you will need to go through a series of operations manipulating the ATmega pins to which the 8255's microprocessor bus interface is connected.  You can learn about the necessary operations by reading the 8255 data sheet.  Also keep in mind that the 8255 does not have per-pin configuration - rather, the first two ports must each be either entirely inputs or entirely outputs, while there third port can be split in half.
Once you know how to set a pin, you will need to have the liquid crystal functionality trigger these operations.
One approach would be to create a heavily modified version of the library which knows how to work through the 8255.
Another would be to create a modified version of the Arduino core which has additional pin numbers corresponding to the 8255's pins, and generates code which does the necessary intermediate bus operations to access them.  However this will be quite challenging - you have to make sure the intermediate code gets in there in all paths, and figure out how it will handle cases where code tries to set pins that must have the same mode to conflicting modes.
As others have said, you would practically be better off using a different MCU with more I/Os - either an Arduino Mega, or one of the ARM-based boards.

Thanks @Chris Stratton for your advice, this is what im gonna do :)


text:
Reading SD card with Sparkfun MP3 Shield
So I am using an Arduino Mega with the Sparkfun MP3 shield. And I can't seem to read the µSD card. It's formatted in FAT32 and it has a single .txt file on it. I always get this error:
SD initialization failed.
Do not reformat the card!
Is the card correctly inserted?
Is chipSelect set to the correct value?
Is there a wiring/soldering problem?
errorCode: 0x1, errorData: 0xff

I have tried chipSelect 8,9 and 10. I've seen all the other forum threads about the error but none apply here as it is a bought board and not self built, so the wiring should be correct. I've tried software that has ran on the same configuration, and I get the same error.
Thanks in advance,
Michidez
The code that I use to try the SD card (QuickStart, from the SdFat Library):
// Quick hardware test
#include <SdFat.h>
// Test with reduced SPI speed for breadboards.
// Change spiSpeed to SPI_FULL_SPEED for better performance
// Use SPI_QUARTER_SPEED for even slower SPI bus speed
const uint8_t spiSpeed = SPI_HALF_SPEED;
//------------------------------------------------------------------------------
// Normally SdFat is used in applications in place
// of Sd2Card, SdVolume, and SdFile for root.
Sd2Card card;
SdVolume volume;
SdFile root;

// Serial streams
ArduinoOutStream cout(Serial);

// input buffer for line
char cinBuf[40];
ArduinoInStream cin(Serial, cinBuf, sizeof(cinBuf));

// SD card chip select
int chipSelect;

void cardOrSpeed() {
  cout << pstr(
    "Try another SD card or reduce the SPI bus speed.\n"
    "The current SPI speed is: ");
  uint8_t divisor = 1;
  for (uint8_t i = 0; i < spiSpeed; i++) divisor *= 2;
  cout << F_CPU * 0.5e-6 / divisor << pstr(" MHz\n");
  cout << pstr("Edit spiSpeed in this sketch to change it.\n");
}

void reformatMsg() {
  cout << pstr("Try reformatting the card.  For best results use\n");
  cout << pstr("the SdFormatter sketch in SdFat/examples or download\n");
  cout << pstr("and use SDFormatter from www.sdcard.org/consumer.\n");
}

void setup() {
  Serial.begin(9600);
  while (!Serial) {}  // wait for Leonardo

  cout << pstr(
    "\nSD chip select is the key hardware option.\n"
    "Common values are:\n"
    "Arduino Ethernet shield, pin 4\n"
    "Sparkfun SD shield, pin 8\n"
    "Adafruit SD shields and modules, pin 10\n");
}

bool firstTry = true;
void loop() {
  // read any existing Serial data
  while (Serial.read() >= 0) {}

  if (!firstTry) cout << pstr("\nRestarting\n");
  firstTry = false;

  cout << pstr("\nEnter the chip select pin number: ");
  cin.readline();
  if (cin >> chipSelect) {
    cout << chipSelect << endl;
  } else {
    cout << pstr("\nInvalid pin number\n");
    return;
  }
  if (!card.init(spiSpeed, chipSelect)) {
    cout << pstr(
      "\nSD initialization failed.\n"
      "Do not reformat the card!\n"
      "Is the card correctly inserted?\n"
      "Is chipSelect set to the correct value?\n"
      "Is there a wiring/soldering problem?\n");
    cout << pstr("errorCode: ") << hex << showbase << int(card.errorCode());
    cout << pstr(", errorData: ") << int(card.errorData());
    cout << dec << noshowbase << endl;
    return;
  }
  cout << pstr("\nCard successfully initialized.\n");
  cout << endl;

  uint32_t size = card.cardSize();
  if (size == 0) {
    cout << pstr("Can't determine the card size.\n");
    cardOrSpeed();
    return;
  }
  uint32_t sizeMB = 0.000512 * size + 0.5;
  cout << pstr("Card size: ") << sizeMB;
  cout << pstr(" MB (MB = 1,000,000 bytes)\n");
  cout << endl;

  if (!volume.init(&card)) {
    if (card.errorCode()) {
      cout << pstr("Can't read the card.\n");
      cardOrSpeed();
    } else {
      cout << pstr("Can't find a valid FAT16/FAT32 partition.\n");
      reformatMsg();
    }
    return;
  }
  cout << pstr("Volume is FAT") << int(volume.fatType());
  cout << pstr(", Cluster size (bytes): ") << 512L * volume.blocksPerCluster();
  cout << endl << endl;

  root.close();
  if (!root.openRoot(&volume)) {
    cout << pstr("Can't open root directory.\n");
    reformatMsg();
    return;
  }

cout << pstr("Files found (name date time size):\n");
  root.ls(LS_R | LS_DATE | LS_SIZE);

  if ((sizeMB > 1100 && volume.blocksPerCluster() < 64)
    || (sizeMB < 2200 && volume.fatType() == 32)) {
    cout << pstr("\nThis card should be reformatted for best performance.\n");
    cout << pstr("Use a cluster size of 32 KB for cards larger than 1 GB.\n");
    cout << pstr("Only cards larger than 2 GB should be formatted FAT32.\n");
    reformatMsg();
    return;
  }
  // read any existing Serial data
  while (Serial.read() >= 0) {}
  cout << pstr("\nSuccess!  Type any character to restart.\n");
  while (Serial.read() < 0) {}
}

It would help if you actually posted code.

Any code gives me the error. Including 2 examples from SdFat: QuickStart and SdInfo. But I'll add QuickStart to the post.

Firstly, where did you get the get the SdFat library from? A quick search on GitHub returned 34 results: GitHub search of SdFat. Of those, Greiman and Adafruit were the highest results on Google.
The reason I mention this is that you could be using a library that has issues or requires something specific in the hardware. I would suggest using the Adafruit version, as that would be the most scrutinized and hence the most stable. It appears very similar to the Arduino library (mentioned below).
Arduino has a SD library that comes with the Arduino IDE. It is simply called SD. There are 6 example programs:

CardInfo: SD card test - This example shows how use the utility libraries on which the'SD library is based in order to get info about your SD card. Very useful for testing a card when you're not sure whether its working or not.
ReadWrite:  SD card read/write - shows how to read and write data to and from an SD card file.
Files: SD card basic file example - shows how to create and destroy an SD card file.
ListFiles:  Listfiles - This example shows how print out the files in a
directory on a SD card.
DumpFile:   SD card file dump - shows how to read a file from the SD card using the SD library and send it over the serial port.
Datalogger: SD card datalogger - shows how to log data from three analog sensors.

Use the CardInfo example program to verify that your setup is correct. Then progress to one of the other examples such as ListFiles or Dumpfile.


text:
Connecting to WIFI using esp8266
This is my code. I am tring to make a connection to my wifi through esp8266.
#define DST_IP "192.168.1.5" // my IP
#include <SoftwareSerial.h>

SoftwareSerial mySerial(0, 1);

void setup()
{
  Serial.begin(115200);
  mySerial.begin(115200);
  while (! Serial); // Wait until Serial is ready - Leonardo
  Serial.println("AT+RST");
  delay(4000);
  Serial.println("AT+CWJAP=\"Ahmed\",\"12341234Aass\"");
  delay(4000);
  if (Serial.find("OK") )
  {
    Serial.println("1");
  }
  else
  {
    Serial.println("0");
  }
}

void loop()
{

}

This is the result of my code.

SoftwareSerial mySerial(0, 1);

try changing pin0 and pin1 with some other pins. (lets say with pin2 & pin3)
pin0 and pin1 are used by default Serial.

but pin0 and pin1 are my RX and TX .. is it true to work with any pin ?

yeh,  pin0 and pin1 are your RX and TX. BUT they are so, only when you are using Serial. In above mentioned line of code you are initializing another serial, mySeial, to use same pins as Serial which is the cause of error.

Thanks for replying BUT actually I use mySeial in nothing. So I removed it and still same error!

The point is that these pins are already used for the connection to the USB serial device proxying for the host PC.  You need to connect the ESP8266 to different pins, not to these.

Okay. I have set SoftwareSerial mySerial(0, 1); To SoftwareSerial mySerial(2, 3); But it always return 0 in the result which means it can not connect to the network.


text:
Wake up from sleep from pressed button?
#include <avr/sleep.h>
#include <avr/power.h>
//This sketch is a metronome, in which each led pin shows one beat.

const int speaker = 13;  //speaker at pin 13
int ts = 6;  //highest led pin
int count = 3;  //"beat 1 pin"
const int keyPin = 11;  //button to change time signature
const int keyPinR = 10;  //button to change rhythm
const int keySwitch = 2;  //sleep mode/wake up button

//All pins below use a pull-up resistor, so the states are inverted
int buttonState = LOW;
int buttonState2 = LOW;
int switchState = LOW;
int silentState = LOW;

int bpm = 120;  //you do not need to know this,
//it's just a variable for the potentiometer to change the tempo

int rthm = 1;  //rhythm
volatile int pressed = 0;
long silent = p;

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

   for(int thisPin = 3;thisPin <= ts;thisPin++)
   {
      pinMode(thisPin,OUTPUT); //initialize thisPin as an output
      pinMode(8, INPUT); //potentialmeter for changing temp
      //Pin 9 to 11, along with pin 2, are all push buttons with pull-up     resistors
      for(int i = 9; i<=11; i++)
      {
         pinMode(i, INPUT);
         digitalWrite(i, HIGH);
      }
         pinMode(2, INPUT);
         digitalWrite(2,HIGH);
   }
}

void loop()
{
   turnOn();
}

void turnOn()
{
    buttonState = digitalRead(keyPin);//key for
    buttonState2 = digitalRead(keyPinR);
    switchState = digitalRead(keySwitch);
    silentState = digitalRead(9);
    //Serial.println(switchState);
    if(switchState==LOW&&pressed==0)
    {
       sleep_enable();
       set_sleep_mode(SLEEP_MODE_PWR_DOWN);
       attachInterrupt(digitalPinToInterrupt(0), interrupt, LOW);
       sleep_cpu();
       //Serial.println(switchState);
    }
    else {
       //The beat starts at pin 3, runs in consecutive pins,
       //and ends at pin 8 at maximum
       if(buttonState==LOW)
       {  //changing time signature - up to 5 beats
           ts++;
           if(ts==8)
           {
              ts = 3;
              //8 - 3 = 5 beats max
           }
        }
        if(buttonState2==LOW)
        {  //changing rhythm - quarter note to eighth, then
          //triplets and sixteenths, back to quarter notes
          rthm++;
          if(rthm==5)
          rthm = 1;
 }

    if(silentState==LOW){//if silent key pressed, go to silence (only LED's showing)
    silent++;
  }

  //The RUN code
  for(int thisPin = 3;thisPin <= ts;thisPin++)
  //LED's blinking beats (thisPin - LED pin (beat number + 2))
 {

 for(int r = 1; r<=rthm; r++)
 {//nested loop for the rhythm
   bpm = pulseIn(8, HIGH);//pin 8 - tempo potentialmeter
   digitalWrite(thisPin,HIGH);//each LED blinks

   pinMode(13,OUTPUT); //pin 13 - speaker

   if(silent%2==0)//Press once, tone, press again, no tone
     noTone(13);
 else
 if(count == 3&&r==1). //first beat is higher
 tone(13,4400,80);
 else if(r==1). //downbeats slightly lower
 tone(13,2500,80);
 else
 tone(13,2200,60);  //off beats even lower
 delay((bpm-52)/rthm);
 digitalWrite(thisPin,LOW);  //turn each off as we proceed to the next beat (LED)
 pinMode(13,INPUT);  //speaker input
}
count++;  //beat++

if(count >ts){//go back to count
count = 3;
}

   }
  }
 }

void noSound()//silence the speaker
{
  noTone(13);
}

void interrupt()//this is where the sleep interrupt starts -               //how can i press it to wake up???
{
    sleep_disable();
    detachInterrupt(0);
    if(switchState==HIGH){
       pressed = 1;
       Serial.println(switchState);
       turnOn(); //go back to the main functional method (?????)
     }
 }

Once the keySwitch button is pressed (pin 2), the arduino goes to sleep; however, the only way to turn it on is by resetting everything. How can I just wake up the Arduino, keeping every state as before the sleep interrupt?

attachInterrupt(digitalPinToInterrupt(0), interrupt, LOW);

should be either
attachInterrupt(0, interrupt, LOW);

or
attachInterrupt(digitalPinToInterrupt(2), interrupt, LOW);

As pin 0 is not an interrupt pin. Also the button is connected to pin 2, not pin 0. digitalPinToInterrupt(0) would actually return -1.

It would be a lot more useful if you explained your apparent theory that the wrong pin is being monitored rather than just proposing an unexplained change to the code.

@ChrisStratton thanks for the suggestion. MikeZhou; you are welcome.


text:
Communication between IC and microcontroller (Teensy 3.2)
I am trying to use a rotary encoder with an integrated circuit to measure the position of a rotating shaft. I am then taking this data and writing to an SD card. The IC seems to be working correctly and outputting binary data to the specified pins,  but the data does not seem to be reaching the micro-controller. My output data is fragmented, and seems to only be receiving binary data from some of the IC pins. The IC I am using is HCTL-2021-A00 (http://www.mouser.com/ProductDetail/Avago-Technologies/HCTL-2021-A00/?qs=RuhU64sK2%252bsgeK17XZB%2fNA%3d%3d). I tried using a larger gauge wire to connect the two, but then the micro-controller didn't seem to pick up any of the data. Here is the code I used.
I am trying to use a rotary encoder with the HCTL-2021-A00 from avago. I am getting data output from the IC, but only one of the two bytes which it should be providing. When I move the encoder forward, it will only give me the LOW byte and all of the high bits will be zero. However, when I move the encoder backward, all of the high data bits are 1, and the low data bits still operate normally, counting the position. What could cause the high data bits to all be 1 when moving backward, and all 0 when moving forward? Code used is below.
#include <SD.h>
#include<SPI.h>

File datafile;
const int chipSelect = 10; // connected to the CS pin on the sd card, Make sure the card is formatted
int encoderpos=0;
int i=0;
int pulses, A_SIG=0, B_SIG=1;
int b[15];  //the individual bits of data read from the IC
int pos; //position output of IC ranging from 0 to 5000 for 1 revolution
int selpin=1, OEpin=2;
int clock=4;
int d[7]; //the pins on the IC attached to which digital teensy pins
double deg; //degree position of the servo as found from the encoder and IC

void setup()
{
  //set pwm signal for timer input
  pinMode(4, OUTPUT);
  analogWriteFrequency(4, 6000000); // Teensy 3.0 pin 3 also changes to 375 kHz
analogWrite(4, 128);
   //First setup and attach the pins used to communicate with the IC and encoder
  d[0]=22;//pin numbers for attaching the IC to the teensy
  d[1]=21;
  d[2]=20;
  d[3]=19;
  d[4]=18;
  d[5]=17;
  d[6]=16;
  d[7]=15;
//first set pins as inputs and outputs
pinMode(selpin, OUTPUT);
pinMode(OEpin, OUTPUT);
pinMode(d[0], INPUT);
pinMode(d[1], INPUT);
pinMode(d[2], INPUT);
pinMode(d[3], INPUT);
pinMode(d[4], INPUT);
pinMode(d[5], INPUT);
pinMode(d[6], INPUT);
pinMode(d[7], INPUT);

digitalWrite(selpin, HIGH);
digitalWrite(OEpin, HIGH);

pinMode(5, OUTPUT);

digitalWrite(5, HIGH);
delay(5);
digitalWrite(5, LOW);
delay(5);
digitalWrite(5, HIGH);
delay(5);

pinMode(chipSelect, OUTPUT);
SD.begin();
datafile=SD.open("c.txt", FILE_WRITE);
pinMode(7, INPUT);
pinMode(8, OUTPUT);

}

void loop()
{
datafile.println(pose());
if (millis()>4000)
{
  datafile.close();
}

delay(5);
}

int pose()     //Gives the position in degrees from the readings from encoder and IC for 0 to 5000 representing one revolution
{
    digitalWrite(selpin, LOW);     // The sel pin on the IC
  digitalWrite(OEpin, LOW);     // The OE pin on the IC
digitalWrite(4, HIGH);
digitalWrite(4, LOW);
analogWrite(4, 128);

  b[0]=digitalRead(d[0]);
  b[1]=digitalRead(d[1]);
  b[2]=digitalRead(d[2]);
  b[4]=digitalRead(d[4]);
  b[5]=digitalRead(d[5]);
  b[6]=digitalRead(d[6]);
  b[7]=digitalRead(d[7]);
if(digitalRead(7)==1)
{
  digitalWrite(8, HIGH);
}
else if(digitalRead(7)==0)
{
  digitalWrite(8, LOW);
}
  digitalWrite(selpin, HIGH);
digitalWrite(4, HIGH);
digitalWrite(4, LOW);
analogWrite(4, 128);

  b[8]=digitalRead(d[0]);
  b[9]=digitalRead(d[1]);
  b[10]=digitalRead(d[2]);
  b[11]=digitalRead(d[3]);
  b[12]=digitalRead(d[4]);
  b[13]=digitalRead(d[5]);
  b[14]=digitalRead(d[6]);
  b[15]=digitalRead(d[7]);

  digitalWrite(OEpin, HIGH);

  pos=0;
  i=8;
  for(i; i>0; i--)
  {
pos=2*pos+b[i-1];
  }

  i=16;
  for (i; i>8; i--)
  {
    pos=2*pos+b[i-1];
  }

  return pos;

}

I found the problem.
I had assumed that the rst pin was supposed to be held low unless you wanted to reset the count on the encoder, and was ignoring it the whole time. Once I held the reset pin high, the count started to show up.
As of now there are still problems, I cannot read the high byte from the IC.

Probably because you are still mishandling the clock

I also changed the clock to force up and down after changing sel and oe. These changes are now reflected in the code above. Would this still be incorrect?

Wanted to just put this in a comment but apparently still don't have the rep to do that, so taking a stab at answering.
Sounds to me like you are having physical layer corruption issues.  I highly doubt that your wires were too fine a gauge since these are just signal wires for SPI, however, it was instructive that you did that since larger wires seemed to make the problem worse, I would guess that you have too large capacitance on the wire for the datarate you have chosen.
When I am debugging any serial communications for the first time, the first thing I do until communication is reliable is to slow the data rate down.  Something like 10kHz should work in most cases.  See if this fixes the corrupted data.  If it does, go back to a finer gauge wire and then bump the speed back up til you see corruption issues.  If you have a logic analyzer or a scope you can get on the line, it will be very educational to see what is going on with your edge rates.

Would that just involve adding a delay in between the times I call the pose() function?

You seem to be overlooking (or at least mishandling) the fact that these parts are built with a bus interface where the /OE and SEL signals as well as the internal position data latch are sampled synchronously with a clock input which you do not seem to be driving.

You need to generate a low-to-high transition of the CLK signal to latch the count into the readout
You need to generate a high-to-low transition of the CLK signal to latch in chosen values of the /OE and SEL signals.

On second examination of your code, perhaps you are trying to use a free-running clock asynchronous to your reading.  That, however, is extremely unwise.  First, you don't know that a suitable clock edge will happen between when you set the /OE or SEL and when you try to read the data.  Next, you do not know that an undesired clock edge will not happen in the midst of reading data, causing you to end up with a corrupted value that contains some "old" bits from before the clock edge and some "new" bits from after.  This would be particularly bad if it happened across a transition such as 0b01111111 to 0b10000000 or similar...
You may have other problems as well - your question is not complete without a schematic diagram of how you have wired up this chip.

The IC has an internal inhibit to stop new data from being transfered to the pins after both OE and SEL are low, until both OE and SEL are high again. Unless I am mistaken, this means I won't have to worry about clock signals in the middle of data reading.

No, it doesn't - it would only mean that if you could verify that the critical clock transition occurred between when you set these signals and started reading, and not at some point in the midst of reading... which at present you can't.  Your asynchronous approach is fundamentally broken.  If you want to keep the free-running clock, at minimum you will have to have your program wait for suitable clock transitions between settings and readout.

Is there a way to get the OE and SEL signals to be syncronous with the clock? or any way to insure there is a clock transition after changing them without using a delay?

Either drive the clock explicitly in code after you set the control signals, or else read back the clock and wait for the necessary transition between setting the control signals and reading the data.


text:
Air data rate nRF24L01
I'm using two nRF24L01 to communicate with each other. I did the right setup and they worked fine, however I wanted to change the air data rate to a lower value, for more stability, as the datasheet says.
How can I setup the configuration for this?
After a small research I knew that you can change this using RF_DR
to change the value of the transmission, but I didn't really know how I could exactly write the correct code for this.
Another question: does this effect the range of the module? Or does it only affect the stability? And if not, then which code can I use to extend the range of these two modules ?

Which library are you using?

i'm using this library https://github.com/TMRh20/RF24

The documentation tells you how to do it. Did you try reading before coming here? It took me precisely 15 seconds to find it from the link you just provided: http://tmrh20.github.io/RF24/classRF24.html#aeb9920e7a95699748b003c4a839b0814

can you please tell me where to find it, i'm sorry but i honestly tried to do my best, so if you can, give me where did you find it

Did you click the link I provided?

yes i found it, thanks alot  , so can you help me with my second part of the question

Let us continue this discussion in chat.

Increasing stability will increase the (usable) range. At least a bit. You could try decreasing the packet size, to make it even more reliable. There is no way to increase the output-power (only decrease).
You could try different channels, and see which one gives you the best range in your application.
After that you have to get NRF24 modules, with external antennas and amplifiers.

According the nRF datasheet if you decrease the data rate it will definitely affect your range.
A lower data rate will increase your stability due to which the nRF can detect weaker signals (-102 dB at 250Kbps) due to this you can significantly increase the range (up to 1km theoretically).
Also if you need to increase your range further you can attach an antenna with a higher gain than what you already have.
No other software changes will affect the range other than reducing the transmission speed.

The documentation for the function you want is here.
Reducing the speed doesn't directly increase the range, but increased stability will have the knock-on effect that the fringes of transmission distance will be more reliable, making it appear that you have slightly greater distance.

Your claim about speed and range is untrue.  A narrower bandwidth signal has a greater power spectral density for a given total power output, a properly designed receiver listening for a narrower signal sees less total noise, and depending on architecture may see higher gain.  The data sheet is even explicit about some of this: " The 1Mbps data rate gives 3dB better receiver sensitivity compared
to 2Mbps."  However it also mentions that transmitting the same data at a slower rate increases the period of time during which it could be interfered with.

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


text:
MQ7 Readings are too high
I am currently trying to learn how to use my MQ 7 CO Standalone to read CO in the air around the sensor. Currently Im using this circuit using my Arduino Uno. I get results of 900-1000. Here's a Fritzing Schematic on my setup.
Currently this is the code I am using on the arduino:
[code]
int mqx_analogPin = A0; // connected to the output pin of MQ-X

void setup(){
  Serial.begin(9600); // open serial at 9600 bps
}

void loop()
{
  // give ample warmup time for readings to stabilize

  int mqx_value = analogRead(mqx_analogPin);
  Serial.println(mqx_value);

  delay(100); //Just here to slow down the output.
}

I'm following the setup from this Instructables:
http://www.instructables.com/id/Smoke-Detector/?ALLSTEPS
However his readings are around 150-200ppm outside. I'm unsure how to reach these values since im following basically everything from the guide. Does anyone any experience with a MQ7 sensor?
I've been reading I need to preheat the sensor but I can't find any circuit that clearly shows how to preheat an MQ7 sensor or find any code for the arduino.

You are following a flawed tutorial which does not correctly operate the heater - see the comment by "Gregory0" part way down the page.

I believe you just leave it running for 5 minutes before taking a reading.

Using of this sensor is a bit more complicated than that. You must cycle through 60 seconds of heating and 90 seconds of measurement cycles, during heating you need to provide 5V on its heater pins, during measurement you need to provide 1.4V, so you'll need transistor or some other PWM-controlled current limiter (Arduino pin can't provide enough current for sensor heating).
I've tried to explain all details and calibration process here: https://www.instructables.com/id/Arduino-CO-Monitor-Using-MQ-7-Sensor/

Yes, it is not easy, lot of details to MQ-7 is here: http://www.arduinohobby.euweb.cz/  in the section "Analysator CO"

While this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference.

Yes, thank you. That link can helps. A foreign text can transform Google. MQ7 is element for stable enviroment and continuous ranning. Long brake of Vcc influences of the sensor sensitivity and it takes  time to return it. Basically, the MQ7 is for observing of a hygienic limit CO as 100ppm continuously with a compatator. That limit should be adjusted with a calibration gas and RL resistance. Any other application is comlicated, see that link.  Josef


text:
Draw polygon on LCD from GPS latitude and longitude
I'm working on a personal project  (a usefully tool based on ublox GPS and Arduino Mega that can measure distance between 2 points, compute area, speed, save data on SD card)
Now I want to add new feature and when I show the area(in m^2) on LCD, I want to show the polygon built by more coordinates.
I tried all I know, I searched for solutions but without success.
How can I "scale down" coordinates to make them fit in a x,y system with max size (320*480, LCD size) ?

It's called "division"...? Surely you did it at school?

@majenko : I did the dividion at school. But there is a problem, eg:
Lat1 = 44.456798, Lng1 = 25.563478
Lat2 = 44.672323, Lng2 = 25.894578
Let say with this 2 points I want to draw a line on the LCD, I can draw it but on the display will be almost a single pixel, and If i want to scale it up, I will obtain every time a small one ...  because there are changed only decimals ...

@ChrisStratton i did the math myself. The map function is amazing and I think I will convert actual code to on that use map function. Thanks for suggestion!

Over a small area lat and long are just simple Y and X coordinates respectively.
Dynamic scaling of the points is a very simple matter.  All you need to do is work out the range of each dimension - so subtract the lowest latitude from the highest, and the lowest longitude from the highest.
That gives the full X and Y dimension of your area. Then just divide those by the dimensions of your screen.  That gives you a scaling factor for each direction.
For each point, subtract the lowest longitude and latitude, and divide by the scaling factor for each direction.
If you want to be more fancy and retain the aspect ratio then you just need to work out which of the two scaling factors will allow all the polygon to remain on the screen - that is, divide and offset all your points by one factor, then by the other, and pick the smallest factor where all the points are within the area of your screen.

I'm trying now to do your method, I think is what I want ...

I did the code for Arduino and it works really nice. I added an dynamic X offset to center it on the screen.
// lat = coordinatesForArea[i][0]
// lng = coordinatesForArea[i][1]
// cntr is the count of points

float newPoints[100][2];
float maxLat = 0;
float maxLng = 0;
float minLat = 180;
float minLng = 180;

for (int i = 0; i < cntr; i++) {
  maxLat = max(maxLat, coordinatesForArea[i][0]);
  maxLng = max(maxLng, coordinatesForArea[i][1]);
  minLat = min(minLat, coordinatesForArea[i][0]);
  minLng = min(minLng, coordinatesForArea[i][1]);
}

float ySize = maxLat - minLat;
float xSize = maxLng - minLng;

float scaleFactor = ySize / 300;

float maxY = 0;
float maxX = 0;

for (int i = 0; i < cntr; i++) {
  newPoints[i][1] = (coordinatesForArea[i][1] - minLng) / scaleFactor;
  newPoints[i][0] = (coordinatesForArea[i][0] - minLat) / scaleFactor;
  maxX = max(maxX, newPoints[i][0]);
  maxY = max(maxY, newPoints[i][1]);
}

float newScaleFactor = maxY > maxX ? maxY / 300 : maxX / 300;

float newMaxX = 0;

for (int i = 0; i < cntr; i++) {
  newPoints[i][1] = newPoints[i][1] / newScaleFactor;
  newPoints[i][0] = newPoints[i][0] / newScaleFactor;

  newMaxX = max(newMaxX, newPoints[i][0]);
}

float newOffsetX = (320 - newMaxX) / 2;
float newOffsetY = 100;

for (int i = 0; i < cntr; i++) {
  newPoints[i][1] = newPoints[i][1] + newOffsetY;
  newPoints[i][0] = newPoints[i][0] + newOffsetX;
}

for (int i = 0; i < cntr-1; i++) {
  myGLCD.drawLine(newPoints[i][0], newPoints[i][1], newPoints[i+1][0], newPoints[i+1][1]);
}

myGLCD.drawLine(newPoints[0][0], newPoints[0][1], newPoints[cntr-1][0], newPoints[cntr-1][1]);

Thank you Majenko


text:
BMP280 returns 0
I have connected a BMP280 temperature/pressure sensor to an Arduino Uno just like here:

and used the example code provided by the Adafruit BMP280 library. However, the values for temperature and pressure return 0.00 on the serial monitor. What might be the reason for this? I have set it up in I2C mode and deleted the lines responsible for the SPI connections.
    /***************************************************************************
  This is a library for the BMP280 humidity, temperature & pressure sensor

  Designed specifically to work with the Adafruit BMEP280 Breakout
  ----> http://www.adafruit.com/products/2651

  These sensors use I2C or SPI to communicate, 2 or 4 pins are required
  to interface.

  Adafruit invests time and resources providing this open source code,
  please support Adafruit andopen-source hardware by purchasing products
  from Adafruit!

  Written by Limor Fried & Kevin Townsend for Adafruit Industries.
  BSD license, all text above must be included in any redistribution
 ***************************************************************************/

#include <Wire.h>
#include <SPI.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BMP280.h>

#define BMP_SCK 13 // deleted the following 4
#define BMP_MISO 12
#define BMP_MOSI 11
#define BMP_CS 10

Adafruit_BMP280 bme; // I2C
// and the following 2 lines:
//Adafruit_BMP280 bme(BMP_CS); // hardware SPI
//Adafruit_BMP280 bme(BMP_CS, BMP_MOSI, BMP_MISO,  BMP_SCK);

void setup() {
  Serial.begin(9600);
  Serial.println(F("BMP280 test"));

  if (!bme.begin()) {
    Serial.println("Could not find a valid BMP280 sensor, check wiring!");
    while (1);
  }
}

void loop() {
    Serial.print("Temperature = ");
    Serial.print(bme.readTemperature());
    Serial.println(" *C");

    Serial.print("Pressure = ");
    Serial.print(bme.readPressure());
    Serial.println(" Pa");

    Serial.print("Approx altitude = ");
    Serial.print(bme.readAltitude(1013.25)); // this should be adjusted to your local forcase
    Serial.println(" m");

    Serial.println();
    delay(2000);
}

Yes, the manufacturer's data sheet says there is one integrated (120 Ohms)

Well, I followed this tutorial http://www.instructables.com/id/How-to-Use-the-Adafruit-BMP280-Sensor-Arduino-Tuto/step2/The-Circuit/. Where in the schematic would I place such a resistor?

Is your I2C address 0x76 or 0x77? Run the I2C scanner to find out: (http://playground.arduino.cc/Main/I2cScanner) I found that Adafruit_BMP280.h had 0x77 and changing it to 0x76 made it work. No pullups were needed.

I2C has to have pull up resistors on the data lines, otherwise it just doesn't work.
Have a quick search for the correct value but off the top of my head is 4.7k ish.
You have to place a resistor from the SDA and SCK lines to the +5V and suddenly it will jump into life. (Hopefully)

I suspect there are already pull-ups on the breakout; doesnt make any sense to not include them. Also if there were no pull-ups, begin() would have failed and there'd be a different error message

The recommended value is 10k, according to the documentation. When I connect one of them each between the data pin and V+, I still get an output of 0

Recently i bought a bmp280 which is not an adafruit one and connected it to esp32 and and tried to upload the code from the examples test but i got the error no valid bmp 280 found, i searched on google and found
https://www.circuitschools.com/interfacing-bmp280-with-esp-32-on-i2c-with-errors-and-solutions/
i read on i2c addresses errors,then from there i copied the code for an i2c scanner and ran it to get the correct i2c address  I checked on I2c address and replaced the i2c hex address in the BMP initiialization line.
then the sensor worked and gave me temp, pressure and approx altitude. Thanks

I had the same problem and I solved it by changing I2C address from 0x77 to 0x76, in Adafruit_BMP280.h

Good answer, and it would be better if you also had an explanation

well the reason for changing the I2C address from 0x77 to 0x76 is when you have your SD0 pulled down to ground.
If there is nothing attached to SD0 on the BMP280 the device address is 0x77 by default.


text:
'Keyboard' not found when trying to use Keyboard.write from the <Keyboard> library
I am trying to get a response from the arduino when I press a key, but when I try to upload the code it says that it could not find 'Keyboard' with 'Keyboard.write'. Here is my code. Ignore the bits with servo stuff, that is for the project later on. I am using the arduino mega 2560.
  #include <Servo.h>
  #include <Keyboard.h>

Servo myservo;
Servo myservo2;

int pos = 0;
int pos2 = 0;
String comdata = "";
int lastLength = 0;

void setup() {
myservo.attach(12);
myservo2.attach(11);
Serial.begin(9600);
pinMode(2, INPUT_PULLUP);
Keyboard.begin();
}

void loop() {
if (Serial.available() > 0) {
 // read incoming serial data:
 char inChar = Serial.read();
 Keyboard.write(inChar + 1);
}

}

I don't know if this problem has been solved, but I am having the same issue, however I am using one of the pure USB boards; the Due. I tried writing my own sketch and it failed to compile stating: > 'Keyboard' not found. Does your sketch include the line '#include

Keyboard.h'? Side note: I realise that the Keyboard.h is meant to be enclosed by the greater than and less than signs, but for some reason this fails to show in the post. These signs were in the IDE error. I then thought I'd try one of the standard examples to compare it to, and this also failed with the same error. I have i

The Mega2560 can't be a keyboard. It lacks the required hardware.
Instead you need to use one of the pure USB boards, like the Leonardo.

To use USB communication (such as mouse or keyboard) you must have a arduino that uses an ATMEGA32U4. These are so far, the only boards that can work as a USB device.


text:
When should you worry about interference affecting the analog input?
I made something that uploads the measured current to Thingspeak. Everything works, but i did not place the DC to DC converter on the board because i was worried that it would interfere with the analog input. Also the ESP8266 is very close to the Arduino Pro Mini. Could it affect the reading?
Could i have put the DC to DC converter on the board without any problem?

230VAC to 12VDC adapter(not on the picture) --> 12VDC to 3,3VDC(on the picture)-->the prototype board
Sensor: SCT-013-030 30A = 1V

There is not enough information for making  hardware improvement suggestions.  For starters what are you using as a sensor?  What type of impedance does it have? Is it generating current, voltage or does its resistance vary? However, my first thought is to shorten what appears to be an excessively long cable between the ADC input and the sensor. And if you are really worried about power noise, try a test where you run everything off of batteries.

Sensor: SCT-013-030 30A = 1V

Ah, that's what that blue thing is!  The internal resistance is low.  About 62 ohms according to the specifications.  In general, the lower the internal resistance the less influence electrical noise will make.   We can say it is less likely for the switcher to interfere with the ADC should you decide to mount it on the board.  I am a bit more concerned about the switcher coupling with the radio.  To be safe, I would keep them on opposite sides of the board and point the radio's antenna away from the switcher.

You are more likely to have noise injected on the power pins of the Arduino that by EMI or capacitative coupling. With the switcher on board of off board it will make no difference if the voltage it supplies to the Arduino (and hence to the ADC) is noisy and full of spikes.

Noise reduction involving Analog to Digital Conversions can be done in many ways.  Common software solutions involve averaging multiple conversions.  Exponential smoothing is one such method.  One advantage of exponential smoothing is that it can be applied to an endless stream of conversions.

I don't want to smooth it, i just want to know if the DC to DC converter or the ESP8266 could affect the analog reading?
Also the analog input is an AC signal, i guess you can't smooth that.

Actually ADC are noisy enough that, say, an 8 bit ADC only gives you a few bits of significant accuracy w/o taking multiple samples into consideration.  The DC to DC is probably operating at a high frequency.  So, guessing because I don't know much about your sensor, you might be able to mitigate any effect by adding a low pass filter to the ADC input.  In the end, designing with switchers is notoriously problematic.  I have seen hardware designers spinning boards because of switcher problems.  Others may have more experience, but this may come down to trying & testing.


text:
Are there fixed connectors for gpio?
Curently I am using these connectors for my prototype:
Ebay link
However, I need something more reliable so I can deliver the prototype to a user without to risk that the cables fall out of their pins.
Is there something else to use? I would like to avoid soldering.. :(

Unless you want to replace the headers with something else, which means soldering, then you will be soldering.
The options are:

Solder different connectors in the place of the existing headers
Remove the existing headers and solder wires directly in their place
Get a prototyping shield and solder wires in to that
Get a prototyping shield and solder different connectors to it.

Whatever you choose you will be soldering.
Don't be scared of soldering - it's the most basic thing you need to be able to do when you are working with electronics.

The cables you link are supposed to be assembled by crimping rather the soldering.  The risk of them falling out is mostly because the housing are only for a single contact.
If you instead get multi-contact housings the width of the headers you are matching, and insert contacts into those in the desired positions, the risk of things falling out will be greatly reduced.  You can add a label to indicate correct insertion direction.
Of course, a much better result would be to make either a custom shield with terminations for the signals you need to route elsewhere, or to replace the Arduino itself with a custom ATmega board that handles application-appropriate polarity-keyed wiring harnesses.


text:
Is it possible to start audio playback when headphones gets plugged in?
I want to have 6 audio jacks IN waiting for connection to start some WAV/OGG playback as soon as a headphone plugs in. In fact, I'd like to have simultaneous playback in 6 lines.
I've seen in the market some stuff that you can add buttons to different actions (play, pause, stop, etc). So far I believe this might be possible and affordable with Adafruit's Audio FX (which are stand-alone, Arduino-programmable WAV/OGG decoder circuits).
But,

Is it possible to start audio playback when headphones gets plugged
  in? HOW?

Is that an event? like pressing a button?
Does it need some "hacking" between GND lines maybe?

You can detect when a headphone is plugged in because the connector closes a switch within the body of the audio jack when its fully plugged in (assuming you're using a 3.5mm jack). If you have a function for starting playback, you can call it as soon as the MCU detects the switch has been closed.

@TisteAndii - You should turn your comment into an answer... I'd give it an upvote :-)

@Greenonline thanks...was waiting for some feedback from the OP to know if its what they want

@TisteAndii - I would think that it is the best [only?] and most obvious way to go... it was the first thing that came to my mind, when I saw the question.

A lot of 3.5mm jacks come with built-in normally-closed contacts, and their state can be tested through the pins of the jack with a multimeter or sensed by your MCU like any other switch. There are usually 2 pins each for the ring (pins 2 and 4 below) and the tip (pins 3 and 5), each pair connected to the other and one pin for the sleeve. The insertion of the headphones' connector breaks the connection between each pair, so that only one pin of each pair is actually connected to the connector's tip and ring.

You can connect the tip (pin 3) of each jack to digital input pins and connect the other pin of the pair (pin 5) to Vcc; you only need to read the tip because if the tip contacts are closed, it means nothing is fully plugged in yet. When no connector is plugged in, input pin reads HIGH from the tip since it is connected to Vcc through pin 5. When the headphones are plugged in, it breaks the 3-5 connection, and the tip now floats. Its voltage is indeterminate; it will probably sit somewhere near the middle of the 0-5V range, but we can't be sure.
To remedy this, there are 2 possible approaches I can see:

You use an analog input pin, instead of a digital pin. This way, you can read the very voltage at the tip; if its ADC value is above 900 perhaps, you can conclude that its HIGH and therefore nothing is plugged in, whereas if its below 600, you can conclude that the tip is floating and a headphone is plugged in. However, this method will require an input pin per headphone. The Uno has 6 analog pins, so this will take up all of them. If you aren't already using any of them, this method may be good enough. You could also use an analog GPIO expander.
You can use a digital input pin for the tip (pin 3) but instead of pulling pin 5 to Vcc, you connect it to a digital output pin. You can connect the pin 5 of each headphone set to this common output pin. To test if a particular jack has headphones plugged into it, you read the associated input pin and check if this is the same as the current value of the common output pin (saved to some variable). If it is, you toggle the output pin and again check the input pin to see if it mirrors the new value of the output pin; just additional confirmation. If everything checks out, then nothing is connected to the jack yet. If either test fails, you can reasonably conclude that headphones are plugged in.

Now that you know headphones are plugged in, you can call the appropriate function to begin playback through the right jack. Of course, all this assumes you'll be working with the jacks directly and not through some module. If you use the Adafruit Soundboard, you can check out the L (Left Channel) pin, which corresponds to the tip. I don't know if it's actually connected to the jack so you'll have to experiment and find out.


text:
Arduino/ESP8266 no SPI data coming from MCP3008
I'm using an ESP8266 (NodeMCU Dev Kit v1) to read analog data via an MCP3008 ADC chip.
However I'm receiving only zeros when I know non-zero data should be present. I'm using the following code, which works perfectly when using the MCP3008 with my Arduino UNO. Using verbose mode on compilation, I can confirm that when compiling for the ESP8266, that is indeed linking the ESP8266 SPI library.
Am I missing something here in the code?
#include <SPI.h>

#define CS_PIN 15 // Use 10 when compiling for Arduino

int adcRead(int channel) {
  if ((channel > 7) || (channel < 0)) {
    return -1;
  }

  digitalWrite(CS_PIN, LOW);

  SPI.transfer(1);
  uint8_t r1 = SPI.transfer((channel + 8) << 4);
  uint8_t r2 = SPI.transfer(0);

  digitalWrite(CS_PIN, HIGH);

  return ((r1 & 3) << 8) + r2;
}

void setup() {
  SPI.begin();
  SPI.setBitOrder(MSBFIRST);
  SPI.setDataMode(SPI_MODE0);
  SPI.setFrequency(1000000); // 1 MHz -- remove line when running on Arduino UNO
  Serial.begin(9600);
  digitalWrite(CS_PIN, HIGH);
}

void loop() {
  Serial.println(adcRead(0));
  delay(50);
}

In terms of wiring, I have the following
MCP3008   ESP8266
V_DD      3v3
V_REF     3v3
AGND      GND
CLK       GPIO14 (D5)
D_OUT     GPIO12 (D6)
D_IN      GPIO13 (D7)
CS        GPIO15 (D8)
DGND      GND

I dont see any pinMode(CS_PIN, OUTPUT);

That fixed it! Guess I managed to overlook that.

I was having trouble with this code and setup with the Adafruit Feather HUZZAH ESP8266.
Solution
In addition to adding the pinMode(CS_PIN, OUTPUT); to setup(), I also dropped the frequency to something much lower. In my case, dropping the frequency to 10000 gave me good readings.


text:
Find number in a reply returned via serial
I am communicating with my GoPro via ESP8266 and GET requests.
One of the replies returns a set of predefined number and what I would like to do is extract the number on position "38". This is what the reply looks like in full:
SEND OK

+IPD,4,163:HTTP/1.1 200 OK
Transfer-Encoding: chunked
Date: Sun, 24 Apr 2016 03:13:40 GMT
Server: Cherokee/1.2.101b150714_bd80061 (UNIX)
Content-type: application/json

OK

+IPD,4,972:3c0
{"status":{
"1":1,"2":1,"3":0,"4":0,"6":0,"8":0,"9":0,"10":0,"11":0,"13":0,"14":0,"15":0,"16":0,"17":1,"19":0,"20":0,"21":0,"22":0,"23":0,"24":0,"26":0,"27":0,"28":18,"29":"","30":"xxx","31":0,"32":0,"33":0,"34":7933,"35":5039,"36":0,"37":4,"38":0,"39":4,"40":"%10%04%18%03%0D%28","41":0,"42":0,"43":1,"44":0,"45":0,"46":0,"47":0,"48":0,"49":0,"54":29698976,"55":1,"56":4,"57":1022279,"58":0,"59":0,"60":500,"61":2,"62":0,"63":0,"64":0},
"settings":{"1":0,"2":9,"3":6,"4":1,"5":2,"6":1,"7":1,"8":0,"9":0,"10":0,"11":1,"12":1,"13":1,"14":0,"15":4,"16":0,"17":2,"18":2,"19":2,"20":0,"21":1,"22":2,"23":0,"24":2,"25":0,"26":4,"27":0,"28":2,"29":1,"30":10,"31":0,"32":0,"33":0,"34":1,"35":2,"36":1,"37":2,"38":0,"39":4,"40":0,"41":13,"42":8,"43":0,"44":8,"45":8,"46":0,"47":0,"48":0,"49":0,"50":1,"51":1,"52":0,"53":0,"54":0,"55":1,"56":1,"57":1,"58":1,"59":0,"60":8,"61":1,"62":700000,"63":4,"64":1,"65":0,"66":0,"67":0,"68":0,"69":0,"70":0,"71":0,"72":1}}

0

OK

As you can see, position 38=0 (...,"38":0,...). The number 0 will increment. So I would like to find the string "38": and do something with following numbers until ,.
What is the correct way to grab that number from the serial reply and echo or do something with it?

Are you using an Arduino to see the serial reply ? Or are you directly connected to the ESP8266 via USB?

USB <-> Teensy <-> ESP ~~~~ GoPro

Since you are being returned JSON, you can use the jsoncpp library found here
To split your return to an array. Then you simply retrieve whatever item you want using array index notation.
Here is another helpful post on creating arrays of strings in C++ from JSON.
C++ and JSON

I ended up using https://github.com/bblanchon/ArduinoJson and Serial.find();


text:
Reading two sensors at different frequencies... multiple Timer3?
Originally, I had a single sensor which I was reading at 100MHz. I used Timer3 and function attached to it to do both reading and writing of the sensor data (print to com port).
Now I have added another sensor which can only be read at half the frequency. I still want to be able to write data in the same format as before for both sensor data at 100Hz, with slower sensor data just being repeated twice.
How do I handle this? Do I use multiple Timer3 attachments at different frequencies? I am planning to have three interrupts.. 1st for reading sensor A, 2nd for reading sensor B, and 3rd for writing data.

which Arduino you are using?

I am actually using Teensy 3.1

The rule is:

One Timer, One Interrupt.

When the timer overflows it triggers its interrupt. It only has one. That interrupt then runs your ISR.
If you are using a library to provide abstraction from the timer registers then it is down to that library how it calls your ISR. It is possible for one to provide a mechanism whereby you can "attach" multiple routines to the same interrupt, but that is quite a lot of work and overhead for a simple timer library to provide, so it is highly unlikely anyone would ever bother.
So how do you do multiple sensor measurements from one timer? Simple: just do multiple sensor measurements. You don't have to restrict yourself to just reading one sensor within your interrupt - you can read as many as you like. There is just a couple of caveats though:

The whole ISR must take less that 10ms to run or it will overrun the timer overflow period.
You cannot do serial from inside an interrupt*

So in your interrupt you read the sensors and add their values to a buffer. Then in your main loop you read that buffer to send the data out through serial. You may want to set a flag in your interrupt routine to alert the main loop that there is data available, or implement a circular buffer which has an equivalent of a .available() function to see if there is any data to read from it.

*You can place data in the serial TX buffer but it will not be transmitted out of the TX buffer until after the interrupt routine has finished. If you put too much data in that TX buffer it will block indefinitely waiting for it to empty.

Conceptually, this is best solved by having an ISR which always reads the high rate sensor, but implements a toggle so that it only ready the low rate sensor every other execution.  On the times when you don't read it you could repeat a stored version of the last reading, though it would be more bandwidth efficient not to transmit that at all.
However, practically speaking this may not be the best choice.  The process of reading sensors often has a latency - typically to achieve the highest possible rate you would need to start the reading, and claim the result sometime later.  If your two sensors have distinct interfaces, or even if the they share an I2C or SPI bus, you may be able to start readings for both and then claim them with subsequent transactions after allowing them an overlapped measurement time.
It is also not clear that you are best to use an interrupt service routine at all.  If your MCU has nothing else to do, the most deterministic and ultimately fastest behavior on an ATmega might be to accomplish reading and direct (unbuffered) serial transmission within the main program loop, busy waiting at each phase.  This avoids not only the overhead of context switches when entering an ISR, but also a lot of the variability.  That would be doubly true if you can be transmitting the old reading while waiting for the already-triggered sensors to measure the next one.
However, you mentioned you are using a Teensy 3.x, which probably communicates natively via USB, rather than a serial UART.  That complicates things a bit - so called "serial" output flows in response to interrupts from the USB engine responding to the host, which is not really deterministic for you.  Fortunately, the Teensy is enough faster that you are less likely to have issues with running out of time, particularly when sampling at 100 Hz.


text:
Digital input pin voltage treshold (voltage to register 1 or 0)
I was thinking of using multiple analog light sensors (variable resistance by light), but basically I only need to know if there is "a lot of light" or "not a lot of light". And would like to use interrupts.
Since I'm using multiple analog inputs, I can't set the ADC module to interrupt on a specific voltage, for each of the (5?) sensors?
I'd like to do this withouth using a external comparator.
I've checked the ATMega328p datasheet (going to use Arduino Nano probably).

The fun thing, however, is that on 5V a high signal is >2.6V and a low signal is <2.2V
What does this mean for the grey area? Would my inputs be glitching randomly? Would they maintain high, until below 2.2V and maintain low until above 2.6V? Or can the switching point be any where between that (and is it different per chip or pin?
EDIT: I've checked, my voltage divider circuit has 0.6V for "nothing" and 3V for "interrupted", so it should work neverthless. Though, I'm still interested in how the grey threshold area behaves.

Consider adding a differential amplifier like LM741 or LM341 with the sensor input connected to the non-inverting terminal and the inverting input connected to a potentiometer. This is always the best arrangement that I have found that works..when it comes to light sensors. You may adjust the potentiometer to such that the op-amp produces the desired output at the desired conditions. This has also the advantage that you easily adjust the threshold if the lighting conditions change by changing the potentiometer than changing the code.

The titles of the graphs are actually saying what happens: the hysteresis.
In other words:

if the input level is high (greater than 2.6V), it will be considered high through the hysteresis area (until it goes below 2.2V)
if the input level is low (below 2.2V), it will be considered low through the hysteresis area (until it goes above 2.6V)

According to the description you gave, this should work for your case.
In case it doesn't, you have to condition it until the values you want to consider 0 and 1 are respectively below 2.2V and above 2.6V, with a safety margin, for good measure (say 30%).
The hysteresis is meant to prevent noise from causing unwanted spurious transitions: without safety margin, it should be greater than 0.4V.
You can dimension the safety margin to meet your needs.
But, for the sake of completeness, I'll say that it might be preferable to have a timer to trigger periodic sampling with the ADC.
If you know the maximum frequency at which every input can vary, you can sample it at twice that frequency and be sure that you will not miss anything. Again, this is theory, I would probably make it 4 times, to allow for unforeseen variations.
This works as long as the conversion time of the ADC is shorter than the maximum combined frequency at which you need to read the values.
The GPIOs, of course, are faster, but might require additional circuitry for the conditioning I mentioned earlier.

Good, I was worried the input might go random when it's on 2.4V. But you're saying the 2.4V will leave it in the current state, only if it goes higher as 2.6V or lower as 2.2V it will cause a "transition". So one could say that the grey area is "stable".

After setting my voltage divider right, I've got a 0.6V for low and 3V for high. I might shift it a little higher, but that would indeed work, withouth having to worry about the "grey area", but it's good to know what the values in the datasheet mean.

It is designed exactly for that purpose, to increase the resilience of the circuit to noise and variation in components (think of the tolerances in the industrial manufacturing processes) and environments where they operate.

The challenge modern electronics face is that the physical world is not really changing, while the circuits are becoming low power (lower max voltage). So the 0 and 1 thresholds are getting closer: just compare an "old school" 5V circuit with Arduino, with a modern SoC that has Vdd=1.8V. The entire range of the modern circuit is smaller than the range allowed for logic 0 on the Arduino!

I was wondering about that also, my project was a proof of concept for a "planter monitor" which could measure maize seeds dropping. If I would ever put it on a real planter, I'd better have some noise immunity. I believe PLC's run at 24V for that reason. The advantage of low voltage would ve lower power? 1.8V is okay on a PCB, but I wouldn't run long wires with it (:

This is now digressing, but on long lines you do not usually put normal signal, you want to have something that has better S/N ratio. Example: differential signals used in old telephone lines. For modern, more complex cases, one uses complex modulations (that's what a DSL modem does, for example.)  As reference, check out this: https://en.wikipedia.org/wiki/Phase-shift_keying

In your case, you would probably use a level shifter against the bus/sensor used to dete the parameter you need. Ex: http://i.stack.imgur.com/DGm1u.png


text:
PWM on non PWM pins
Why does this code not function in a similar way to the example fade sketch?
I have had to resort to using bit-banging as a way to implement PWM onto non PWM pins due to  a lack of available free pins on my Arduino Pro Mini. I am using a sketch that supposedly should fade an LED ranging from maximum brightness to minimum brightness. My code however does not work. Can anyone figure out why my code does not operate in the same way the fade sketch does?
My current code is:
int brightness = 0;
int fadeAmount = 50;
void setup()
{
  pinMode(12, OUTPUT);
}
void loop()
{
  brightness = brightness + fadeAmount;
  if (brightness == 0 || brightness == 255) {
    fadeAmount = -fadeAmount ;
  }
  digitalWrite(13, HIGH);
  delayMicroseconds(brightness); // Approximately 10% duty cycle @ 1KHz
  digitalWrite(13, LOW);
  delayMicroseconds(1000 - 100);
}

And I want it to work in the same way as:
int led = 9;
int brightness = 0;
int fadeAmount = 5;
void setup() {
  pinMode(led, OUTPUT);
}
void loop() {
  analogWrite(led, brightness);
  brightness = brightness + fadeAmount;
  if (brightness == 0 || brightness == 255) {
    fadeAmount = -fadeAmount ;
  }
  delay(30);
}

If possible could anyone provide a correct version to help me with my project.

You seem to have a typo on the pin number: you are configuring pin 12 and driving pin 13.
In other words: pinMode(12, OUTPUT); and digitalWrite(13, HIGH); do not match.

Your code here is not quite right:
digitalWrite(13, HIGH);
delayMicroseconds(brightness);
digitalWrite(13, LOW);
delayMicroseconds(1000 - 100);

Your two delays should add up to the total period (wavelength), or the reciprocal of the frequency (scaled to microseconds).
Hence the - 100 in the second delay - that is subtracting the "on" time from the total time to give the "off" time.   It should be replaced with - brightness as such:
digitalWrite(13, HIGH);
delayMicroseconds(brightness);
digitalWrite(13, LOW);
delayMicroseconds(1000 - brightness);

And of course the brightness is in the range 0 - 1000 not 0 - 255 like analogWrite().  To make it 0-255 you should replace the 1000 with 255, which of course makes it all run at a much higher frequency. (1 / 0.000255 = 3922Hz).
digitalWrite(13, HIGH);
delayMicroseconds(brightness);
digitalWrite(13, LOW);
delayMicroseconds(255 - brightness);

Mind you, all this is not good regardless of your calculations. This is a blocking system in which you are unable to do anything else at all in your program whilst generating PWM.  Instead you should be using a timer (like the tone() command does) and switch between two different time periods each interrupt for "on" and "off" time periods. That way it can function asynchronously ("in the background") like analogWrite() does.

It's not strongly related to your question but i suggest you to use external library as SoftPWM.h
You can find the whole documentation on https://github.com/bhagman/SoftPWM

A more generic version of your approach would be like this.

Set the output pin - don't hardwire the pin number but instead use a macro for it.
Delay for it's duty cycles.
Clear the output pin.
Delay for period - duty cycles used in step 2 above.

You can put that in a routine and call it.
With that said the routine has limited use in a real application as it can drive one output pin and ties up the whole mcu needlessly.
A better approach is to use an interrupt and test for duty cycles in the interrupt . This can drive multiple pins with independent duty cycles. All without tying up the mcu.

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


text:
Is it possible to use AWS and Arduino Uno to upload data from Arduino to a website running on my localhost?
I was wondering if it's possible to send data from my Arduino Uno (e.g. from the temperature sensor) to the Amazon Web Service RDS or anything there, which will then upload the data to a website on my localhost?
If yes, could someone give me guidance please?
I've been messing with this for a few weeks now, but I am just getting lost with linking it all up together.
Thanks.

First of all you must post your code how you are progressing, like @Majenko said it is not easily possible but it can work.  I will guide you along the way

You'll probably only need one server, and let the Arduino's upload to that directly?

No... by definition the only thing that can upload anything to "localhost" is that host itself, because "localhost" always refers to oneself.  It may well be possible to contact this from some other device, but never by referring to it as "localhost"!

If the goal is to get the data from the arduino to your local machine? Is the arduino on the same local network as the your local machine? if so, skip AWS altogether and just have the arduino talk directly to your local machine...

No, it is not (easily) possible.
AWS has no access to your localhost - you are (most likely) behind a NAT router.
You could possibly open up port forwarding on your router and then ensure that AWS knows always what the IP address of your router is so it can connect (using some dynamic DNS service maybe).
However, that is not secure, and dynamic IP address assignments makes it a real pain. It opens up your computer to hacking from the internet.  A more secure method is to use AWS as the "central point" and have your computer go and fetch data from there rather than having it send data to your computer.

What would you suggest would be a good idea doing what I want to achieve? Thanks

@deeveeABC The last sentence of the last paragraph.

You can always setup a dynamic dns (as I do), with no-ip or dyndns clients (most routers allow you to configure that), and use the port forwarding thing. You can even configure a afraid.org dns redirection (pretty easy), but you have to note that you won't be capable of fetching / posting via https, so it's very likely it's not gonna work or be very prone to attacks.

I realize that this probably two years too late for the OP; however, I'd like to provide insight to anyone else who might be interested.
It is possible to do what you're asking. What you are looking for my friend is AWS IoT Core and the related IoT Services (e.g. IoT Device Management).
There are several steps that you're going to need to perform prior to being able to send telemetry to AWS:

Ensure that your device has the necessary components to connect to the Internet (e.g. a network shield).
Once you are Internet-capable, locate here the AWS IoT SDK that will work well with your device.
Read the documentation (I'll let you look that part up ;-)...probably within the sub-links on the page from #2) on how to connect your device to an MQTT-based Web Sockets connection to AWS IoT Core.
Once you've figured out how (using the SDK from your device) to connect to AWS using MQTT, read about AWS Lambda and how you can setup various triggers off of IoT Core, which can then propagate data down to your RDS DB or the like.
Once you have your data in AWS, you can then connect your "localhost" website to RDS, using the appropriate connection string, and pull the data from there.

Good luck and happy IoTing.


text:
RGB Led strip pot control burned my arduino?
I made this exact build on my Arduino, with the following differences:

I'm using Arduino Nano
Transistors I use are 2N2222A
I'm running everything on 12V except Arduino, I use LM317 to feed Arduino 6v

Here's the build:

Here's what happened. First, it started to get strange voltage, arduino would light up even when disconnected from power. After that, Arduino kind of got fried, when I connect it to USB, nothing happens. I can give it 6v to VIN and ground it with the rest, but turning potentiometers only dims the onboard LED of the Arduino and that's it.
Now I'm going to go and pick up a new nano, however, I'd prefer not to fry that one, so figuring out why this one burned would be nice.
PS. The image shows RGB LED instead of RGB LED Strip because 123d doesn't have strip component.

No base resistors?

Nothing according to the original build, should there be any?

Yes, otherwise the transistors can draw too much current for the Arduino to handle.

Would you suggest anything specific? Arduino should be able to throw 20mA on those outputs, transistors are running on 12v, while Arduino is on 6

That depends on how much current your LED strip needs per channel.

Any ideas how to figure it out? There are zero marks on the strip itself. No make and model, no specs

How many LEDs on your strip?

Theres 12 leds total, 3 per segment

220Ω should be fine

So i did try the resistor and arduino keeps burning up. One thing i noticed: if i wire pots directly to + arduino gets really hot really fast. If i wire them to arduino 5v pin, it gets hot slower, but still does. Im confused

Then you must have something seriously messed up with your wiring.

Power everything from the same source. Keep grounds common. Check your wiring. Fritizing is a poor way to show your connections.

First, as Majenko said, you need resistors between the arduino output pins and the transistor bases. Start at something like 330 Ohm.
Second, what is the value of the potentiometers? If it is too low you would be drawing too much current from the 5V pin to the ground.
Third, you should power the arduino with at least 7V, assuming you power it through the Vin pin or the power jack. 6V is considered too low.
I assume the pins connected to the potentiometers are initialised as inputs. Otherwise, it would be possible to burn your arduino by having them source/sink too much current (i.e. by turning the potentiometers to one end or the other).

I just figured 6v safe, but I'll increase it to 7. I did start with 330 and went all the way up to 1k resistors without results. The pots are 4.7k trimmers, original design said 10k, but I had none at hand. They are hooked to A5 and A6 which are initialised as inputs yes

Although 6V is generally considered too low (you are applying it to pin Vin or the power jack, right?) this would not explain the arduino burning, so pls don't try with another arduino unless you find a plausible explanation for this. It may seem a silly question, but have you double- and triple-checked all your connections?

The trimmers are fine. At 5V they will draw around 1 mA each, which is really unimportant toward the 200mA limit.

Yeah vin is connected to 6v and gnd to power supplu ground. I did, only thing left is to recheck the wires for broken ones (i had one that beep on continuity test but didnt work) and breadboard itself i see nothing else that can be an issue, since my circuit is correct

Looking at the datasheet for the 2N2222A at http://www.onsemi.com/pub_link/Collateral/2N2222A-D.PDF
The 2N2222A base will draw 50 ma at 2volt.  You are giving them more than that.
The maximum allowed output from the Arduino is 40ma.
So check the 2N2222A's they are probably burnt out as well as the Arduino.
Next time put in a limit resistor of 1k to the 2N2222A bases.
Try pulling out the 2N2222A's and see if your Arduino powers up ok.