body:
I'm using arduino uno with cc3000 shield and I'm trying to get some sort of data from my server but I only get some of it and the remaining part is delivered after so long, when I send the request I get this:

    HTTP/1.1 200 OK.
    Date: Sun, 14 Feb 2016 14:00:46 GMT.
    Server: Apache.
    Last-Modified: Sun, 14 Feb 2016 11:58:31 GMT.
    Accept-Ranges: bytes.
    Content-Length: 16.
    Keep-Alive: timeout=2, max=100.
    Connection: Keep-Alive.
    Content-Type: application/json.

and the full data should look like this:

    HTTP/1.1 200 OK.
    Date: Sun, 14 Feb 2016 13:59:26 GMT.
    Server: Apache.
    Last-Modified: Sun, 14 Feb 2016 11:58:31 GMT.
    Accept-Ranges: bytes.
    Content-Length: 16.
    Keep-Alive: timeout=2, max=100.
    Connection: Keep-Alive.
    Content-Type: application/json.
    {"light": "off"}

the `{"light": "off"}` part takes too long to get parsed to my code.

I'm using this code:

    #include <SPI.h>
    #include <SFE_CC3000.h>
    #include <SFE_CC3000_Client.h>
    #include <ArduinoJson.h>

    // Pins
    #define CC3000_INT      3   // Needs to be an interrupt pin (D2/D3)
    #define CC3000_EN       5   // Can be any digital pin
    #define CC3000_CS       10  // Preferred is pin 10 on Uno

    // Connection info data lengths
    #define IP_ADDR_LEN     4   // Length of IP address in bytes

    // Constants
    char ap_ssid[] = "xxxxx";                  // SSID of network
    char ap_password[] = {0xXX, 0xXX, 0xXX, 0xXX, 0xXX, 0xXX};          // Password of network
    unsigned int ap_security = WLAN_SEC_WEP; // Security of network
    unsigned int timeout = 30000;             // Milliseconds

    #define SERVER "XXXXX"
    #define DIRECTORY      "/esp8266pir/light.json"

    const int pin        = 2;
    #define IDLE_TIMEOUT_MS  5000

    // Global Variables
    SFE_CC3000 wifi = SFE_CC3000(CC3000_INT, CC3000_EN, CC3000_CS);
    SFE_CC3000_Client client = SFE_CC3000_Client(wifi);

    void setup() {

      pinMode(pin, OUTPUT);
      pinMode(pin, HIGH);

      ConnectionInfo connection_info;
      int i;

      // Initialize Serial port
      Serial.begin(115200);
      Serial.println();
      Serial.println("---------------------------");
      Serial.println("SparkFun CC3000 - WebClient");
      Serial.println("---------------------------");

      // Initialize CC3000 (configure SPI communications)
      if ( wifi.init() ) {
        Serial.println("CC3000 initialization complete");
      } else {
        Serial.println("Something went wrong during CC3000 init!");
      }

      // Connect using DHCP
      Serial.print("Connecting to SSID: ");
      Serial.println(ap_ssid);
      if(!wifi.connect(ap_ssid, ap_security, ap_password, timeout)) {
        Serial.println("Error: Could not connect to AP");
      }

      // Gather connection details and print IP address
      if ( !wifi.getConnectionInfo(connection_info) ) {
        Serial.println("Error: Could not obtain connection details");
      } else {
        Serial.print("IP Address: ");
        for (i = 0; i < IP_ADDR_LEN; i++) {
          Serial.print(connection_info.ip_address[i]);
          if ( i < IP_ADDR_LEN - 1 ) {
            Serial.print(".");
          }
        }
        Serial.println();
      }
    }

    void loop() {
      send_request();
    }

    void send_request () {

      client.connect(SERVER, 80);
      if (client.connected())
      {
        client.print(F("GET "));
        client.print(DIRECTORY);
        client.print(F(" HTTP/1.1\r\n"));
        client.print(F("Host: ")); client.print(SERVER); client.print(F("\r\n"));
        client.print(F("Connection: keep-alive\r\n\r\n"));
        client.println();
      }
      else
      {
        Serial.print(F("failed to connect"));
        return;
      }
      // read response
      String section="header";
      unsigned long lastRead = millis();
      while (client.connected()&& (millis() - lastRead < IDLE_TIMEOUT_MS)) {
        while (client.available()) {
        String line = client.readStringUntil('\r');
        Serial.print(line);
        // we’ll parse the HTML body here
        if (section=="header") { // headers..
          Serial.print(".");
          if (line=="\n") { // skips the empty space at the beginning
            section="json";
          }
        }
        else if (section=="json") {  // print the good stuff
          section="ignore";
          String result = line.substring(1);

          // Parse JSON
          int size = result.length() + 1;
          char json[size];
          result.toCharArray(json, size);
          StaticJsonBuffer<200> jsonBuffer;
          JsonObject& json_parsed = jsonBuffer.parseObject(json);
          if (!json_parsed.success())
          {
            Serial.println("parseObject() failed");
            return;
          }

          // Make the decision to turn off or on the LED
          if (strcmp(json_parsed["light"], "on") == 0) {
            digitalWrite(pin, HIGH);
            Serial.println("LED ON");
          }
          else {
            digitalWrite(pin, LOW);
            Serial.println("led off");
          }
        }
      lastRead = millis();
      }
      }
    }

and here is my `light.json` code:

    <?php
    $light = $_GET['light'];
    if($light == "on") {
      $file = fopen("light.json", "w") or die("can't open file");
      fwrite($file, '{"light": "on"}');
      fclose($file);
    }
    else if ($light == "off") {
      $file = fopen("light.json", "w") or die("can't open file");
      fwrite($file, '{"light": "off"}');
      fclose($file);
    }
    ?>

    Turn On
    Turn Off

      <?php
        if($light=="on") {
          echo("Turn LED on.");
        }
        else if ($light=="off") {
          echo("Turn LED off.");
        }
        else {
          echo ("Do something.");
        }
      ?>

thanks in advance.

**Edit**

memory statistics:

    Global variables use 1,187 bytes (57%) of dynamic memory, leaving 861 bytes for local variables. Maximum is 2,048 bytes.

**Edit**

I did some enhancement to my arduino code and used adafruit library but still the server response takes too long to get it (up to 10 seconds).

this is my new code:

    /***************************************************
      This is an example for the Adafruit CC3000 Wifi Breakout & Shield

      Designed specifically to work with the Adafruit WiFi products:
      ----> https://www.adafruit.com/products/1469

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

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

    /*

    This example does a test of the SNTP (Simple Network Time Protocol) client:
    * Initialization
    * SSID Scan
    * AP connection
    * DHCP printout
    * SNTP time synchronization
    * Extract and print current time and date information

    */

    #include <Adafruit_CC3000.h>
    #include <ccspi.h>
    #include <SPI.h>
    //#include "utility/NetTime.h"
    #include <string.h>
    #include "utility/debug.h"

    #include <ArduinoJson.h>
    #include <TextFinder.h>

    // These are the interrupt and control pins
    #define ADAFRUIT_CC3000_IRQ   3  // MUST be an interrupt pin!
    // These can be any two pins
    #define ADAFRUIT_CC3000_VBAT  5
    #define ADAFRUIT_CC3000_CS    10
    // Use hardware SPI for the remaining pins
    // On an UNO, SCK = 13, MISO = 12, and MOSI = 11
    Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS, ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT,
                                             SPI_CLOCK_DIV2); // you can change this clock speed but DI
    Adafruit_CC3000_Client client;
    TextFinder finder(client);

    #define WLAN_SSID       "XXXXX"   // cannot be longer than 32 characters!
    const char WLAN_PASS[] = {0xXX, 0xXX, 0xXX, 0xXX, 0xXX, 0x00};
    // Security can be WLAN_SEC_UNSEC, WLAN_SEC_WEP, WLAN_SEC_WPA or WLAN_SEC_WPA2
    #define WLAN_SECURITY   WLAN_SEC_WEP

    #define SERVER "XXXXX"
    String DIRECTORY   =   "XXXXX";

    uint32_t ip;

    const int pin        = 2;

    /**************************************************************************/
    /*!
        @brief  Sets up the HW and the CC3000 module (called automatically
                on startup)
    */
    /**************************************************************************/
    void setup()
    {
      pinMode(pin, OUTPUT);
      pinMode(pin, HIGH);
      Serial.begin(115200);
      Serial.println(F("Hello, CC3000!\n"));

      Serial.print("Free RAM: "); Serial.println(getFreeRam(), DEC);

      /* Initialise the module */
      Serial.println(F("\nInitialising the CC3000 ..."));
      if (!cc3000.begin())
      {
        Serial.println(F("Unable to initialise the CC3000! Check your wiring?"));
        while(1);
      }

      /* Optional: Update the Mac Address to a known value */
    /*
      uint8_t macAddress[6] = { 0x08, 0x00, 0x28, 0x01, 0x79, 0xB7 };
       if (!cc3000.setMacAddress(macAddress))
       {
         Serial.println(F("Failed trying to update the MAC address"));
         while(1);
       }
    */

      uint16_t firmware = checkFirmwareVersion();
      if (firmware < 0x113) {
        Serial.println(F("Wrong firmware version!"));
        for(;;);
      }

      /* Delete any old connection data on the module */
      Serial.println(F("\nDeleting old connection profiles"));
      if (!cc3000.deleteProfiles()) {
        Serial.println(F("Failed!"));
        while(1);
      }

      /* Attempt to connect to an access point */
      char *ssid = WLAN_SSID;             /* Max 32 chars */
      Serial.print(F("\nAttempting to connect to ")); Serial.println(ssid);

      /* NOTE: Secure connections are not available in 'Tiny' mode! */
      if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
        Serial.println(F("Failed!"));
        while(1);
      }

      Serial.println(F("Connected!"));

      /* Wait for DHCP to complete */
      Serial.println(F("Request DHCP"));
      while (!cc3000.checkDHCP())
      {
        delay(100); // ToDo: Insert a DHCP timeout!
      }

      ip = 0;
      // Try looking up the website's IP address
      Serial.print(SERVER); Serial.print(F(" -> "));
      while (ip == 0) {
        if (! cc3000.getHostByName(SERVER, &ip)) {
          Serial.println(F("Couldn't resolve!"));
        }
        delay(500);
      }

      cc3000.printIPdotsRev(ip);

      client = cc3000.connectTCP(ip, 80);
    }

    void loop()
    {
      if(!cc3000.checkConnected())
      {
        cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY);
        Serial.println("connection was lost but succefully retrieved");
      }
      if(!client.connected())
      {
        client = cc3000.connectTCP(ip, 80);
        Serial.println("client lost connection but succefully retrieved it");
      }

      String request = "GET " + DIRECTORY + " HTTP/1.1\r\n" +
                   "Host: " + SERVER + "\r\n" +
                   "Connection: keep-alive\r\n\r\n";
      send_request(request);
    }

    /**************************************************************************/
    /*!
        @brief  Tries to read the CC3000's internal firmware patch ID
    */
    /**************************************************************************/
    uint16_t checkFirmwareVersion(void)
    {
      uint8_t major, minor;
      uint16_t version;

    #ifndef CC3000_TINY_DRIVER
      if(!cc3000.getFirmwareVersion(&major, &minor))
      {
        Serial.println(F("Unable to retrieve the firmware version!\r\n"));
        version = 0;
      }
      else
      {
        Serial.print(F("Firmware V. : "));
        Serial.print(major); Serial.print(F(".")); Serial.println(minor);
        version = major; version <<= 8; version |= minor;
      }
    #endif
      return version;
    }

    void send_request (String request) {
      String req = request;
      if (client.connected())
        {
          client.print(req);
          delay(5);
          client.println();
          delay(5);
        }
        else
        {
          Serial.print(F("failed to connect from loop"));
          return;
        }

      // read response
      while (client.connected()) {
        while (client.available()) {
          if(finder.find("\n\r")){
        int line = finder.getValue();
        Serial.print(line);
          if (line == 1) {
            digitalWrite(pin, HIGH);
            Serial.println("LED ON");
          }
          else {
            digitalWrite(pin, LOW);
            Serial.println("led off");
          }
        }
        }
      }
      client.close();
    }

can somene tell me how to reduce this delay time?

title: error parsing data from server using arduino uno and cc3000 shield

Answers: 0


body:
I programming atmega328P bootloaded with an FTDI.

Some tutorial mentions that you have to connect the DTR to the reset pin:

http://electronics-diy.com/FT232RL_USB_to_Serial_Adapter_for_PIC_AVR_ATMEGA_ARDUINO_MCUs.php

Is that so? Because some don't, they just say rx,tx is enough. I still can't program the chip with the error:

     avrdude -p m328p -P /dev/ttyUSB0 -c avrisp -b 9600 -n -v -v -v

    avrdude: Version 5.11.1, compiled on Oct 18 2011 at 21:17:35
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2009 Joerg Wunsch

             System wide configuration file is "/etc/avrdude.conf"
             User configuration file is "/root/.avrduderc"
             User configuration file does not exist or is not a regular file, skipping

             Using Port                    : /dev/ttyUSB0
             Using Programmer              : avrisp
             Overriding Baud Rate          : 9600
    avrdude: ser_recv(): programmer is not responding
    avrdude: stk500_recv(): programmer is not responding

    avrdude done.  Thank you.

I tried different baud rates, no matter what it's not responding. Linux recognizes the FTDI as:

    Sat Feb 13 22:52:14 2016] ftdi_sio ttyUSB0: FTDI USB Serial Device converter now disconnected from ttyUSB0
    [Sat Feb 13 22:52:14 2016] ftdi_sio 1-2.1:1.0: device disconnected
    [Sat Feb 13 22:52:19 2016] usb 1-2.1: new full-speed USB device number 73 using uhci_hcd
    [Sat Feb 13 22:52:20 2016] usb 1-2.1: New USB device found, idVendor=0403, idProduct=6001
    [Sat Feb 13 22:52:20 2016] usb 1-2.1: New USB device strings: Mfr=1, Product=2, SerialNumber=3
    [Sat Feb 13 22:52:20 2016] usb 1-2.1: Product: FT232R USB UART
    [Sat Feb 13 22:52:20 2016] usb 1-2.1: Manufacturer: FTDI
    [Sat Feb 13 22:52:20 2016] usb 1-2.1: SerialNumber: A6004mhS
    [Sat Feb 13 22:52:20 2016] ftdi_sio 1-2.1:1.0: FTDI USB Serial Device converter detected
    [Sat Feb 13 22:52:20 2016] usb 1-2.1: Detected FT232RL
    [Sat Feb 13 22:52:20 2016] usb 1-2.1: FTDI USB Serial Device converter now attached to ttyUSB0
    [Sat Feb 13 22:56:25 2016] usb 1-2.1: USB disconnect, device number 73
    [Sat Feb 13 22:56:25 2016] ftdi_sio ttyUSB0: FTDI USB Serial Device converter now disconnected from ttyUSB0
    [Sat Feb 13 22:56:25 2016] ftdi_sio 1-2.1:1.0: device disconnected

Well my questions now are:

1, When I use the Arduino IDE to program a barebone 328P with this FTDI what should be the **BOARD** and what should be the **PROGRAMMER**?

Right now I have it on Arduino Nano/Atmega328 + AVRISP mkII

Although I tried almost all... I think something else is wrong.

2, Should I be able to get any result with doing the previous:

     avrdude -p m328p -P /dev/ttyUSB0 -c avrisp -b 9600 -n -v -v -v

command WITHOUT connecting the barebone chip? I think not, since this doesn't act like a fully fledged MCU just like a serial converter.

Thanks

title: FTDI stdk 500k not responding

Answers: 2

body:
You need to connect DTR to the reset pin because the Arduino IDE (really avrdude) needs to be able to reset the processor in order to return control to the bootloader, which will then receive the new program. When an Arduino board is running your sketch, the serial port is available for use by the sketch; it can't be used to upload a new program.

To answer your first question, you should set the board to whatever your board actually is. You don't have to worry about the programmer. It's only used if you use the "upload with programmer" function. The normal "upload" function uses the serial port to send the sketch to the board via the bootloader. That's what you want. Note that while you don't have to set the programmer, you do have to set the port.

You can use avrdude to program the Arduino through the serial port via the bootloader. That's exactly what the IDE does. You have to specify the port just as you do in the IDE. To determine the other settings, look up your board in the Arduino IDE's boards.txt file. Most of what boards.txt does is tell the IDE how to invoke avrdude.

I suspect that one reason why avrdude isn't working for you is that you've set the baud rate to 9600.  According to boards.txt the upload speed for the Nano with the ATmega328P is 57600.

body:
> Right now I have it on Arduino Nano/Atmega328 + AVRISP mkII

Tha AVRISP is not an FTDI programmer. How do you have it wired up?

See: [How to make an Arduino-compatible minimal board](http://www.gammon.com.au/breadboard)

From that page, this is how I hooked up my FTDI cable:

[![FTDI connections][1]][1]

And a close-up:

[![Close-up of FTDI][2]][2]

You need RTS, via a 0.1 µF capacitor (in series) in order to trigger a reset.

  [1]: https://i.stack.imgur.com/0ymm8.jpg
  [2]: https://i.stack.imgur.com/V9wye.jpg


body:
I found this thread here which describes procedure to change the produce-name of Teensy
However when we open device properties we see 'Teensy USB Serial (COM xx) in the Device function summary.

Please find the image below to understand what I am referring to.

[![Teensy Device Properies][1]][1]

So is there any way to change this details as well?

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

title: Change device Function Summary for Teensy-LC

Answers: 0


body:
I need to operate 2 different sensors (gas and temp) simultaneously.
I have managed to run each one of them separately and I don't know how to manipulate the code so they could work together. My background in coding is basic and I'm not the one who wrote these codes.

Here are the sketches:

Thermistor code:

    void setup() {
      //This function gets called when the Arduino starts
      Serial.begin(9600);
      //This code sets up the Serial port at 9600 baud rate
    }

    void loop() {
      //This function loops while the arduino is powered
      int val; //Create an integer variable
      val=analogRead(0);
      //Read the analog port 0 and store the value in val
      Serial.println(val);
      //Print the value to the serial port
      delay(1000);
      //Wait one second before we do it again
    }

This is the gas detector code:

    /* GAS Sensor MQ-2
    This sensor detects flammable gasses
    the board has four pins
    connect AO to Arduino pin A0
    connect DO to Arduino pin 2
    connect Gnd to Arduino Gnd
    connect Vcc to Arduino 5 volts
    */

    int sensorPin = A0;
    // select the input pin for the potentiometer
    int DOPin = 2;
    // select the pin for the LED
    int sensorValue = 0;
    // variable to store the value coming from the sensor
    int ledPin =13;

    void setup() {
      // declare the ledPin as an OUTPUT:
      pinMode(DOPin, INPUT);
      pinMode(ledPin, OUTPUT);
      Serial.begin(9600);
    }

    void loop() {
      // read the value from the sensor:
      sensorValue = analogRead(sensorPin);
      Serial.print("Analog Output = ");
      Serial.println(sensorValue);
      // turn the ledPin on if triggered
      if (digitalRead(DOPin) ==HIGH) {
        digitalWrite(ledPin, LOW);
        Serial.println("Digital Output = OFF");
      } else {
        digitalWrite(ledPin, HIGH);
        Serial.println("Digital Output = ON");
      }
      delay(1000);
    }

title: Combining code for multiple sensors in one program

Answers: 1

body:
You just need to assign the sensors different pins.

    /* GAS Sensor MQ-2
    This sensor detects flammable gasses
    the board has four pins
    connect AO to Arduino pin A0
    connect DO to Arduino pin 2
    connect Gnd to Arduino Gnd
    connect Vcc to Arduino 5 volts
    */

    int gasSensorPin= A0; // GAS sensor pin
    int DOpin= 2; // select the pin for the LED
    int gasSensorValue= 0; // variable to store the value coming from the sensor
    int ledPin = 13;

    int tempSensorPin = A1;  //Temperature sensor pin
    int tempSensorValue;

    void setup() {
     // declare the ledPin as an OUTPUT:
     pinMode(DOPin, INPUT);
     pinMode(ledPin, OUTPUT);
     Serial.begin(9600);
     }

    void loop() {
     // read the value from the sensor:
     gasSensorValue= analogRead(gasSensorPin);
     Serial.print("Analog Output = ");
     Serial.println(gasSensorValue);
     // turn the ledPin on if triggered
     //
     if (digitalRead(DOpin) == HIGH){
     digitalWrite(ledPin, LOW);
     Serial.println("Digital Output = OFF");
     }
       else {
         digitalWrite(ledPin, HIGH);
         Serial.println("Digital Output = ON");
      }

    Serial.print("Temperture: ");
    tempSensorValue = analogRead(tempSensorPin));
    Serial.println(tempSensorPin);  //Print the value of pin A4

    delay(1000);
    }

This is your combined sketch.


body:
I was learning to program for a *void obstacle robot* but when I looked at the code I saw two data types long and int.

Int are datatypes that holds  -2,147,483,648 to 2,147,483,647.
Long are also datatypes that holds -2,147,483,648 to 2,147,483,647.

Int and long are like same but I came up with the code where two types of datatype is used as seen below:

    int trigPin = 2;
    int echoPin = 4;
    long duration, cm, inches;

But how can you know when to use which datatype? I searched a lot in the web but I didn't understand so can someone explain this to me please.

title: Difference between data type int and long on Arduino

Answers: 6

body: `int` in AVR GCC is **16** bits, *not* 32.

body:
On the Arduino (AVR models) an `int` is 16 bits, not 32 bits. Thus it goes from -32768 to +32767.

That is **different** from `long` which is 32 bits.

body:
According to the C language specification, `int` must be at least 16 bits or longer and `long` must be at least 32 bits or longer.

It is OK for a compiler to implement `int` as 32 bits or even 64 bits. It is OK for a compiler to implement `long` as 64 bits or longer. But it is not allowed for a compiler to implement `long` as 16 bits.

So when to use which type?

If the values you will be working with can be represented within 16 bits then it's OK to use `int`. If you need more than 16 bits use `long`. If you need more than 32 bits use `long long`.

Do not be caught up with compiler and/or CPU specifics. As mentioned by others, even within the same product range, Arduinos, there are 16 and 32 bit CPUs available. Instead, only trust what the standard guarantees.

The full specification of types in C are:

- `char` must be at least 8 bits
- `int` must be at least 16 bits
- `long` must be at least 32 bits
- `long long` must be at least 64 bits

Note: It is perfectly legal for compilers to implement char, int, long and long long as 64 bits. This is in fact not uncommon among DSPs.

body:
I like to use types from `stdint.h`.

While they do have minor drawbacks, the benefit they provide is you know exactly the size your are handling, even when compiling on other architectures.

    #include <stdint.h>

    uint8_t  my_byte = 0xf0;
    int16_t  trig_pin = 2;
    int16_t  echo_pin = 4;
    uint32_t duration, cm , blah;
    uint64_t big_int;

    // etc.

But obviously you don't want to be moving around a bunch of int32_t when your data only needs int16_t.

body:
It's the same reasoning as in C: the size of the `int` type is expected to be *the natural word size that your system handles most efficiently*. It must also be at least 16 bits wide, no smaller than a `short`, and no larger than a `long`.

So an `int` may be 16-, 32-, or 64-bits, based on the whatever your system handles best, and so is most likely to be 16 bits wide on an 8- or 16-bit CPU, 32 on a 32-bit CPU etc.

I use `int` when I want the best performance, whilst taking care to guard when I need more range than offered by 16 bits. These days, you tend to know when you are writing application code for 16-bit systems, although that's not so true for "library" code where portability may be of greater concern.

In your example, assuming the author had chosen their types carefully, the `int` variables probably require a small range and could afford to be word-size, leading to potentially shorter or faster code (or both). The `long` ones presumably required more than 16-bit range (they are guaranteed to be at least 32 bits wide). On the processor you'd selected as a compilation target, it looks like `int` and `long` were both implemented as 32-bit; this would be different (or *should* be) if you selected a 16-bit target CPU.

body:
if you are using Esp32 boards in Arduino IDE:
[![enter image description here][1]][1]

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


body:
While working for the automation side of my new house, I'm currently in the process of installing several reed switches on top of external doors and windows.

Even if this could be used as a "security" infrastructure, I'm more interested, at the moment, at the "automation" side (*checking the status of door and windows without the need to physically watch them*) and as such, I'm going to extend the arduino-based infrastructure I've already planned and prototyped [*more details [here][1]*].

This is the reed-switch I've installed (1€ coin added for size reference):

[![reed switch photo][2]][2]

and this is the related circuits:

[![reed switch circuits][3]][3]

As you can see, it comes with two circuits: one related to the "switch" funcionality; another one as a safety-measure to catch some "cuts" along the wires.

To check its status, currently, I've configured:

 - "contact circuit":
   - one end to an Arduino GROUND_PIN;
   - the other end to Digital PIN 52 (REED1_SW_Pin);

 - "tamper circuit":
   - one end to an Arduino GROUND_PIN (same GND pin as above);
   - the other end to Digital PIN 50 (REED1_AT_Pin);

 - Arduino setup:
   - `pinMode(REED1_SW_Pin, INPUT_PULLUP)`
   - `pinMode(REED1_AT_Pin, INPUT_PULLUP)`

 - Arduino code:
   - the main code-block handling REED events is reported below

Even tough everything is working fine, I wonder if there are better approaches, expecially inchecking the status of door and windows without the need to physically watch them terms of POWER-CONSUMPTION. So, here are my questions:

 1. **TAMPER-Circuit**: due to its nature, it will always be a "closed" circuit, with current flowing inside, from REED1_AT_Pin to GND. Currently I'm checking its state every 1 second (`#define REED_AT_CHECKDELAY   1000`) but a frequency of once every 5 seconds, or even 10 seconds would be acceptable (for me). So I would like to have the current flowing _ONLY_ during the "checking-timeframe". Something like:
      - every 5 seconds...
      - power-up something, getting the current flowing along the circuit;
      - check if the current flows;
      - if yes => OK
      - if no => set/keep the ALARM state
      - power-down the "something"

Is it feasible? If yes, how? Also: is it worth the effort?

2. **REED-switch circuit**: same as above. Polling approach is still acceptable (for me) but frequency need to be relatively high (5 seconds max), in order to keep of sort of "near-real-time feedback" when opening/closing windows. Best would be 2 secs polling-interval.
With such a timing, does the polling-approach make sense?

3. from an "electronic" point of view, what is the "to-be-preferred-scenario" for the Arduino board:
    - having a small, fixed, steady current, flowing out from a PIN, for _YEARS_ on a 24/7/365 basis or...
    - having a continuosly transition from LOW->HIGH->LOW for a Digital PIN, say once every 5 seconds, again, for YEARS?

Every comment, sidenotes, hints, critics, whatever... is **REALLY** welcomed/appreciated.

----------

## Arduino code-block handling REED events ##

BTW: the full-code, where the REED switch is handled togheter with pushbuttons and relays, [it's available on GitHub][4]
<pre>
    [...]
    if (reed_sw1_state != reed_sw1_previous_state) {
        // a change occurred. Are we in a "boucing" window?
        if (millis() - last_reed_sw1_debounce > REED_DEBOUNCE) {
          // no. So it's a real change
          // Let's handle the event...
          Serial.print(millis());
          Serial.print("[REED] - SW1 state CHANGED from [");
          Serial.print(reed_sw1_previous_state);
          Serial.print("] to [");
          Serial.print(reed_sw1_state);
          Serial.println("]");
          reed_sw1_previous_state = reed_sw1_state;
          last_reed_sw1_debounce = millis();
        } else {
          // yes. Let's ignore it
        }
      }

      // Let's check REED Switches anti-tamper state
      if (millis()-reed_at1_lastcheck > REED_AT_CHECKDELAY) {
         reed_at1_state = ! digitalRead(REED1_AT_Pin);
         if (reed_at1_state == HIGH ) {
            Serial.print(millis());
            Serial.print("[REED] - AT1 state OK [");
            Serial.print(reed_at1_state);
            Serial.println("]");
         } else {
            Serial.print(millis());
            Serial.print("[REED] - AT1 state ALARM - OnGoing TAMPER!!! [");
            Serial.print(reed_at1_state);
            Serial.println("]");
         }
         reed_at1_lastcheck = millis();
      }
      [...]
</pre>

  [1]: https://arduino.stackexchange.com/questions/15834/how-to-interconnect-multiple-arduinos-with-a-rpi-to-control-home-lights-switches
  [2]: https://i.stack.imgur.com/hFchU.png
  [3]: https://i.stack.imgur.com/Gq0GH.png
  [4]: https://github.com/verzulli/arduino-smart-home/tree/master/TEST_NETWORKED_BUTTON_WITH_REED

title: "tamper" circuit of a reed switch: can I connect the two wires to an INPUT and an OUTPUT pin?

Answers: 1

body:
>  So I would like to have the current flowing ONLY during the "checking-timeframe".

Turn off the pull-up until just before checking. Allow a few milliseconds for the pull-up to raise the voltage.

> With such a timing, does the polling-approach make sense?

Certainly, if you are trying to save battery power.

---

Bear in mind the voltage drops over long cable runs (and also possibly induced spikes). You might want a more powerful pull-up (eg. 10k) rather than the inbuilt 50k. You can still organize that by having an output pin turn on the voltage to the pull-up. Or, have the pull-up wired in permanently but instead of running the other side to ground, set the "ground" wire to `OUTPUT` and write `LOW` to it - and then set it to `INPUT` when you want it to be inactive.

See my post about [Power saving](http://www.gammon.com.au/power) - you could use a watchdog timer to wake the device at (say) every 4 seconds, to check things.

You may want to add in input-circuit protection (eg. a couple of diodes) to dampen down any incoming spikes. Even something simple like this:

[![Input protection][1]][1]

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


body:
I am using the following code to enable an interrupt for a pin:

    *digitalPinToPCMSK(pin) |= bit (digitalPinToPCMSKbit(pin));  // enable pin
    PCIFR  |= bit (digitalPinToPCICRbit(pin)); // clear any outstanding interrupt
    PCICR  |= bit (digitalPinToPCICRbit(pin)); // enable interrupt for the group

But I can't disable it. I am trying with this code:

    if (*digitalPinToPCMSK(pin) == 0)
    *digitalPinToPCICR(pin) &= ~(1<<digitalPinToPCICRbit(pin));

but it isn't working.

title: Detaching interrupts

Answers: 1

body:
Don't you mean:

      PCICR  &= ~bit (digitalPinToPCICRbit(pin));


body:
This is my first question on this site, and I'm relatively new with Arduino. I do have some experience using the board to reprogram a robot that used infrared proximity sensors, servos, and switches.

I would like to add a sensor on to the robot that will allow him to recognize specific "obstacles" that I will put in his environment (not walls!) For instance, when he sees a red card, he needs to spin, but when he sees a green card, he needs to roll in the opposite direction. I do not want to spend much on the cards, but I would be willing to put a small battery and LED in them if I had to. The cards do not necessarily need to be colored, I was just using that as an example.

The robot will be in a well-lit room with noise in the background. He will be controlled by an Arduino Uno, an infrared sensor and a remote control. He can be pretty close to the cards if he has to (3 centimeters or so would be enough). It would be ideal if he could discern different types of cards, but that is not necessary as long as he's able to tell a card from the rest of his environment.

I am simply not sure how to go about implementing this. I have read about using photoresistors to differentiate color, and they're really cheap, but will they be accurate enough from a distance? This is the light sensor I was considering using:

http://www.mouser.com/ProductDetail/Adafruit/161/?qs=GURawfaeGuDpQ5XPTNqKUw==&gclid=Cj0KEQiA6IC2BRDcjPrjm_istoUBEiQASrLz1rQNwZgntUcccnOmrFph-pCbu60R00GNozB_XbZxYz0aAn0j8P8HAQ

I'm willing to pay about 5$ for one if I need to.

If I use the light sensor method, can I just use brightly colored cards or will I need to use LEDs? Is there a better way to accomplish my goal that you are aware of?

Thank you for your time. If there is missing information in my question, please tell me and I will add it.

title: How can I get my Arduino to recognize a specific object using some kind of sensor?

Answers: 3

body:
If you are controlling your robot with a remote control, why do you need it to detect cards, instead you can tell it to do whatever you want right?

If you want to detect specific objects according to their colors, arduino is not a platform i will choose, because it doesn't have processing power to do image processing.

But take a look at this, http://charmedlabs.com/default/pixy-cmucam5/ it can talk to arduino, and you can train it by telling it identify colored objects which i might think is apt for your case.
RFID tags will be a good idea as @Majenko said.

body:
Detecting colour with RGB illumination and an LDR is not particularly accurate in my experience.  The idea is you illuminate the card (or whatever) with red light, take an LDR reading, then with green then blue.

This gives you a set of 3 light levels for the different colour components of the object.  Combining them together gives you an RGB signature for the object.  Ideally, on say a red card, the value from the LDR under red illumination is much stronger, and blue & green much weaker.

RGB LED + LDR colour detection *does work*, but it's not accurate, and it helps to block out ambient lighting.  Maybe if you put a lot of time into calibration, it would for you.  I had a classroom of 14 kids, each made-up one of these circuits, yet only a couple had any moderate success, if at all.
That said, we were using very cheap RGB LEDs and similar quality LDRs.

There's a bunch of stuff you can do to help the accuracy, like subtract readings with only ambient illumination, take multiple readings, etc.

I think you would save yourself a lot of time and frustration buy using a purpose-made colour sensor.

Something like the ADAFruit Colour Sensor -  https://www.adafruit.com/products/1334

body:
You can get an RFID reader for $7 from eBay:

[![RFID reader][1]][1]

Cards are around 30 cents:

[![RFID card][2]][2]

I have example code for an [entry control system](http://www.gammon.com.au/forum/?id=12869) which uses that reader.

The cards tend to activate at around 3 cm to 5 cm, so that sounds about right. Of course they aren't particularly directional, but if you are driving in a certain direction and it detects a card it is probably in front of you (however possibly off to one side).

You could combine card detection with simple range finding using an ultrasonic detector.

  [1]: https://i.stack.imgur.com/iRHQx.jpg
  [2]: https://i.stack.imgur.com/HF3h5.jpg


body:
I have 5 LDR and Arduino Mega. I connect them and get light level.

    void loop() {
    // print the analog output in milli volts
    int w=analogRead(west);
    Serial.print("west = ");

    Serial.print(w);
    Serial.println(" mv");

    int e=analogRead(east);
    Serial.print("east = ");

    Serial.print(e);
    Serial.println(" mv");

    int n=analogRead(north);
    Serial.print("north = ");

    Serial.print(n);
    Serial.println(" mv");

    int s=analogRead(south);
    Serial.print("south = ");

    Serial.print(s);
    Serial.println(" mv");

    int c=analogRead(control);
    Serial.print("control = ");

    Serial.print(c);
    Serial.println(" mv");

    delay(1000);

    if(e > w)
    Serial.println("west");

    else if(e < w)
    Serial.println("east");

    else if(s > n)
    Serial.println("south");

    else(s < n);
    Serial.println("north");

    Serial.println("\n");
    }

This is my loop and I always see east-north. When west is bigger than east I also see east. What

title: while compare, something is wrong

Answers: 2

body:
<!-- language-all: lang-C++ -->

Here:

    else(s < n);
    -----------^

That is wrong. See [Arduino programming traps, tips and style guide](http://www.gammon.com.au/tips#trap13).

---

## Trap #13: Don't put a semicolon at the end of every line

Semicolons end statements. However `if`, `for` and `while` are *compound* statements, so they should *not* have a semicolon after them like this:

**Wrong! ...**

      if (temperature > 40);    // <----- this semicolon is incorrect!
        {
        digitalWrite (furnaceControl, LOW);
        digitalWrite (warningLight, HIGH);
        }

      for (int i = 0; i < 10; i++);   // <----- this semicolon is incorrect!
        digitalWrite (i, HIGH);

The semicolons above (as indicated) terminate the `if` and `for` so they don't do anything useful. The lines following them are just unconditional blocks of code which are always executed, once.

**Correct:**

      if (temperature > 40)
        {
        digitalWrite (furnaceControl, LOW);
        digitalWrite (warningLight, HIGH);
        }

      for (int i = 0; i < 10; i++)
        digitalWrite (i, HIGH);

body:
Nick Gammon correctly points out a problem due to an extra semicolon, but you should also note what the construct `else(s < n)` is doing.  When the `if` condition that this `else` gives an alternative to is false, the statement   `(s < n)` gets executed.  That statement is an expression statement, and its value is the evaluation of `s<n`, either true or false.

If the semicolon after `(s < n)` weren't there, you'd get a compile error because `(s < n) serial.println("north")` is not a valid statement.  You may have meant to say `else if(s < n)` instead of `else(s < n)`.

Note, in the sequence

    if (e > w)
       Serial.println("west");
    else if (e < w)
       Serial.println("east");
    else if (s > n)
       ...

that last `else` typically is reached only rarely, because the only condition to get to it is `e` and `w` being equal.  Due to sensor noise and signal processing noise, the chance of `e` and `w` being equal is probably at most a few percent.

If your north/south test sequence is supposed to be independent of your east/west test sequence, leave out the second `if` and second `else` .  That is, instead say:

    if (e > w)
       Serial.println("west");
    else
       Serial.println("east");
    if (s > n)
       ...


body: Anybody here knows the physical dimensions(size) of the new Aduino MKR1000 board?

title: Physical dimensions(size) of the new MKR1000 board?

Answers: 1

body: If the diagram on the main page is to scale, then it's approximately 2.2 inches by 1.0 inches.


body:
Lately, we got an old arduino uno donated from a friend and have been trying to get it to work with servos. We have been having very perplexing results. We have tried many different "stock" code and servo combinations with our servos, but here is the behavior:

 - 180 Servos automatically move to right max as soon as power is applied.
 - Sail Winch servo moves a tiny amount and then stops. If power wire is removed and then reapplied, the servo moves another tiny amount.

The code is very simple. First we call the `servo.attach(pin)`, and confirm the pin. We have also tried doing the manual uSec definition: `servo.attach(pin, 600, 2400)`. In our loop() we have tried `servo.write(*value from 0-180*)` and `servo.writeMicroseconds(*value in PWM range*)`

Power is being supplied by a 9v battery, the sensor (yellow) is directly in digital pwm pin, while red (power) is in **+** and black (ground) is in **-**.

**I'm trying to decide whether I should invest in another arduino system.**

servos:

[180 servos][1]

[Sail Winch servo][2]

  [1]: https://www.servocity.com/html/hs-322hd_standard_deluxe.html
  [2]: http://www.hobbyking.com/hobbyking/store/__20853__SW5513_4MA_Sailwinch_Servo_10_63kg_55g_0_9.html

title: Do I have a faulty arduino uno, or have I found an Arduino bug?

Answers: 1

body:
If the Arduino "fails" the moment you apply power to a motor, you can bet that it is a power issue.

Or possibly you are exceeding the output rating of the output pin. You should not draw more than 20 mA from each output pin continuously.

> I'm trying to decide whether I should invest in another arduino system.

Power the motor independently of the Arduino. This is normal advice for all but very small motors. Also make sure that you have a suitable driving transistor / MOSFET if the motor draws more than 20 mA. Take into account any surge startup current.

---

See [Driving motors, lights, etc. from an Arduino output pin](http://www.gammon.com.au/motors) for some design ideas.

For example:

[![MOSFET driver][1]][1]

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


body:
I am currently working on a program for an Arduino uno and want to, in the program, when it receives a 16 digit number from a serial transmition, it will split the 16 digit number into 4 separate 4 digit numbers.

For Example:
The computer sends the Arduino the number 1100115011001150 and I want the Arduino to break the number so that "Avalue" would equal 1100, "Bvalue" would equal 1150, "Cvalue" would equal 1100 and so on...

Thanks for any help you can provide!

title: Splitting String from Serial

Answers: 4

body:
    int nums[] = {0, 0, 0, 0};   // must be always reset to zero if you will repeat this process
    while (Serial.available() < 16);   // wait for 16 chars to come in; easiest way to do this
    for (int i = 0; i < 4; i++){      // for each number
        for (int j = 0; j < 4; j++){    // for each digit in the number
            nums[i] *= 10;
            nums[i] += Serial.read() - '0';

    //while (Serial.available() == 0);
    //Serial.read();  // in case you use an extra character to separate numbers

    A = nums[0];
    B = nums[1];
    C = nums[2];
    D = nums[3];

If you are using a character or characters to delimit the 16-digit numbers being received, make sure to read off those extra characters before running the while loop again.

body:
    char ArrayBuffer[][4] = {};         // holds four characters, must be
declared as global to loop()

in

    loop()
    {
    byte Index = 0;                    // initialize array index
    if(Serial.available())             // have data in Serial buffer
    {
    byte Count = Serial.readBytes(ArrayBuffer[Index],4); // read       //4             //characters     into array buffer , returns actual number //of        characters //read and times out if less than 4 characters are //currently in Serial buffer
     Serial.println(ArrayBuffer[Index]); // print buffer to monitor
    }while(++Index != 4);              // read 4 by 4 characters from incoming stream
    }
...
continue with loop - process ArrayBuffer as required
}

This is one way to get the incoming stream from Serial buffer into for individual buffers, however, it is better, less chance of misdirecting the data into wrong buffer (index)  to read the entire buffer at once instead of using he readBytes four times.
Just my opinion, your mileage will vary.

PS what is the trick to format the code and text correctly ?
This is a mess.
I cannot get the code block to indent, I can get only the first ( four spaces line.

body:
    while (Serial.available() < 16);   // wait for 16 chars to come          easiest way to do this
    for (int i = 0; i < 4; i++){      // for each number
        for (int j = 0; j < 4; j++){    // for each digit in the number
            nums[i] *= 10;
            nums[i] += Serial.read() - '0';

Where did my last post - comment on this code went?
It was suppose to wait for "peers" approval, per note I got after I posted it.

This is not the best way to use "available()", beside what will happen if 16 characters never arrive?

body:
Not tested but should work.

    int nums[] = {0, 0, 0, 0};
    String inString = "";
    while (Serial.available() >= 16) {
      for (int k =0;k<4;k++) {
        for (int i =0;i<4;i++) {
          int inChar = Serial.read();
          if (isDigit(inChar)) {
            inString += (char)inChar;
          }
        }
        nums[k]=inString.toInt();
        inString = "";
      }
      Serial.println(nums[0]);
      Serial.println(nums[1]);
      Serial.println(nums[2]);
      Serial.println(nums[3]);
    }


body:
I am trying to hide libraries behind another, for simplicity. But I can't deal with the objects required by the libraries. Basically I want to use the objects both in my .cpp and .ino file, but I am getting errors about double definition, or not declared in this scope.

  *test.ino*

    #include "lib.h"
    #include "obj.cpp"

    void setup() {
      mesh.setNodeID(40);
      mesh.begin();
    }

    void loop() {
      mesh.update();
    }

  *lib.cpp*

    #include "Arduino.h"
    #include "lib.h"

    #include "obj.cpp"

    int message = 1;

    void send() {

      if (!mesh.write(&message, 'C', sizeof(message))) {

        // If a write fails, check connectivity to the mesh network
        if ( ! mesh.checkConnection() ) {
          //refresh the network address
          Serial.println("Renewing Address");
          mesh.renewAddress();
        } else {
          Serial.println("Sending failed, Test OK");
        }
      } else {
        Serial.print("Sent OK");
      }
    }

  lib.h

    #ifndef lib_h
    #define lib_h

    void send();

    #endif

  obj.cpp

    #include "RF24.h"
    #include "RF24Network.h"
    #include "RF24Mesh.h"
    #include <SPI.h>
    #include <EEPROM.h>

    RF24 radio(7, 8);
    RF24Network network(radio);
    RF24Mesh mesh(radio, network);

title: Defining object

Answers: 1

body:
<!-- language-all: lang-C++ -->

    #include "obj.cpp"

Don't include .cpp files. That gets them compiled twice (or more) and then you get duplicate definitions. Include .h files only.

What you are calling obj.cpp should probably be obj.h, however I haven't actually tried to compile it.

---

> it says that I have multiple definitions of the three objects

I tried compiling but I don't have the RF24 library. Anyway, this is wrong:

**obj.h**

    #include "RF24.h"
    #include "RF24Network.h"
    #include "RF24Mesh.h"
    #include <SPI.h>
    #include <EEPROM.h>

    RF24 radio(7, 8);
    RF24Network network(radio);
    RF24Mesh mesh(radio, network);

You can't *define* things there (like `radio`) which get included in multiple files. `obj.h` or `obj.cpp` it will be the same thing.

These lines need to be in **one** .cpp file:

    RF24 radio(7, 8);
    RF24Network network(radio);
    RF24Mesh mesh(radio, network);

Thus you cannot include that file in another file. However you can refer to them by making them `extern` in a header file, eg.

    extern RF24 radio;
    extern RF24Network network;
    extern RF24Mesh mesh;


body:
Im using an HC-05 Bluetooth module connected to my Arduino MEGA. The Arduino has an SD card with some data files stored (sensor readings). After the sensor readings are done, the Arduino then connects to Android phone via Bluetooth and transfers the file data.
This is working fine. Arduino sends the data to HC-05 over Serial port, which transfers it over the air to my Android phone.

But its kinda slow and I hence had a question.

QUESTION: Does the HC-05 buffer the data coming from the Arduino Serial and then send efficiently filled packets over the air. I would like to make sure that the HC-05 isn't inefficiently sending just a single byte or so per Bluetooth packet.

Thank you.

title: Arduino Bluetooth data (large data files) transfer efficiency using HC05 module

Answers: 0


body:
As a follow up to my earlier post: https://arduino.stackexchange.com/questions/20396/simultaneously-reading-data-from-multiple-serial-ports/20642#20642, I am stuck trying to develop a python sketch that can read the incoming serial data from the com port on my Arduino and unpack them from the buffer into two separate cvs files.

One of the csv files would contain the data from the first sensor, while the other would contain the data from the second sensor. I have been able to develop the sketch to a point where on receiving the first header byte the first sensor data is unpacked. I am finding it hard to adjust the sketch to allow for the second byte header to be called to unpack the second sensor data from the data packet. Below is my abbreviated sketch thus far. Thanks all.
<!-- language-all: lang-cpp -->

    def run(self):
        #Creating a csv file to read data from the first sensor
        self.click = open("ball_Data.csv", "wb")
        #Creating a csv file to read data from the second sensor
        self.flick = open("rugby_Data.csv", "wb")
        #creating the serial port object
        self.push = serial.Serial('COM6', 9600)
        while True:
            #If the incoming byte is equivalent to '$'
            if node == b'$':
                # the byte object is equivalent to the available bytes
                node = self.push.read()
                #an array to hold the sensor data
                sensor_array = []
                i = 0
                #This while loop initiates a count from 0 to 9
                #through the sensor array
                while i < 10:
                    #The available byte present
                    malcolm = self.push.read()
                    #The next byte
                    turnbull = self.push.read()
                    #The incoming uint_16 data is unpacked into the variable lingo
                    lingo= (struct.unpack('b', turnbull)[0] << 8) | struct.unpack('B',malcolm)[0]
                    #The variable lingo is then appended to the sensor array
                    sensor_array.append(lingo)
                    #If the length of the sensor array is equivalent to 9
                    #write the data through each count into the sensor array
                    if len(sensor_array) == 9:
                        self.click.write(str(sensor_array[0] ..+ str(sensor_array[9]))
                        #My idea is that this else statement was supposed to trigger
                        #the next header for the second sensor which would be an '#'
                        #sign before unpacking the data
                        else:
                            oldde = self.push.read()
                            sensor_array = []
                            i = 10
                            while i < 20:
                                #The available byte present
                                malcolm = self.push.read()
                                #The next byte
                                turnbull = self.push.read()
                                lingo= (struct.unpack('b', turnbull)[10]<<8)|struct.unpack('B',malcolm)[10]
                                sensor_array.append(lingo)
                                if len(sensor_array) > 19:
                                    self.flick.write(str(sensor_array[10]..+ str(sensor_array[19]))

                                    The Packet data structure for the first and second sensor is:
                                        Packet1 from sensor 1:
                                            data_array[0] = headerbyte('#')
                                            data_array[1] = acceleration_xAxis
                                            data_array[2] = acceleration_yAxis
                                            data_array[3] = acceleration_zAxis
                                            data_array[4] = temperature
                                            data_array[5] = gyro_xAxis
                                            data_array[6] = gyro_yAxis
                                            data_array[7] = gyroz_xAxis
                                            data_array[8] = checksum
                                            Packet2 from sensor 2:
                                                data_array[9] = headerbyte('$')
                                                .
                                                .
                                                .
                                                data_array[17] = checksum

title: Unpacking Arduino binary data on a python sketch

Answers: 1

body:
I'm somewhat confused by the flow of your program, so instead I will tell you how I would handle the data.

You have a single-byte header, then 7 bytes of data, followed by a single byte checksum.

PySerial's read is (I believe) blocking by default, so it's simple to read the next serial character - unlike an Arduino.  It also has a "multi-byte" read version where it can read a pre-set number of bytes from the stream for you.

So my methodology would be:

1. Read a byte.  Is it a '#' or a '$'?
2. If it is, remember which stream you are dealing with, then:
3. Read 7 bytes with `this.push.read(7)` into a byte array (or a string in python < 2.6)
4. Read one byte for the checksum. If the checksum is correct (whatever calculation you use for that) then unpack the data in the array.
5. Write the data to the correct file depending on the stream you remembered in step 2.

That way you're not duplicating code for each sensor stream, you are just saying "this packet is stream 2" and using that remembered fact once you have received the packet and verified that it's correct.

A better protocol arrangement, though, which is more reliable, involves both a start byte and an end byte, and your whole packet is wrapped in that pair of bytes.  You then have a "sliding window" arrangement whereby the incoming data bytes scroll past a window of a fixed width, and when the first and last characters in that window match your start and end bytes you then extract the middle section and do what you need to do with it.  That way if you have a $ or a # that is midway through a stream of data it won't trigger reception since the end byte doesn't match. It makes the whole synchronisation of the data more reliable.

For instance, if you have the current data packet that looks like `$ho9*$fup` and you miss the first bit of the data for whatever reason (arduino started transmitting before you were ready to receive, for instance) it might trigger reception on the second `$` which would give you incorrect values.  So instead if you have the start character as `$` and the end character as `#` and include a stream number, so your packet looks like:

    $1ho9*$fup#

Then when you scroll that past the window it would look like:

     $         #
     v         v
    [..........$]
    [.........$1]
    [........$1h]
    [.......$1ho]
    [......$1ho9]
    [.....$1ho9*]
    [....$1ho9*$]
    [...$1ho9*$f]
    [..$1ho9*$fu]
    [.$1ho9*$fup]
    [$1ho9*$fup#]

And the first and last characters match, so you receive the content.

If you were to miss the first $ the second $ wouldn't match - say the extended stream looks like: `$1ho9*$fup#$2hdiw83bf#` and you missed $1, the window would look like:

     $         #
     v         v
    [..........o]
    [.........o9]
    [........o9*]
    [.......o9*$]
    [......o9*$f]
    [.....o9*$fu]
    [....o9*$fup]
    [...o9*$fup#]
    [..o9*$fup#$]
    [.o9*$fup#$2]
    [o9*$fup#$2h]
    [9*$fup#$2hd]
    [*$fup#$2hdi]
    [$fup#$2hdiw] <= Doesn't match even though it starts with $
    [fup#$2hdiw8]
    [up#$2hdiw83]
    [p#$2hdiw83b]
    [#$2hdiw83bf]
    [$2hdiw83bf#] <= Matches - starts with $ and ends with #

As you can see the synchronising of your packet is then much more reliable. It would normally have incorrectly triggered on the first $ it saw.

There is always a chance that there may be a $ and a # in just the right positions within successive packets to fool the system, but the chances of that are somewhat slim.  You can add extra protection against that by "escaping" the start and stop bytes if they appear within your stream. There's many possible ways of handling that if you really need it.


body:
I'm already done copying/pasting the libraries that I know is needed to run the program, but I wonder why I always get this error every time I tried to run the code. What do you think would be the possible reason why I get this error:

      C:\Program Files (x86)\Arduino\libraries\I2Cdev\I2Cdev.cpp:64:14: warning:
      #warning Using current Arduino IDE with Wire library is functionally
      limiting.   [-Wcpp]

      #warning Using current Arduino IDE with Wire library is functionally limiting.

              ^

      C:\Program Files (x86)\Arduino\libraries\I2Cdev\I2Cdev.cpp:65:14: warning:
      #warning Arduino IDE v1.0.1+ with I2CDEV_BUILTIN_FASTWIRE implementation
      is recommended. [-Wcpp]

      #warning Arduino IDE v1.0.1+ with I2CDEV_BUILTIN_FASTWIRE implementation
      is recommended.

              ^

     C:\Program Files (x86)\Arduino\libraries\I2Cdev\I2Cdev.cpp:66:14: warning:
     #warning This I2Cdev implementation does not support: [-Wcpp]

     #warning This I2Cdev implementation does not support:

              ^

     C:\Program Files (x86)\Arduino\libraries\I2Cdev\I2Cdev.cpp:67:14: warning:
     #warning - Timeout detection (some Wire requests block forever) [-Wcpp]

     #warning - Timeout detection (some Wire requests block forever)

              ^

     In file included from C:\Program Files
     (x86)\Arduino\libraries\RTIMULib\RTIMUHal.cpp:27:0:

     C:\Program Files (x86)\Arduino\libraries\RTIMULib\RTIMUHal.cpp: In member
     function 'bool RTIMUHal::HALRead(unsigned char, unsigned char, unsigned
     char, unsigned char*, const char*)':

     C:\Program Files (x86)\Arduino\libraries\RTIMULib\RTIMUHal.h:59:37: error:
    'class HardwareSerial' has no member named 'printf'

     #define HAL_ERROR1(m, x)     Serial.printf(m, x);

                                     ^

    C:\Program Files (x86)\Arduino\libraries\RTIMULib\RTIMUHal.cpp:73:13: note:
    in expansion of macro 'HAL_ERROR1'

             HAL_ERROR1("I2C read failed - %s\n", errorMsg);

             ^

      C:\Program Files (x86)\Arduino\libraries\RTIMULib\RTIMUHal.cpp: In member
      function 'bool RTIMUHal::HALWrite(unsigned char, unsigned char, unsigned
      char, const unsigned char*, const char*)':

      C:\Program Files (x86)\Arduino\libraries\RTIMULib\RTIMUHal.h:59:37: error:
      'class HardwareSerial' has no member named 'printf'

      #define HAL_ERROR1(m, x)     Serial.printf(m, x);

                                     ^

      C:\Program Files (x86)\Arduino\libraries\RTIMULib\RTIMUHal.cpp:96:13:
      note: in expansion of macro 'HAL_ERROR1'

             HAL_ERROR1("I2C write failed - %s\n", errorMsg);

             ^

       C:\Program Files (x86)\Arduino\libraries\RTIMULib\RTIMUHal.cpp: In member
       function 'bool RTIMUHal::HALWrite(unsigned char, unsigned char, unsigned
       char, const char*)':

       C:\Program Files (x86)\Arduino\libraries\RTIMULib\RTIMUHal.h:59:37:
       error: 'class HardwareSerial' has no member named 'printf'

       #define HAL_ERROR1(m, x)     Serial.printf(m, x);

                                     ^

      C:\Program Files (x86)\Arduino\libraries\RTIMULib\RTIMUHal.cpp:119:13:
      note: in expansion of macro 'HAL_ERROR1'

             HAL_ERROR1("I2C write failed - %s\n", errorMsg);

             ^

      exit status 1
      Error compiling.

title: Is it possible to run the Teensy to the Arduino?

Answers: 0


body: What is the maximum of bits that an Arduino can read on the digital input, which model in the Arduino range can read the most bits?

title: How many bits can an Arduino uno read?

Answers: 2

body:
> What is the maximum of bits that an Arduino can read on the digital input, which model in the Arduino range can read the most bits?

A digital input is by nature binary (i.e. a single bit). The answer to your question is therefore one bit per digital input.

The total number of digital inputs depends on the board. It ranges from Arduino Micro (which has fewest less with than 10) to Arduino Mega which has the most with more than 60).

Another possible interpretation of your question is the resolution of an analog pin (ADC). The AVR has max 10 bit resolution.

Cheers!

body: Do you mean _simultaneous_ read or write? The AVR processors are 8-bit processors and their I/Os are grouped into 8-bit registers. If you configure all of the bits in a register to the same direction - all inputs or all outputs - then the entire 8 bits could be read/written at once. in C/C++ you would use the `PORTWhich I/Os are assigned to which register is designed into the chip - but the data sheet describes which physical pins are connected to which I/O register. You can take advantage of that to make use of a single register's-worth of pins for up to 8 signals that need to be set or read simultaneously.


body:
I'm currently working on a project where I need to use PID to get the correct speed for a motor when it is angled a certain amount.

The problem is that I'm only getting 0.00 and 255.00 as the speed. Nothing in between. The code is supposed to activate when the angle value is more than 1300 and less than -1300. The `ax` variable is from an MPU6050 sensor.

    int16_t ax, ay, az;

    double Setpoint, Input, Output;
    //Specify the links and initial tuning parameters
    double Kp=2, Ki=5, Kd=1;
    PID myPID(&Input, &Output, &Setpoint, Kp,Ki,Kd, DIRECT);

    void setup() {
      Input = analogRead(ax);
      Setpoint = 100;
      //turn the PID on
      myPID.SetMode(AUTOMATIC);
    }

    void loop() {
      accelgyro.getAcceleration(&ax, &ay, &az);
      int a=ax+10900;
      //Here I set the used variable to around 0. ax is actually around -10900
      //This is always true, this won't be in the final code. This is just making it work.
      if(1) {
        int val;
        val = map(a, -1300, 1300, 0, 1023);
        Input = val;
        myPID.Compute();
        Serial.println(Output);
      }
    }

title: PID not working correctly

Answers: 2

body:
Please respect others by presenting code that is readable. By doing that you may also find obvious errors in your code. Let me clean up the loop() and you will see what I mean.

    void loop() {
        int a = ax + 10900;
        if (1) {
          int val;
          val = map(ax, -1300, 1300, 0, 1023);
          Input = val;
          myPID.Compute();
          Serial.println(Output);
        }
      }
    }

So what is "int a = ax + 10900"? "ax" is not defined but the other use of it is as an analog pin number "Input = analogRead(ax)". And "a" is not used.

There is a condition that is always true "if (1)" and so on.

Cheers!

body:
How fast is your system compared to the loop() sampling time?  Does (100-map((ax+10900),-1300,1300,0,1024)) change appreciably during the sub-millisecond loop()?

With kI=5, an error of only 10 will saturate your 0-255 speed output in 26 iterations of loop(), potentially producing the behavior you see.  If you don't have control of your sampling time, the integral error can wind up (or down) to the process limits very quickly.

From https://www.arduino.cc/en/Reference/Map map() only linearly transforms the input data to the output data, but does not constrain() it to those limits.  If ax=-9000, then val would be greater than 1024.   Still, taking the normal working range of ax+10900 to be (-1300,1300) which is then mapped into  (0,1024), the Kp=2 term with a setpoint of 100 would produce a range of (-200,2048) constrained to the default (0,255) limits.

Working backwards from the setpoint of 100, through the 0-1024 map is 0.0975 along the (-1300 to 1300) range, or val = -949, or ax = -11849.  And the kP=2 times the mapping factor of 1024/2600 would change the output by 2*1024/2600=0.79 points for each step difference of ax from -11849.

The http://playground.arduino.cc/Main/MPU-6050 pages says the acceleration registers are 16 bit with high sensitivity, and suggests that 50 points of noise is a small variation.  If the sensor set for 16 bits for +/-2G into ax, then, each step change 60 micro-G.  If that is the source of your ax, then the small variations could easily saturate your control system, making it bang-bang between its output limits with only milli-G variations at the sensor.

Slow down your sampling time, reduce kI, and think of your Kp, Ki, and Kd as conversions of your measured and translated variable ax errors into output space (0-255 speed).

Also, in choosing a sampling time, consider how often you want the PID to make adjustments to the process.


body:
I currently have an Arduino Mega project that uses a relay to switch some high voltage loads. Currently, I use a scheduler library so that every 250ms I check if certain conditions are met and if so I turn off or on the relay. The relay is active when pulled down.

I'm trying to figure out how to transition this project to using a shift register. If the pin needs to be pulled low to be turned on and I want to keep it on, how do I supply a steady "low" signal using a shift register if the register is clocked to only latch every 8 clock cycles (not to mention I only run this code every 250ms). Even if every bit that gets sent by the shift register is low, do I need to no longer use the scheduling library so that every time through the Arduino loop I am sending the low signal so that the low signal can remain constant? With the standard Arduino pin once I set it to low it stays low until I switch it to high. But with a shift register can I keep it low "until I switch it high?"

title: Maintaining pull down on a relay with a shift register

Answers: 2

body:
You have misunderstood how shift registers work - and one of the main reasons they exist in the first place.

Shift register ICs have a common 'latch' pin which latches the data present at the input of the cell into the cell, thus updating the output. Some ICs also offer an "output enable", which switches the outputs to a high-impedance state irrespective of the values in the cells - this might not be useful in your case, but the feature exists.

With a serial-to-parallel shift register you can shift in as many bits as you want, at whatever rate you choose, and the outputs will never change **until you trigger a rising edge on the LATCH pin**.

----------

**How a (latching) Shift Register works:**

You have eight spaces within the register:

                 ___    ___    ___    ___    ___    ___    ___    ___
    [DATA_IN]-->|___|--|___|--|___|--|___|--|___|--|___|--|___|--|___|-->[DATA_OUT]
                BIT0                                              BIT7

The 'spaces' are chained together; at one end of the chain is the `DATA_IN` pin and at the other end is the `DATA_OUT` pin.

Every time there is a rising edge on the `CLOCK` pin, data is *shifted* down the chain from `DATA_IN` to `DATA_OUT`, one space at a time. For example, if the state of the 'spaces' is as the left hand column, then upon the rising edge of the `CLOCK` pin the spaces will change to the values in the right hand column:

     DATA_IN PIN = 1  ->  C  -> ?
    BIT0 'SPACE' = 0  ->  L  -> 1
    BIT1 'SPACE' = 1  ->  O  -> 0
    BIT2 'SPACE' = 1  ->  C  -> 1
    BIT3 'SPACE' = 0  ->  K  -> 1
    BIT4 'SPACE' = 0  ->  E  -> 0
    BIT5 'SPACE' = 1  ->  D  -> 0
    BIT6 'SPACE' = 1  ->  G  -> 1
    BIT7 'SPACE' = 0  ->  E  -> 1

You will see that `BIT(n)` changes to the value of `BIT(n-1)`, with `BIT0` changing to the value of `DATA_IN`. The `DATA_OUT` pin is used to daisy-chain multiple shift registers together. The important thing to note here is that **the outputs do not change without a rising edge on the `LATCH` pin**. You can pulse `CLOCK` as many times as you want, with whatever values on `DATA_IN`, and the outputs will not change. Ever.

When you finally trigger the `LATCH` pin, the value in each 'space' is latched into a second row of 'spaces' - these represent the outputs. On a latch trigger, the outputs therefore change to the values of the *last eight* bits that were shifted into the `DATA_IN` pin. For example:

    OUTPUT = 11001010
                       SHIFT IN "01101111" (starting with RHS first)
                                   TRIGGER RISING EDGE ON 'LATCH' PIN
    OUTPUT = 01101111
                       SHIFT IN "11110000110011001100"
                                   TRIGGER RISING EDGE ON 'LATCH' PIN
    OUTPUT = 11110000   i.e. the LAST EIGHT BITS that were shifted in
                       SHIFT IN "10"
                                   TRIGGER RISING EDGE ON 'LATCH' PIN
    OUTPUT = 10111100   again the LAST EIGHT BITS that were shifted in

It is generally never the case with a serial-in-parallel-out register that you would ever shift in less that eight bits at a time, so the last example is only there to illustrate the functioning of the IC.

body:
> ... relay ... active when pulled down ... shift register ... latch ... Arduino ...

TPIC6C595

`shiftOut()` and the '595


body: Hello I have just got my Arduino to read text from a text file and it is running perfectly. I was interested in being able to load a sketch into the Arduino and having it execute it, from and SD card. The Arduino wouldn't be connected to my laptop at all. I researched it and it is possible, with a different boot loader. Which is a bit annoying because I don't want to change the boot loader on my Arduino. I could put it on a standalone atmega chip but lets pretend I don't have those. So I was thinking if you had pre-compiled Arduino code. Which is in hex format and ready to be put on the board, would it be able to be loaded from the SD card? If so how would I go about doing this?

title: Arduino compiled sketch on sd card

Answers: 1

body:
Yes it is possible:

**With a different bootloader**.

You need something which will erase the old sketch from the chip, read the data from the SD card, and write that into the flash of the chip. The only thing that can do that is the bootloader or some external device (another ATMega328p chip which we have to pretend you don't have).

Due to the way the architecture works you can only execute code out of the flash, so you need to program your sketch into the flash somehow. And that is the role of the bootloader.


body:
**Is it possible to change pin operation from output to input within the Arduino loop (event-driven)?**

I would like to change the operation of a couple of Arduino pins from input to output during execution of the Arduino loop in an event-driven way. Is this possible please?

Answers: 1

body:
Yes.

Just call `pinMode([pin], [mode])` whenever you want to change from input to output or output to input.

How to decide when to do that is entirely up to you. You can do it any time you choose using any stimulus you like.


body:
Hello I have a String that contains the following: "println('hello world')".
I want to be able to remove everything from the String except for the text insie the brackets. Bear in mind that this text will change multiple times as the programme runs. How can I remove everything except for what is in the brackets from the string.

        String line1 = "println('hello world')";

Please help me thx.

title: Arduino disecting a string

Answers: 1

body:
> How can I remove everything except for what is in the brackets from the string?

There are a number of [String class][1] member functions that can help with this. First, [indexOf(val)][2] will help locate the character of interest. Second, [substring()][3] will help cut out the part you want. And as a bonus, using [lastIndexOf()][4] will allow brackets within the string.

    String s = "println('hello world')";
    s = s.substring(s.indexOf('(') + 1);
    s = s.substring(0, s.lastIndexOf(')'));

Cheers!

  [1]: https://www.arduino.cc/en/Reference/StringObject
  [2]: https://www.arduino.cc/en/Reference/StringIndexOf
  [3]: https://www.arduino.cc/en/Reference/StringSubstring
  [4]: https://www.arduino.cc/en/Reference/StringLastIndexOf


body:
I'm trying to control a pellet stove auger motor in such a way that I can use a toggle switch to do High/Low (H/L) - so the way that I have it now is:

     void setup() {
       // initialize digital pin 13 as an output.
       pinMode(13, OUTPUT);
       pinMode(12, OUTPUT);
    }

    // the loop function runs over and over again forever
    void loop() {
      digitalWrite(12, HIGH);
      digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(2850);              // wait for a second
      digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
      delay(11250);

Which is just LED on/off but it also controls another relay that controls the blower motor - what I'm trying to set up is a H setting that would be the 2850 delay-ON - and then have say: pin 11 have a delay-OFF of 7000, and have pin 13 still resetting to the delay-ON of 2850.

What I mean is:

 - loop A: pin12 on -delay 2850 pin12 off -delay 11250
 - loop B: pin13 on -delay 2850 pin13 off -delay 7000

I saw and tried the code for 'multi-blink' - as the one I use is pretty much modified 'blink'.

Any assistance would be awesome - I run the one I show above now, on my pellet stove and it was recently -31.4 and worked like a charm, but I'd like to be able to have a high/low option.

PS: I also have a coffee roaster control project as well... help on that one is always appreciated as well.

title: Trying to run two simultaneous loops that do the same task with different delay cycles

Answers: 2

body:
The Arduino [Simple Timer library][1] (and other similar timer libraries) are made for exactly this kind of application. Your `setup()` routine calls the SimpleTimer library, naming a callback-function and how often it should get called. Your loop function must then call `timer.run()` reasonably frequently (where
reasonably frequently" depends on the timing accuracy and jitter tolerance of your application). `timer.run()` will call each of your callback-functions at its appropriate time. You write the callback-functions to do whatever you need them to do when the timer calls them.

There are one-shot timers and repeating timers - it sounds like your application could one of each per LED: One that fires periodically, to to call a turn-on-LED12 function every (ON_TIME_12+OFF_TIME_12) ms, and a one-shot that calls a turn-off-LED12 function, started by the turn-on-LED_12 function for (ON_TIME_12) msec. Same for LED13, ( ..., etc.)

Your loop function is free to do whatever else, as long as it calls `timer.run()` frequently enough that your application can meet its timing requirements.

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

body:
This seems to be the perfect example for [the simple scheduler][1]:

    #include <Scheduler.h>

    const int pinA = 12;
    const int pinB = 13;

    void setup()
    {
      Serial.begin(9600);
      while (!Serial);
      Scheduler.start(setupA, loopA);
      Scheduler.start(setupB, loopB);
    }

    void loop()
    {
      Serial.print(millis());
      Serial.print(F(":pinA="));
      Serial.print(digitalRead(pinA));
      Serial.print(F(",pinB="));
      Serial.println(digitalRead(pinB));
      delay(1000);
    }

    void setupA()
    {
      pinMode(pinA, OUTPUT);
    }

    void loopA()
    {
      digitalWrite(pinA, HIGH);
      delay(2850);
      digitalWrite(pinA, LOW);
      delay(11250);
    }

    void setupB()
    {
      pinMode(pinB, OUTPUT);
    }

    void loopB()
    {
      digitalWrite(pinB, HIGH);
      delay(2850);
      digitalWrite(pinB, LOW);
      delay(7000);
    }

Cheers!

  [1]: https://github.com/mikaelpatel/Arduino-Scheduler


body:
I have burned out a few Pro Micro clones now. Initially I ran them using a 12VDC external raw power supply but two Pro Micro clones burned out pretty quickly this way. Another thread suggested that the Pro Micro clones use regulators that are not very robust. Since then, I've been using just USB power for my 5V/16MHz Pro Micro clones.

The third clone has been working fine on USB power only. I estimate that I uploaded a sketch I was working on about a dozen times. Suddenly the RxLED stayed lit and I can't upload to it anymore.

When I plug it in, Windows assigns a COM port successfully. The Arduino IDE sees the port and I can select it. This tells me the Pro Micro is not entirely dead. When I enable verbose mode for uploading in the Arduino IDE, here's what I get:

    Sketch uses 3,914 bytes (13%) of program storage space. Maximum is 28,672 bytes.
    Global variables use 148 bytes (5%) of dynamic memory, leaving 2,412 bytes for local variables. Maximum is 2,560 bytes.
    Forcing reset using 1200bps open/close on port COM3
    PORTS {COM3, } / {COM3, } => {}
    [repeating 19 more times]
    Uploading using selected port: COM3
    C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Users\Bartman\AppData\Local\Arduino15\packages\SparkFun\hardware\avr\1.1.2/avrdude.conf -v -patmega32u4 -cavr109 -PCOM3 -b57600 -D -Uflash:w:C:\Users\Bartman\AppData\Local\Temp\buildb15cf522f4023b15f86cbd1c900761d6.tmp/sketch_feb15a.ino.hex:i

    avrdude: Version 6.0.1, compiled on Apr 15 2015 at 19:59:58
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2009 Joerg Wunsch

             System wide configuration file is "C:\Users\Bartman\AppData\Local\Arduino15\packages\SparkFun\hardware\avr\1.1.2/avrdude.conf"

             Using Port                    : COM3
             Using Programmer              : avr109
             Overriding Baud Rate          : 57600
             AVR Part                      : ATmega32U4
             Chip Erase delay              : 9000 us
             PAGEL                         : PD7
             BS2                           : PA0
             RESET disposition             : dedicated
             RETRY pulse                   : SCK
             serial program mode           : yes
             parallel program mode         : yes
             Timeout                       : 200
             StabDelay                     : 100
             CmdexeDelay                   : 25
             SyncLoops                     : 32
             ByteDelay                     : 0
             PollIndex                     : 3
             PollValue                     : 0x53
             Memory Detail                 :

                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
               flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
               lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
               signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

             Programmer Type : butterfly
             Description     : Atmel AppNote AVR109 Boot Loader

    Connecting to programmer: .

and after some time:

    avrdude: butterfly_recv(): programmer is not responding
    Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

On my working Pro Micro clone, I get the following after instead:

    Found programmer: Id = "CATERIN"; type = S
        Software Version = 1.0; No Hardware Version given.
    Programmer supports auto addr increment.
    Programmer supports buffered memory access with buffersize=128 bytes.

    Programmer supports the following devices:
        Device code: 0x44

    avrdude: devcode selected: 0x44
    avrdude: AVR device initialized and ready to accept instructions

    Reading | ################################################## | 100% -0.00s

    avrdude: Device signature = 0x1e9587
    avrdude: reading input file "C:\Users\Bartman\AppData\Local\Temp\buildb15cf522f4023b15f86cbd1c900761d6.tmp/sketch_feb15a.ino.hex"
    avrdude: writing flash (3914 bytes):

    Writing | ################################################## | 100% 0.30s

    avrdude: 3914 bytes of flash written
    avrdude: verifying flash memory against C:\Users\Bartman\AppData\Local\Temp\buildb15cf522f4023b15f86cbd1c900761d6.tmp/sketch_feb15a.ino.hex:
    avrdude: load data flash data from input file C:\Users\Bartman\AppData\Local\Temp\buildb15cf522f4023b15f86cbd1c900761d6.tmp/sketch_feb15a.ino.hex:
    avrdude: input file C:\Users\Bartman\AppData\Local\Temp\buildb15cf522f4023b15f86cbd1c900761d6.tmp/sketch_feb15a.ino.hex contains 3914 bytes
    avrdude: reading on-chip flash data:

    Reading | ################################################## | 100% 0.04s

    avrdude: verifying ...
    avrdude: 3914 bytes of flash verified

    avrdude done.  Thank you.

On the now non-functional one, I tried using a jumper from RST to GND, tapping this twice quickly in succession and uploading from the IDE in an attempt to recover the Pro Micro but this doesn't work.

I don't think it's a bootloader problem since the Pro Micro does get a COM port assigned to it but never-the-less, I tried burning a new bootloader from my working Pro Micro. Here's my Pro Micro to Pro Micro wiring:
[![enter image description here][1]][1]

In the IDE, I've selected:

> Board: SparkFun Pro Micro

> Processor: ATmega32U4 (5V, 16 MHz)

> Port: [current COM port of working Pro Micro]

> Programmer: Arduino as ISP

But when I select `Tools->Burn Bootloader`, I get the following error:

    Arduino: 1.6.7 (Windows 10), Board: "SparkFun Pro Micro, ATmega32U4 (5V, 16 MHz)"

    C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Users\Bart_S\AppData\Local\Arduino15\packages\SparkFun\hardware\avr\1.1.3/avrdude.conf -v -patmega32u4 -cstk500v1 -PCOM6 -b19200 -e -Ulock:w:0x3F:m -Uefuse:w:0xCB:m -Uhfuse:w:0xD8:m -Ulfuse:w:0xFF:m

    avrdude: Version 6.0.1, compiled on Apr 15 2015 at 19:59:58
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2009 Joerg Wunsch

             System wide configuration file is "C:\Users\Bart_S\AppData\Local\Arduino15\packages\SparkFun\hardware\avr\1.1.3/avrdude.conf"

             Using Port                    : COM6
             Using Programmer              : stk500v1
             Overriding Baud Rate          : 19200
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x03
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x03
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x03
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x03
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x03
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x03
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x03
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x03
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x03
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x03

    avrdude done.  Thank you.

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

Is it permanently damaged? What are the next steps to troubleshoot this Pro Micro clone?

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

title: Pro Micro clone worked fine, now RxLED stays on and can't program it

Answers: 2

body:
To make things simpler, try flashing the Pro Micro firmware with another UNO (or compatible) hardware. I prefer an UNO clone with CH340 chip or a pro mini with a FTDI cable. Just to keep things simple.

Flash the UNO with Arduiono as ISP sketch. Use connection guidance from Arduino tutorial:
[Using an Arduino as an AVR ISP][1]

[![connection diagram][2]][2]

Once this is done, AVRDUDE will see the source Arduino as **AVR ISP** and you can flash the firmware on the target Arduino.

You can also use [this post][3] for guidance as well.

  [1]: https://www.arduino.cc/en/Tutorial/ArduinoISP
  [2]: https://i.stack.imgur.com/j6Wh1.png
  [3]: http://blog.bhargavaz.us/2011/08/programming-arduino-bootloader-on-mega8.html

body:
After many hours of unsuccessful bootloader reprogramming attempts, I was able to revive the Pro Micro by trying different timing of double tapping RST while the IDE was compiling/uploading a sketch. After several attempts the Pro Micro suddenly took a sketch and seems to be working now. Not sure how long it will stay this way or how often I will loose it and have to go through these shenanigans again.

Thanks to all for the help.


body:
I'm using Arduino: 1.6.7 (Mac OS X 10.11.3), Board: "Arduino Leonardo".

When I try to program my code, it works without problems.
When I want to open the built-in Serial Monitor or Serial Plotter, it says "Board at /dev/cu.usbmodem1421 is not available".

The board is available and my simple code even works using "SerialTools" from Mac App Store. So there must be some problem with the Arduino IDE.

No serial related messages on dmesg. Comically it mounts and umounts my Boot OS X and Recovery HD partitions every time I unplug the Leonardo.

    hfs: mounted Recovery HD on device disk0s3
    hfs: unmount initiated on Recovery HD on device disk0s3 hfs: mounted
    Boot OS X on device disk2s3 ioqueue_depth = 64,   ioscale = 2 hfs:
    unmount initiated on Boot OS X on device disk2s3

Any ideas?
<!-- language-all: lang-cpp -->

    int inByte = 0;         // incoming serial byte

    void setup() {

        // start serial port at 9600 bps:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
      }

    }

    void loop() {

      if (Serial.available() > 0) {
        inByte = Serial.read();
        Serial.println("Hi");
      }

    }

title: Arduino IDE programs Leonardo but cannot open serial terminal

Answers: 0


body:
I have been trying to grasp a better understand of registers and port manipulation. I have been looking through the ATmega 328P datasheet to look at the different registers.

For some of the registers, I see that there are two addresses listed. For example, for PORTB is listed at 0x05 (0x25). Similarly, for its DDRB and PINB, they are listed at 0x04 (0x24), and 0x03 (0x23), respectively. What does this mean for the register? Thank you.

title: What does it mean when there are two addresses listed in the data sheet for a particular register?

Answers: 1

body:
One (the lower number) is the IO port address which is used when using the IN or OUT op-code. The other (higher number) is the memory mapped address.

Different methods of access are more programatically efficient depending on how you are manipulating the values. For instance IN and OUT are more efficient at setting or reading the entire register value, but SBI and CBI on the memory mapped address are more efficient when manipulating individual bits.


body:
Hello  I have an Arduino programme where a string is loaded from an SD card. That all works fine. I want to see if the string that has been loaded contains a certain phrase. I am using substring but it doesn't seem to be working. What am I doing wrong? Here's my code:

    file = SD.open("/classes/basic.txt", FILE_READ);
     Serial.print("Reading, Checking and Compiling \n");
      while(file.available()) {
       character23 = file.read();
       content.concat(character23);
      }
    if (content != "") {
      l1 = content;
      Serial.println(l1 + "\n");
    }

    if(l1.substring(0) == "print"){
      printlnMethod();
    }
    file.close();

it all works until it gets to l1.substring and that doesn't work because the method inside doesn't run. The string that gets loaded into the Arduino from the SD card is : println("hello world");

What am I doing wrong?

title: Arduino substring not working

Answers: 1

body:
Substring takes either one or two arguments.

In the single-argument version that you are using the argument specifies the *start* of the substring. The substring then contines to the end of the string.  So, since you are asking it to start at index 0 the returned value is the entire string - from 0 to the end.

Instead you probably want to use the two-argument version. In that version you provide two numbers - the index in the string to start from, and the index in the string after the last character you want.  So if the string starts with "print" you then want to use `l1.substring(0, 5)` to get the characters 0 to 4 inclusive.


body:
I can't appear to get my MKR1000 to list a port on my mac in the arduino ide, am i missing something obvious or does it need additional drivers?

Also
➜  ~  csrutil status
System Integrity Protection status: disabled.

running OSX 10.11.3

Board appears to be working, default led flashing

title: MKR1000 not showing up on OSX

Answers: 2

body:
See if this answers your question:
https://www.hackster.io/charifmahmoudi/arduino-mkr1000-getting-strarted-08bb4a

If not, go to your Board Manager (this happened to me too) and search MKR1000. There should be another install to do. Install that one and you should be good.

body: Double click the reset button on the board. Then it will show in the Port list :-)


body:
I have been wanting to create a Arduino watch. I built the circuit with an Adafruit Trinket 3v and an Adafruit LED matrix backpack (8*8). When I try to upload this example code:

    /***************************************************
      This is a library for our I2C LED Backpacks

      Designed specifically to work with the Adafruit LED Matrix backpacks
      ----> http://www.adafruit.com/products/872
      ----> http://www.adafruit.com/products/871
      ----> http://www.adafruit.com/products/870

      These displays use I2C to communicate, 2 pins are required to
      interface. There are multiple selectable I2C addresses. For backpacks
      with 2 Address Select pins: 0x70, 0x71, 0x72 or 0x73. For backpacks
      with 3 Address Select pins: 0x70 thru 0x77

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

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

    #include <Wire.h>
    #include "Adafruit_LEDBackpack.h"
    #include "Adafruit_GFX.h"

    Adafruit_8x8matrix matrix = Adafruit_8x8matrix();

    void setup() {
      // Serial.begin(9600);
      // Serial.println("8x8 LED Matrix Test");

      matrix.begin(0x70);  // pass in the address
    }

    static const uint8_t PROGMEM
      smile_bmp[] =
      { B00111100,
        B01000010,
        B10100101,
        B10000001,
        B10100101,
        B10011001,
        B01000010,
        B00111100 },
      neutral_bmp[] =
      { B00111100,
        B01000010,
        B10100101,
        B10000001,
        B10111101,
        B10000001,
        B01000010,
        B00111100 },
      frown_bmp[] =
      { B00111100,
        B01000010,
        B10100101,
        B10000001,
        B10011001,
        B10100101,
        B01000010,
        B00111100 };

    void loop() {
      matrix.clear();
      matrix.drawBitmap(0, 0, smile_bmp, 8, 8, LED_ON);
      matrix.writeDisplay();
      delay(500);

      matrix.clear();
      matrix.drawBitmap(0, 0, neutral_bmp, 8, 8, LED_ON);
      matrix.writeDisplay();
      delay(500);

      matrix.clear();
      matrix.drawBitmap(0, 0, frown_bmp, 8, 8, LED_ON);
      matrix.writeDisplay();
      delay(500);

      matrix.clear();      // clear display
      matrix.drawPixel(0, 0, LED_ON);
      matrix.writeDisplay();  // write the changes we just made to the display
      delay(500);

      matrix.clear();
      matrix.drawLine(0,0, 7,7, LED_ON);
      matrix.writeDisplay();  // write the changes we just made to the display
      delay(500);

      matrix.clear();
      matrix.drawRect(0,0, 8,8, LED_ON);
      matrix.fillRect(2,2, 4,4, LED_ON);
      matrix.writeDisplay();  // write the changes we just made to the display
      delay(500);

      matrix.clear();
      matrix.drawCircle(3,3, 3, LED_ON);
      matrix.writeDisplay();  // write the changes we just made to the display
      delay(500);

      matrix.setTextSize(1);
      matrix.setTextWrap(false);  // we dont want text to wrap so it scrolls nicely
      matrix.setTextColor(LED_ON);
      for (int8_t x=0; x>=-36; x--) {
        matrix.clear();
        matrix.setCursor(x,0);
        matrix.print("Hello");
        matrix.writeDisplay();
        delay(100);
      }
      matrix.setRotation(3);
      for (int8_t x=7; x>=-36; x--) {
        matrix.clear();
        matrix.setCursor(x,0);
        matrix.print("World");
        matrix.writeDisplay();
        delay(100);
      }
      matrix.setRotation(0);
    }

I get this error:

    Build options changed, rebuilding all
    In file included from matrix8x8.ino:23:0:
    C:\Users\My_Username\Documents\Arduino\libraries\Adafruit_LEDBackpack/Adafruit_LEDBackpack.h:30:24: fatal error: TinyWireM.h: No such file or directory
      #include <TinyWireM.h>
                            ^
    compilation terminated.
    Error compiling.

I have installed TinyWireM, Adafruit_GFX, and Adafruit_LEDBackpack. Why would I get this error?
[![My Circuit][1]][1]

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

title: Adafruit Trinket 3v with LED matrix backpack producing error

Answers: 0