message:
Having trouble passing data through RF24

I have three RF24, all of them are connected to one arduino-uno each. The first one has sensors that sends data to the second one then the second one passes it to the third one. The first pass from RF24 #1 to RF24 #2 is successful but from the RF24 #2 to RF24 #3 there seems to be a problem.

Code for the RF24 #1 (I just copied the setup and loop the other functions are for the sensors, I think it's unnecessary):

    //Libraries for temperature
    #include <OneWire.h>
    #include <DallasTemperature.h>
    #define motor1 8
    // Data wire is plugged into port 2 on the Arduino
    #define ONE_WIRE_BUS 2
    #include <SPI.h>
    #include <nRF24L01.h>
    #include <RF24.h>
    // Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
    OneWire oneWire(ONE_WIRE_BUS);

    // Pass our oneWire reference to Dallas Temperature.
    DallasTemperature sensors(&oneWire);

    //for pH meter
    #define SensorPin A0            //pH meter Analog output to Arduino Analog Input 0
    #define Offset 0.00            //deviation compensate
    #define LED 13
    #define samplingInterval 20
    #define printInterval 800
    #define ArrayLenth  40    //times of collection
    int pHArray[ArrayLenth];   //Store the average value of the sensor feedback
    int pHArrayIndex = 0;

    //for NRF24L01
    RF24 radio(7, 8); // CE, CSN
    const uint64_t waddress = 0xB00B1E50D2LL;
    struct package {
      float temperature, ph, Do, inch, cm1;
    };
    typedef struct package Package;
    Package data;
    int LID = 4, LOD = 6;

    //for ultrasonic
    const int trigPin = 3;
    const int echoPin = 4;
    long duration, inches, cm, meter;

    void setup(void)
    {
      // start serial port
      radio.begin();
      radio.openWritingPipe(waddress);
      radio.setPALevel(RF24_PA_MIN);
      radio.stopListening();

      pinMode(LED, OUTPUT);
      // Start up the library
      sensors.begin();
    }

    /*
       Main function, get and show the temperature
    */

    void loop(void)
    {
      static unsigned long samplingTime = millis();
      static unsigned long printTime = millis();
      static float pHValue, voltage;
      if (millis() - samplingTime > samplingInterval)
      {
        pHArray[pHArrayIndex++] = analogRead(SensorPin);
        if (pHArrayIndex == ArrayLenth)pHArrayIndex = 0;
        voltage = avergearray(pHArray, ArrayLenth) * 5.0 / 1024;
        pHValue = 3.5 * voltage + Offset;
        samplingTime = millis();
      }
      if (millis() - printTime > printInterval)  //Every 800 milliseconds, print a numerical, convert the state of the LED indicator
      {
        digitalWrite(LED, digitalRead(LED) ^ 1);
        // call sensors.requestTemperatures() to issue a global temperature
        // request to all devices on the bus

        sensors.requestTemperatures(); // Send the command to get temperatures

        // After we got the temperatures, we can print them here.
        // We use the function ByIndex, and as an example get the temperature from the first sensor only.

        //Serial.print(pHValue,2);
        //Serial.print(",");
        //Serial.print(sensors.getTempCByIndex(0));

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

        data.ph = (pHValue);
        data.temperature = (sensors.getTempCByIndex(0));
        Serial.print(data.ph);
        Serial.print(data.temperature);
        Serial.print(data.Do);
      }
    }

RF24 #2

    #include <SPI.h>
    #include <nRF24L01.h>
    #include <RF24.h>
    RF24 radio(7, 8); // CE, CSN
    const uint64_t raddress = 0xB00B1E50D2LL;
    const uint64_t waddress = 0xB00B1E50B1LL;
    struct package {
      float temperature, ph, Do, inch, cm1;
    };
    typedef struct package Package;
    Package data;

    void setup() {
      Serial.begin(9600);
      radio.begin();
      radio.openWritingPipe(waddress);
      radio.openReadingPipe(1, raddress);
      radio.setPALevel(RF24_PA_MIN);
    }

    void loop() {
      radio.startListening();

      while (radio.available()) {
        radio.read(&data, sizeof(data));
        Serial.print(data.ph);
        Serial.print(",");
        Serial.print(data.temperature);
        Serial.print(",");
        Serial.print(data.Do);
        Serial.print(",");
        Serial.print(data.inch);
        Serial.print(",");
        Serial.println(data.cm1);
      }
      if (radio.write(&data, sizeof(data))) {
        Serial.println(" delivery failed");
      }
      radio.stopListening();
      delay(200);
    }

RF24 #3

    #include <SPI.h>
    #include <nRF24L01.h>
    #include <RF24.h>
    int lid = 2 , lod = 4;
    RF24 radio(7, 8); // CE, CSN
    const uint64_t raddress = 0xB00B1E50B1LL;
    struct package {
      float temperature, ph, Do, inch, cm1;
    };
    typedef struct package Package;
    Package data;

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

      radio.begin();
      radio.openReadingPipe(2, raddress);
      radio.setPALevel(RF24_PA_MIN);
      radio.startListening();
      pinMode(lid, OUTPUT);
      pinMode(lod, OUTPUT);
    }

    void loop() {
      unsigned long startTimer = millis();
      bool timeout = false;

      while (!radio.available() && !timeout) {
        if (millis() - startTimer > 500 )
        {
          timeout = true;
        }
        // radio.read(&temperature, sizeof(temperature));
        //radio.read(&Do, sizeof(Do));
      }
      if (timeout) {
        Serial.println("Failed to receive data");
      }
      else {
        radio.read(&data, sizeof(data));

        Serial.print(data.ph);
        Serial.print(",");
        Serial.print(data.temperature);
        Serial.print(",");
        Serial.print(data.Do);
        Serial.print(",");
        Serial.print(data.inch);
        Serial.print(",");
        Serial.println(data.cm1);
      }
    }

The serial monitor for RF24 #2 displays:

     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
    6.92,28.25,7.20,15.00,38.00
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
    6.91,28.25,7.20,15.00,38.00

RF24 #3 Serial Monitor:

    0.00,0.00,0.00,0.00,0.00
    0.00,0.00,0.00,0.00,0.00
    0.00,0.00,0.00,0.00,0.00
    0.00,0.00,0.00,0.00,0.00
    0.00,0.00,0.00,0.00,0.00
    0.00,0.00,0.00,0.00,0.00
    0.00,0.00,0.00,0.00,0.00
    0.00,0.00,0.00,0.00,0.00
    0.00,0.00,0.00,0.00,0.00

Sometimes RF24 #3 receives the data and prints it continuously. I don't know why. Most of the time it displays the above.

Edit: Revision

Update: It turns out that RF24 #3 continuous to print even if RF24 #2 is unplugged/not powered.

body:
You should always call `stopListening()` right before you `write()`. Also `write()` returns true when messages are delivered so your condition is wrong. Try changing the `loop()` in the second node to:

    void loop() {
      while (radio.available()) {
        radio.read(&data, sizeof(data));
        Serial.print(data.ph);
        Serial.print(",");
        Serial.print(data.temperature);
        Serial.print(",");
        Serial.print(data.Do);
        Serial.print(",");
        Serial.print(data.inch);
        Serial.print(",");
        Serial.println(data.cm1);

        radio.stopListening();
        if (!radio.write(&data, sizeof(data))) {
          Serial.println("Delivery failed");
        }
        radio.startListening();
      }
    }

If a packet is available, it's read, printed and forwarded.
The third node's `loop()` should also be adjusted to something like:

    bool new_data = false;

    void loop() {
      if (radio.available()) {
        radio.read(&data, sizeof(data));

        Serial.print(data.ph);
        Serial.print(",");
        Serial.print(data.temperature);
        Serial.print(",");
        Serial.print(data.Do);
        Serial.print(",");
        Serial.print(data.inch);
        Serial.print(",");
        Serial.println(data.cm1);
        new_data = true;
      }
      if (new_data) {
        // do stuff
        new_data = false;
      }
    }

Data is sent in 32-byte payloads and your entire package is 20 bytes (without padding), assuming a float = 4 bytes. So a complete packet has either arrived or it hasn't; no point in waiting in one place. `new_data` lets you know when there's new stuff obviously and you clear the flag when you're done processing the data. This way, you can do other stuff while you wait for a packet to show.


sender: user

message:
How to properly construct objects on ATmega2056?

I was wondering the correct method to construct objects for use in the setup and loop scopes. I tried working constructing in the global scope, but I get garbage values printed to serial (probably from misusing pointers)? If I use the new keyword, then it works, but I heard that that is not best practice.

I is there a better way I should do this?

    // navigator.cpp

    #include "navigator.h"

    Navigator::begin(Waypoint* w, int count) {
      waypoints = w;
      pointCount = count;
      next = 0;          // start with first waypoint
      course = 90;       // Notice that initial course is due East

      Serial.println('here');
    }

-

    // navigator.h

    #define _navigator_h

    #if defined(ARDUINO) && ARDUINO >= 100
      #include "Arduino.h"
    #else
      #include "WProgram.h"
    #endif

    struct Waypoint {
      double lat, lon;
    };

    class Navigator {
    public:
      begin(Waypoint* w, int);
    };

    #endif

-

    // TransAt.ino

    #include "navigator.h"

    Waypoint w = { 43.36, -75.1 }; // These objects must be accessible in both setup() and loop(), but we can't use the new keyword
    Navigator nav();     // That means we have to do a lot of the heavy lifting here

    uint32_t timer = millis();

    void setup() {
      nav.begin(&w, 1);
    }

    void loop()
    {

    }

sender: assistant

body:
>  I tried working constructing in the global scope, but I get garbage values printed to serial ...

Constructors in global scope are called before `init` and `setup` and thus are probably executing too soon for you. This would account for the garbage printed to serial, because your constructor is printing before the `Serial.begin()` call.

You can put constructors in global scope, however they should do fairly trivial things (eg. setting a counter to zero, or a pointer to NULL). Do not rely upon the system being initialized, thus do not call functions like `millis`, nor should you be using dynamic memory allocation at this point.

Most classes defer their "real" initialization to a `begin` function (eg. `Serial.begin`) because it is safe to do that, usually in the `setup` function.


message:
Buffer reverse to string

A few hours since I started messing with my first Arduino and I was trying to understand a small program and need some help. The program sends out the MAC address to the serial port. As it's little endian, the "printBufferReverse" reverses the buffer as shown below. But instead of sending this data to the serial port, how do I store the same data into a string variable? Thanks so much

    #include <bluefruit.h>
    void scan_callback(ble_gap_evt_adv_report_t* report)
    {
      uint8_t len = 0;
      uint8_t buffer[32];
      memset(buffer, 0, sizeof(buffer));

      // MAC is in little endian --> print reverse
      // NOTE: I want to store this into a string variable
      // NOTE: the reversing
      Serial.printBufferReverse(report->peer_addr.addr, 6, ':');
      Serial.print("\n");

      /* TX Power Level */
      if (Bluefruit.Scanner.parseReportByType(report,
        BLE_GAP_AD_TYPE_TX_POWER_LEVEL, buffer, sizeof(buffer)))
        {
          Serial.printf("s %i\n", "TX PWR LEVEL", buffer[0]);
          memset(buffer, 0, sizeof(buffer));
        }
    }

And the below line how do I store the data to a string instead of sending to serial port? It's adding a hypen to make the end result look like this:12-09-69-57-45-45-43-41-52-45-20

    Serial.printBuffer(report->data, report->dlen, '-');

I don't want to send this to serial port but to store in a string variable.

This is the board that I am using: https://www.adafruit.com/product/3406

## Complete code ##

    /*********************************************************************
     This is an example for our nRF52 based Bluefruit LE modules

     Pick one up today in the adafruit shop!

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

     MIT license, check LICENSE for more information
     All text above, and the splash screen below must be included in
     any redistribution
    *********************************************************************/

    #include <bluefruit.h>

    /* For a list of EIR data types see:
     *    https://www.bluetooth.com/specifications/assigned-numbers/generic-access-profile
     *    Matching enum: cores/nRF5/SDK/components/softdevice/s132/headers/ble_gap.h */

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

      Serial.println("Scanning for beacons");
      Serial.println("------------------------------------\n");

      // Initialize Bluefruit with maximum connections as Peripheral = 0, Central = 1
      // SRAM usage required by SoftDevice will increase dramatically with number of connections
      Bluefruit.begin(0, 1);

      // Set max power. Accepted values are: -40, -30, -20, -16, -12, -8, -4, 0, 4
      Bluefruit.setTxPower(4);

      /* Set the device name */
      Bluefruit.setName("Bluefruit52");

      /* Set the LED interval for blinky pattern on BLUE LED */
      Bluefruit.setConnLedInterval(250);

      /* Start Central Scanning
       * - Enable auto scan if disconnected
       * - Filter out packet with a min rssi
       * - Interval = 100 ms, window = 50 ms
       * - Use active scan (used to retrieve the optional scan response adv packet)
       * - Start(0) = will scan forever since no timeout is given
       */
      Bluefruit.Scanner.setRxCallback(scan_callback);
      Bluefruit.Scanner.restartOnDisconnect(true);
      Bluefruit.Scanner.filterRssi(-80);
      //Bluefruit.Scanner.filterUuid(BLEUART_UUID_SERVICE); // only invoke callback if detect bleuart service
      Bluefruit.Scanner.setInterval(160, 80);       // in units of 0.625 ms
      Bluefruit.Scanner.useActiveScan(true);        // Request scan response data
      Bluefruit.Scanner.start(0);                   // 0 = Don't stop scanning after n seconds

      Serial.println("Started ...");
    }

    void scan_callback(ble_gap_evt_adv_report_t* report)
    {
      uint8_t len = 0;
      uint8_t buffer[32];
      memset(buffer, 0, sizeof(buffer));
      boolean hasPayload;
      String bleDvcID;
      String advPayload;

      hasPayload = false;
      bleDvcID = "";
      advPayload = "";

      /* Display the timestamp and device address */
      /*
      if (report->scan_rsp)
      {
        Serial.printf("[SRd] Packet received from ", millis());
      }
      else
      {
        Serial.printf("[ADV�] Packet received from ", millis());
      }
      */
      // MAC is in little endian --> print reverse
      // bleDvcID = printBufferReverse(report->peer_addr.addr, 6, ':');
      // char buffer[18] = "";
      /*
        snprintf(buffer, "X-X-X-X-X-X", 18,
            report->peer_addr.addr[5],
            report->peer_addr.addr[4],
            report->peer_addr.addr[3],
            report->peer_addr.addr[2],
            report->peer_addr.addr[1],
            report->peer_addr.addr[0]
        );
       */
      Serial.printBufferReverse(report->peer_addr.addr, 6, ':');
      Serial.print("\n");

      /* Raw buffer contents */
      Serial.printf("s %d bytes\n", "PAYLOAD", report->dlen);
      if (report->dlen)
      {
        hasPayload = true;
        Serial.printf("s", " ");
        Serial.printBuffer(report->data, report->dlen, '-');
        Serial.println();
      }

      /* RSSI value */
      Serial.printf("s %d dBm\n", "RSSI", report->rssi);

      /* Complete Local Name */
      if(Bluefruit.Scanner.parseReportByType(report, BLE_GAP_AD_TYPE_COMPLETE_LOCAL_NAME, buffer, sizeof(buffer)))
      {
        Serial.printf("s %s\n", "COMPLETE NAME", buffer);
        if (strcmp((const char*)buffer, "Temperature Fren")==0)
        {
            Serial.println("Found beacon!");
        }
        memset(buffer, 0, sizeof(buffer));
      }

      /* TX Power Level */
      if (Bluefruit.Scanner.parseReportByType(report, BLE_GAP_AD_TYPE_TX_POWER_LEVEL, buffer, sizeof(buffer)))
      {
        Serial.printf("s %i\n", "TX PWR LEVEL", buffer[0]);
        memset(buffer, 0, sizeof(buffer));
      }

      /* Check for UUID16 Complete List */
      len = Bluefruit.Scanner.parseReportByType(report, BLE_GAP_AD_TYPE_16BIT_SERVICE_UUID_COMPLETE, buffer, sizeof(buffer));
      if ( len )
      {
        printUuid16List(buffer, len);
      }

      /* Check for UUID16 More Available List */
      len = Bluefruit.Scanner.parseReportByType(report, BLE_GAP_AD_TYPE_16BIT_SERVICE_UUID_MORE_AVAILABLE, buffer, sizeof(buffer));
      if ( len )
      {
        printUuid16List(buffer, len);
      }

      /* Check for UUID128 Complete List */
      len = Bluefruit.Scanner.parseReportByType(report, BLE_GAP_AD_TYPE_128BIT_SERVICE_UUID_COMPLETE, buffer, sizeof(buffer));
      if ( len )
      {
        printUuid128List(buffer, len);
      }

      /* Check for UUID128 More Available List */
      len = Bluefruit.Scanner.parseReportByType(report, BLE_GAP_AD_TYPE_128BIT_SERVICE_UUID_MORE_AVAILABLE, buffer, sizeof(buffer));
      if ( len )
      {
        printUuid128List(buffer, len);
      }

      /* Check for BLE UART UUID */
      /*
      if ( Bluefruit.Scanner.checkReportForUuid(report, BLEUART_UUID_SERVICE) )
      {
        Serial.printf("s %s\n", "BLE UART", "UUID Found!");
      }
      */
      /* Check for DIS UUID */
      /*
      if ( Bluefruit.Scanner.checkReportForUuid(report, UUID16_SVC_DEVICE_INFORMATION) )
      {
        Serial.printf("s %s\n", "DIS", "UUID Found!");
      }
      */
      /* Check for Manufacturer Specific Data */
      /*
      len = Bluefruit.Scanner.parseReportByType(report, BLE_GAP_AD_TYPE_MANUFACTURER_SPECIFIC_DATA, buffer, sizeof(buffer));
      if (len)
      {
        Serial.printf("s ", "MAN SPEC DATA");
        Serial.printBuffer(buffer, len, '-');
        Serial.println();
        memset(buffer, 0, sizeof(buffer));
      }
      */
      Serial.println();
    }

    void printUuid16List(uint8_t* buffer, uint8_t len)
    {
      /* Serial.printf("s %s", "16-Bit UUID"); */
      for(int i=0; i<len; i+=2)
      {
        uint16_t uuid16;
        memcpy(&uuid16, buffer+i, 2);
        /* Serial.printf("X ", uuid16); */
      }
      /* Serial.println(); */
    }

    void printUuid128List(uint8_t* buffer, uint8_t len)
    {
      (void) len;
      /* Serial.printf("s %s", "128-Bit UUID"); */

      // Print reversed order
      for(int i=0; i<16; i++)
      {
        const char* fm = (i==4 || i==6 || i==8 || i==10) ? "-X" : "X";
        /* Serial.printf(fm, buffer[15-i]); */
      }

      /* Serial.println(); */
    }

    void loop()
    {
      // Toggle both LEDs every 1 second
      digitalToggle(LED_RED);

      delay(1000);
    }

body:
You can do it with snprintf_P:

    char mac[18];

    snprintf_P(mac, 18, (PGM_P)F("X-X-X-X-X-X"),
        report->peer_addr.addr[5],
        report->peer_addr.addr[4],
        report->peer_addr.addr[3],
        report->peer_addr.addr[2],
        report->peer_addr.addr[1],
        report->peer_addr.addr[0]
    );

That is, assuming that `report->peer_addr.addr` is an array of 6 bytes.

If your strange board doesn't support the `_P` variants of string manipulation functions then you can drop that part along with the `(PGM_P)F(...)` bit:

    char mac[18];

    snprintf(mac, 18, "X-X-X-X-X-X",
        report->peer_addr.addr[5],
        report->peer_addr.addr[4],
        report->peer_addr.addr[3],
        report->peer_addr.addr[2],
        report->peer_addr.addr[1],
        report->peer_addr.addr[0]
    );

Doing so on an Ardunio, though, would waste RAM.


message:
Reading Arduino Serial Input

I am reading an input from my Ohaus weighing scale using it's RS232 output using this code:

<!-- language: lang-cpp -->

    #define HWSERIAL Serial1

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

    void loop() {
      int incomingByte;

      if (Serial.available() > 0) {
        incomingByte = Serial.read();
        Serial.print("USB received: ");
        Serial.println(incomingByte, DEC);
        //HWSERIAL.print("USB received:");
        //HWSERIAL.println(incomingByte, DEC);
      }
      if (HWSERIAL.available() > 0) {
        incomingByte = HWSERIAL.read();
        Serial.print("UART received: ");
        Serial.println(incomingByte);
        //HWSERIAL.print("UART received:");
        //HWSERIAL.println(incomingByte);
      }
    }

When pressing the print button on the scale, I was expecting data to come over in single burst with just the readings, but what I am getting is the expected data, but the scale keeps sending data afterwards (ES over and over). I need to parse out just what's needed. The below is the output from the console on my computer.

    UART received:
    UART received:
    UART received:
    UART received:
    UART received: 0
    UART received: .
    UART received: 0
    UART received: 0
    UART received:
    UART received:
    UART received:
    UART received:
    UART received:
    UART received:
    UART received: ?
    UART received: (This is a CR)

    UART received: (This is a LF)

    UART received:
    UART received:
    UART received:
    UART received:
    UART received: 0
    UART received: .
    UART received: 4
    UART received: 0
    UART received:
    UART received:
    UART received:
    UART received:
    UART received:
    UART received:
    UART received: ?
    UART received: G
    UART received:
    UART received:
    UART received: (CR)

    UART received: (LF)

    UART received: E
    UART received: S
    UART received: (CR)

    UART received: (LF)
    ... (The ES loops over and over until the print button is pressed again)

0.00 is the current scale reading and 0.40 is the tare weight. That's all I need and I can't figure out how to parse it. The blocks aren't the same length so how do I pull out the needed information and ignore the repetitive 'ES'? I'm not 100% sure if I'm even going about this the right way?

Output as DEC

    UART received: 32
    UART received: 32
    UART received: 32
    UART received: 32
    UART received: 48
    UART received: 46
    UART received: 48
    UART received: 48
    UART received: 32
    UART received: 32
    UART received: 32
    UART received: 32
    UART received: 32
    UART received: 32
    UART received: 63
    UART received: 13
    UART received: 10
    UART received: 32
    UART received: 32
    UART received: 32
    UART received: 32
    UART received: 48
    UART received: 46
    UART received: 52
    UART received: 48
    UART received: 32
    UART received: 32
    UART received: 32
    UART received: 32
    UART received: 32
    UART received: 32
    UART received: 63
    UART received: 71
    UART received: 32
    UART received: 32
    UART received: 13
    UART received: 10
    UART received: 69
    UART received: 83
    UART received: 13
    UART received: 10
    UART received: 69
    UART received: 83
    ...

body:
From the manual:
http://dmx.ohaus.com/WorkArea/showcontent.aspx?id=4294974226

> The balance will return “ES” for invalid commands.

Check to make sure you're using the correct serial parameters that the RX line is wired correctly.


message:
Light Powered Motor Troubles

I'm working on a small car (<1 kg) which will drive when there is light and stop when there isn't. Below is a plan with code drawn up (the only numbers I know for sure are the current gains for the TIP31C transistor and the rated load current of the 6 V motor I'm using). I'm going to map the analog voltages to a digital signal output.

I read that the maximum digital output was 40 mA and also that `analogWrite` gives a pulse width modulation (PWM) which can be set to 100% (255) [the code: `outputval/1`], 50% (127) [the code: `outputval/2`]. I'm concerned with the lack of control I have here over the current. Will Arduino by default draw 7.75 mA maximum if the input signal is high [giving the output signal also as high]? If not, can I control the current in this manner reliably? Also are there anything I should worry about if I added another 6 V motor in parallel? Coding and electrical suggestions greatly welcomed.

TIP31 transistor: http://www.hobbytronics.co.uk/datasheets/TIP31.pdf

6 V dc motor: http://www.kysanelectronics.com/graphics/RF-370CA-22170.pdf

maximum digital output: https://www.arduino.cc/en/Tutorial/DigitalPins

PWM: https://www.arduino.cc/en/Tutorial/PWM

[![the plan][1]][1]

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

The code:

    const int transistorbase = 9;
    void setup() {
      //set the base as digital output:
      pinMode(transistorbase, OUTPUT);
    }
    void loop() {
      //read voltage at divider:
      int inputval=analogRead(A0);
      //map voltage to digital
      int outputval=map(inputval,0,1023,0,255);
      //control transistor:
      analogWrite(transistorbase,outputval);
    }

tl;dr
Codewise, how do I control the digital output current to my needs? Am I seeing ghosts?

body:
I would take a simple n-channel MOSFET like [this one][1]. At 5V on the gate it can drive up to 8A (so you have plenty of space to connect other motors as long as your power source can handle this) and because it is a MOSFET you don't have to draw much current from the Arduino (only enough to load the gate of the MOSFET). You can also hold the current under the critical value for your motor with a simple resistor (fit for the resulting power dissipation) in series.

Yes, the output of the PWM is 5V - the operation voltage of the Arduino. The whole point in PWM is to use only the digital values (here 0V and 5V) and varying so fast, that slow systems as the motor cannot follow this motion, but summing over the impulses. So the motor gets only very fast kicks. And for a normal motor you don't need fast PWM. This only increases the frequency response from the MOSFET.

The code seems for to me.

  [1]: https://www.mouser.com/ds/2/308/BUZ11-1118746.pdf


message:
Why the program keeps applying what is in loop in first case and stops in the second one?

In the first program after removing hand from the button it keeps on, means it keeps applying what is in the loop:

<!-- language-all: lang-cpp -->

    int led = 13;
    int button = 12;
    void setup() {
      pinMode(led, OUTPUT);
      pinMode(button, INPUT);
                 }
    void loop() {
      if (digitalRead(button) == HIGH)
      {
        digitalWrite(led, HIGH);
      }
                 }

while in the second one it needs to press the button every time in order to apply what is in the loop,means to flash in this case,

    int led = 13;
    int button = 12;
    void setup() {
      pinMode(led, OUTPUT);
      pinMode(button, INPUT);
                }
    void loop() {
      if (digitalRead(button) == HIGH)
      {
        digitalWrite(led, HIGH);
        delay(1000);
        digitalWrite(led, LOW);
        delay(1000);
      }
               }

Why different behavior although the same structure?

The problem is illustrated in this video :
https://www.youtube.com/watch?v=u5WGvKwJYFY&t=2s

body:
You read `value` only once ... what do you expected?

In the first sketch, you put the LED ON and never turn it OFF, no matter what.

In the second sketch, you put the LED ON and one second later you turned it OFF. As the `value` doesn't change, it keeps repeating.

You mistake: you read the button in `setup`. You have to read in each `loop` iteration.

    void loop() {
      value = digitalRead(button);
      if (value == HIGH)
      {
        digitalWrite(led, HIGH);
        delay(1000);
        digitalWrite(led, LOW);
        delay(1000);
      }


body:
This iteration of your code is better.  Now, the difference in behavior is that nothing in the first code ever executes `digitalWrite(led, LOW);`, while each iteration though the second code does.  Therefore the LED remains on forever in code 1, and depends on the button press in code two.

If the behavior you desire is that the code remembers if the button has ever been pressed, latch that event in some state variable, and then in `loop()`, act on the value of the state variable:

    int led = 13;
    int button = 12;
    int everHit = 0;
    void setup() {
      pinMode(led, OUTPUT);
      pinMode(button, INPUT);
    }

    void loop() {
      if (digitalRead(button) == HIGH) everHit = 1;
      if (everHit) {
        digitalWrite(led, HIGH);
        delay(1000);
        digitalWrite(led, LOW);
        delay(1000);
      }
    }


message:
EDB. Is it possible to create multiple tables with db.create()?

Good day! I seem to be having trouble creating multiple tables with EDB. I am using Arduino UNO and SD Card module to save my db.

Here is my Serial.

[![Here is my serial][1]][1]
[1]: https://i.stack.imgur.com/ip89i.png

Here is my table declaration.

    struct LogEvent {
      int id;
      String fname;
      float temperature;
    }
    logEvent;

    struct SecondEvent {
      int id;
      String lastname;
    }
    secondEvent;

Here is my db.create() code.

    db.create(0, TABLE_SIZE, (unsigned int)sizeof(logEvent));
    db.create(0, TABLE_SIZE, (unsigned int)sizeof(secondEvent));

Now, when I try to retrieve, it is a whack. Here is my save and retrieve code.

    void createRecords(int num_recs, float correctTemperature)
    {
        Serial.print("Creating Records... ");
        for (int recno = 1; recno <= num_recs; recno++)
        {
          correctId++;
          logEvent.id = correctId;
          logEvent.fname = "Brix Nicholson";
          logEvent.temperature = correctTemperature;
          secondEvent.id = correctId;
          EDB_Status result = db.appendRec(EDB_REC logEvent);
          if (result != EDB_OK) printError(result);
        }
      Serial.println("DONE");
    }

    void createRecordSecondEvent()
     {
       correctId++;
       secondEvent.id = correctId;
       secondEvent.lastname = "Secretaria";
       EDB_Status result = db.appendRec(EDB_REC secondEvent);
       if (result != EDB_OK) printError(result);
     }

    void selectLastRecord()
    {
      int lastRecNum = db.count();
      EDB_Status result = db.readRec(lastRecNum, EDB_REC logEvent);
      if(result == EDB_OK)
       {
         Serial.print(" ID: ");
         Serial.print(logEvent.id);
         Serial.print(" Name: ");
         Serial.print(logEvent.fname);
         Serial.print(" Temp: ");
         Serial.println(logEvent.temperature);
       }
       else printError(result);
    }

    void selectLastSecondRecord()
    {
     int lastRecNum = db.count();
     EDB_Status result = db.readRec(lastRecNum, EDB_REC secondEvent);
     if(result == EDB_OK)
      {
       Serial.print("Second Event ID: ");
       Serial.print(secondEvent.id);
       Serial.print("Last Name: ");
       Serial.print(secondEvent.lastname);
      }
      else printError(result);
    }

body:
I think I have found the answer to my problem. I forgot to increase the address of the EDB_header.

I wrote:

    db.create(0, TABLE_SIZE, (unsigned int)sizeof(logEvent));
    db.create(0, TABLE_SIZE, (unsigned int)sizeof(secondEvent));

Instead of:

    db.create(0, TABLE_SIZE, (unsigned int)sizeof(logEvent));
    db.create(1, TABLE_SIZE, (unsigned int)sizeof(secondEvent));


body:
> I think I have found the answer to my problem. I forgot to increase
> the address of the EDB_header.

you're right about increasing the address of EDB_header.
But the address is the position from where the library starting reading/writing.

if you have a look at
https://github.com/jwhiddon/EDB/blob/master/EDB.cpp#L66
and
https://github.com/jwhiddon/EDB/blob/master/EDB.cpp#L34

the library writes a fixed size of the header in the binary format
which includes

 1. a magic byte to recognize the EDB header
 2. the number of records currently present in the table which is 0 at of this time
 3. size of your single record
 4. the size of the table (max amount of memory that the table is allowed to consume)

and to write a new record
https://github.com/jwhiddon/EDB/blob/master/EDB.cpp#L93

so in

    db.create(0, TABLE_SIZE, (unsigned int)sizeof(logEvent));
    db.create(1, TABLE_SIZE, (unsigned int)sizeof(secondEvent));

the second statement will override the old header excluding the first byte (0'th position)

the solution to your problem will be

    unsigned int FIRST_TABLE_HEADER_POSITION = 0;
    db.create(FIRST_TABLE_HEADER_POSITION, FIRST_TABLE_SIZE, (unsigned int)sizeof(logEvent));

    unsigned int SECOND_TABLE_HEADER_POSITION = FIRST_TABLE_HEADER_POSITION + (unsigned int)sizeof(EDB_Header) + FIRST_TABLE_SIZE;

    db.create(SECOND_TABLE_HEADER_POSITION, SECOND_TABLE_SIZE, (unsigned int)sizeof(secondEvent));

now you can use

    EDB_Status result = db.open(FIRST_TABLE_HEADER_POSITION );
and

    db.close();
    EDB_Status result = db.open(SECOND_TABLE_HEADER_POSITION );


message:
Using Arduino Uno as USB to serial converter

Can I use my Arduino Uno as a USB to serial converter to program my Raspberry pi 0 over serial communication?

My idea: Computer connects to Arduino via USB > Arduino connects with Raspberry pi 0 via GPIO pins.

How do I go about this?

body:
If you load an empty program in your arduino, and make the folowing connections:

Pi  -->  Arduino

Pin 8 --> Pin 1

Pin 10 --> Pin 0

Gnd --> Gnd

than you should see your linux console in the arduino serial program is you set the baudrate to 115200.

This method will work for the raspberry pi models without wifi.
On the wifi models the pins on the pi will be different.

The Arduino uses FTDI usb-to serial converter. This converters uart side is connected to the AVR-chip via pin 0 and 1. If you load an empty program in your arduino, it wil not use these lines. Now you can connect directly to the FTDI chip thru this pins. The converter does not care if it is communicating with the arduino or the pi over these lines.


body: You may also put Arduino in a reset state then Rx & Tx lines of serial converter will be free.


body:
In the arduino ide, go to file > examples > arduino as isp.
Might be a good starting point.

Seems like a lot of work though. If I were in that situation then I'd either use an ethernet cable and SSH, or, use a mobile phone as a WiFi hot-spot.


message:
Why can't my IF statement see a global?

I'm rather new to Arduino programming. I have a problem compiling the following bit of code:

    const int relay1 = 10;  //Power Relay 1
    const int relay2 = 11;  //Power Relay 2
    const int relay3 = 12;  //Toggle Relay
    const int button1 = 3;
    const int button2 = 4;
    const int button3 = 5;

    //---Button States---\\
    int button1State;   //Current state of Button 1
    int button2State;   //Current state of Button 2
    int button3State;   //Current state of Button 3
    int button1State_prev = LOW;  //Previous state of Button 1
    int button2State_prev = LOW;  //Previous state of Button 2
    int button3State_prev = LOW;  //Previous state of Button 3

    //---General Variables---\\
    int userSelection = 0;
    int interlockState = 0;
    int platformState = 0;

    //---Interval-Tracking Variables---\\
    unsigned long lastTime_Debounce1 = 0;   //Button 1 debounce time
    unsigned long lastTime_Debounce2 = 0;   //Button 2 debounce time

    //---Activity Delays---\\
    const unsigned int relayDelay = 10;           //Delay between relay actions (ms)
    const unsigned int debounceDelay = 60;        //Delay for button de-bouncing (ms)

    void setup() {
      //Configure Pins
      pinMode(relay1, OUTPUT);
      pinMode(relay2, OUTPUT);
      pinMode(relay3, OUTPUT);
      pinMode(button1, INPUT);
      pinMode(button2, INPUT);
      pinMode(button3, INPUT);

      digitalWrite(relay1, LOW);
      digitalWrite(relay2, LOW);
      digitalWrite(relay3, LOW);
    }

    void loop() {
      //Read value of each input pin
      int button1Reading = digitalRead(button1);  //Current reading of Button 1
      int button2Reading = digitalRead(button2);  //Current reading of Button 2
      int button3Reading = digitalRead(button3);  //Current reading of Button 3

      //Debounce Button1
      if (button1Reading != button1State_prev) {
        lastTime_Debounce1 = millis();
      }
      button1State_prev = button1Reading;
      if ((millis() - lastTime_Debounce1) > debounceDelay) {
        if (button1Reading != button1State) {
          button1State = button1Reading;
        }
      }

      //Debounce Button2
      if (button2Reading != button2State_prev) {
        lastTime_Debounce2 = millis();
      }
      button2State_prev = button2Reading;
      if ((millis() - lastTime_Debounce2) > debounceDelay) {
        if (button2Reading != button2State) {
          button2State = button2Reading;
        }
      }

For some reason, the compiler is convinced that the variable `lastTime_Debounce1` in the second IF-statement, on Line 54, has not been declared in-scope. I don't understand how this is possible, since the variable in question is a defined and initialized global.

If I comment-out the first trio of IF-statements (handling Button 1), the second trio (handling button 2) has no problem compiling, even though it does exactly the same thing in exactly the same way.

I checked all the usual suspects: spelling, braces, semicolons, even commented-out blocks of code one at a time, but I can't find the source of the problem. I'm using the Arduino 1.8.2 IDE.

Can someone please point out the mistake I'm missing?

body:
The backslash in your comments are the problem. As per C++ language definitions, a `\` at the end of the line is interpreted as a "line continuation". Thus, your comment gets continued in the next line and your variable declaration and initialization is commented out.

This is apparent when opening your code with a good syntax highlighting program, like Notepad++.

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

Removing all `\\` from the end of the comment line solves your problem.

Side note: For more info, look at https://stackoverflow.com/a/30290133/5296568. Backslashes at the end of a line are actually useful when used in multi-line macro definitions.

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


message:
Issue programming breadboarded Arduino via FTDI chip

I am trying to upload the Blink sketch to my ATmega chip which is now on a breadboard connected via an FTDI chip.

My clock is running, power is OK. I connected the reset pin via a 100 kohm to the vcc and have a 0.1 uF capacitor between the reset pin and the DTR pin of my FTDI chip.

[![a picture][1]][1]
[![a close up][2]][2]

Connections to the PCB with the FTDI chip:
[![Connections to the PCB with the FTDI chip][3]][3]

Does anybody know what I am doing incorrectly?

On a side note, I am running Ubuntu 16.04

All this seems correct to me, yet when I try to program the controller I get this exact:

<!-- language: lang-none -->

    /home/yalishanda/Downloads/arduino-1.8.5/arduino-builder -dump-prefs -logger=machine -hardware /home/yalishanda        /Downloads/arduino-1.8.5/hardware -tools /home/yalishanda/Downloads/arduino-1.8.5/tools-builder -tools /home/yalishanda    /Downloads/arduino-1.8.5/hardware/tools/avr -built-in-libraries /home/yalishanda/Downloads/arduino-1.8.5/libraries -libraries     /root/Arduino/libraries -fqbn=arduino:avr:uno -ide-version=10805 -build-path /tmp/arduino_build_476404 -warnings=none -build-        cache /tmp/arduino_cache_889393 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arduinoOTA.path=/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr -prefs=runtime.tools.avrdude.path=/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr -prefs=runtime.tools.avr-gcc.path=/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr -verbose /home/yalishanda/Downloads/arduino-1.8.5/examples/01.Basics/Blink/Blink.ino
    /home/yalishanda/Downloads/arduino-1.8.5/arduino-builder -compile -logger=machine -hardware /home/yalishanda/Downloads/arduino-1.8.5/hardware -tools /home/yalishanda/Downloads/arduino-1.8.5/tools-builder -tools /home/yalishanda    /Downloads/arduino-1.8.5/hardware/tools/avr -built-in-libraries /home/yalishanda/Downloads/arduino-1.8.5/libraries -libraries /root/Arduino/libraries -fqbn=arduino:avr:uno -ide-version=10805 -build-path /tmp/arduino_build_476404 -warnings=none -build-cache /tmp/arduino_cache_889393 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arduinoOTA.path=/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr -prefs=runtime.tools.avrdude.path=/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr -prefs=runtime.tools.avr-gcc.path=/home/yalishanda/Downloads/arduino-1.8.5/hardware    /tools/avr -verbose /home/yalishanda/Downloads/arduino-1.8.5/examples/01.Basics/Blink/Blink.ino
    Using board 'uno' from platform in folder: /home/yalishanda/Downloads/arduino-1.8.5/hardware/arduino/avr
    Using core 'arduino' from platform in folder: /home/yalishanda/Downloads/arduino-1.8.5/hardware/arduino/avr
    Detecting libraries used...
    "/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10805 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-I/home/yalishanda/Downloads/arduino-1.8.5/hardware/arduino/avr/cores/arduino" "-I/home/yalishanda/Downloads/arduino-1.8.5/hardware/arduino/avr/variants/standard" "/tmp/arduino_build_476404/sketch/Blink.ino.cpp" -o "/dev/null"
    Generating function prototypes...
    "/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10805 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-I/home/yalishanda/Downloads/arduino-1.8.5/hardware/arduino/avr/cores/arduino" "-I/home/yalishanda/Downloads/arduino-1.8.5/hardware/arduino/avr/variants/standard" "/tmp/arduino_build_476404/sketch/Blink.ino.cpp" -o "/tmp/arduino_build_476404/preproc/ctags_target_for_gcc_minus_e.cpp"
    "/home/yalishanda/Downloads/arduino-1.8.5/tools-builder/ctags/5.8-arduino11/ctags" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives "/tmp/arduino_build_476404/preproc/ctags_target_for_gcc_minus_e.cpp"
    Compiling sketch...
    "/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10805 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-I/home/yalishanda/Downloads/arduino-1.8.5/hardware/arduino/avr/cores/arduino" "-I/home/yalishanda/Downloads/arduino-1.8.5/hardware/arduino/avr/variants/standard" "/tmp/arduino_build_476404/sketch/Blink.ino.cpp" -o "/tmp/arduino_build_476404/sketch/Blink.ino.cpp.o"
    Compiling libraries...
    Compiling core...
    Using previously compiled file: /tmp/arduino_build_476404/core/wiring_pulse.S.o
    Using previously compiled file: /tmp/arduino_build_476404/core/WInterrupts.c.o
    Using previously compiled file: /tmp/arduino_build_476404/core/hooks.c.o
    Using previously compiled file: /tmp/arduino_build_476404/core/wiring.c.o
    Using previously compiled file: /tmp/arduino_build_476404/core/wiring_analog.c.o
    Using previously compiled file: /tmp/arduino_build_476404/core/wiring_digital.c.o
    Using previously compiled file: /tmp/arduino_build_476404/core/wiring_pulse.c.o
    Using previously compiled file: /tmp/arduino_build_476404/core/wiring_shift.c.o
    Using previously compiled file: /tmp/arduino_build_476404/core/CDC.cpp.o
    Using previously compiled file: /tmp/arduino_build_476404/core/HardwareSerial.cpp.o
    Using previously compiled file: /tmp/arduino_build_476404/core/HardwareSerial0.cpp.o
    Using previously compiled file: /tmp/arduino_build_476404/core/HardwareSerial1.cpp.o
    Using previously compiled file: /tmp/arduino_build_476404/core/HardwareSerial2.cpp.o
    Using previously compiled file: /tmp/arduino_build_476404/core/HardwareSerial3.cpp.o
    Using previously compiled file: /tmp/arduino_build_476404/core/IPAddress.cpp.o
    Using previously compiled file: /tmp/arduino_build_476404/core/PluggableUSB.cpp.o
    Using previously compiled file: /tmp/arduino_build_476404/core/Print.cpp.o
    Using previously compiled file: /tmp/arduino_build_476404/core/Stream.cpp.o
    Using previously compiled file: /tmp/arduino_build_476404/core/Tone.cpp.o
    Using previously compiled file: /tmp/arduino_build_476404/core/USBCore.cpp.o
    Using previously compiled file: /tmp/arduino_build_476404/core/WMath.cpp.o
    Using previously compiled file: /tmp/arduino_build_476404/core/WString.cpp.o
    Using previously compiled file: /tmp/arduino_build_476404/core/abi.cpp.o
    Using previously compiled file: /tmp/arduino_build_476404/core/main.cpp.o
    Using previously compiled file: /tmp/arduino_build_476404/core/new.cpp.o
    Using previously compiled file: /tmp/arduino_build_476404/core/core.a
    Archiving built core (caching) in: /tmp/arduino_cache_889393    /core/core_arduino_avr_uno_fbfa3aa7d5698fed1dc5326dc32eae8f.a
    Linking everything together...
    "/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr/bin/avr-gcc" -w -Os -g -flto -fuse-linker-plugin -Wl,--gc-sections -mmcu=atmega328p  -o "/tmp/arduino_build_476404/Blink.ino.elf" "/tmp/arduino_build_476404/sketch/Blink.ino.cpp.o"     "/tmp/arduino_build_476404/core/core.a" "-L/tmp/arduino_build_476404" -lm
    "/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr/bin/avr-objcopy" -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0  "/tmp/arduino_build_476404/Blink.ino.elf"     "/tmp/arduino_build_476404/Blink.ino.eep"
    "/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr/bin/avr-objcopy" -O ihex -R .eeprom      "/tmp/arduino_build_476404/Blink.ino.elf" "/tmp/arduino_build_476404/Blink.ino.hex"
    Sketch uses 928 bytes (2%) of program storage space. Maximum is 32256 bytes.
    Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.

    /home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr/bin/avrdude -C/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr/etc/avrdude.conf -v -patmega328p -cstk500v1 -P/dev/ttyUSB0 -Uflash:w:/tmp/arduino_build_476404/Blink.ino.hex:i

    avrdude: Version 6.3, compiled on Jan 17 2017 at 11:00:16
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr/etc/avrdude.conf"
         User configuration file is "/home/yalishanda/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyUSB0
         Using Programmer              : stk500v1
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
    ...

  [1]: https://i.stack.imgur.com/2TfCP.jpg
  [2]: https://i.stack.imgur.com/a92Lg.jpg
  [3]: https://i.stack.imgur.com/yLVTG.jpg

body: Right now you don't have a bootloader on your chip that's the reason why it wouldn't be programmed via UART so to flash the bootloader you need an ISCP programmer and an arduino bootloader.hex file.


message:
HC-05 bridge using Arduino Nano and GNU Screen

I connect an HC-05 module to an Arduino nano with CH341 serial chip (voltage divider on RX pin). I am trying to make a bridge for a test, i.e. serial in, echo local and echo to Bluetooth and vice versa. I modified the echo code from [here](http://spacetinkerer.blogspot.com).

    int incomingByte = 0;    // for incoming serial data

    #include <SoftwareSerial.h>

    SoftwareSerial BTSerial(10, 11); // RX | TX

    void setup() {
        BTSerial.begin(38400);    // opens serial port, sets data rate to 9600 bps
        Serial.begin(9600);    // opens serial port, sets data rate to 9600 bps
    }

    void loop() {
      // send data only when you receive data:
      if (Serial.available() > 0) {

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

        // say what you got:
        Serial.print((char)incomingByte);
        BTSerial.print((char)incomingByte);
      }

      if (BTSerial.available() > 0) {

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

        // say what you got:
        Serial.print((char)incomingByte);
        BTSerial.print((char)incomingByte);
      }

under OSX I open two terminals. In the first terminal using `screen /dev/cu.wchusbserial1410 9600` I see local echo as desired. But on the second terminal using `screen /dev/cu.HC-05-SPPDev 38400` I see nothing after pairing. The only effect is that by typing the latter command, the module stops blinking rapidly and blinks only two times with long pause in between. Exiting the `screen` environment, then again blinks rapidly.

Appreciate any hints what I am doing wrong...

=====

intermediate success but not quite there yet:

I simplified the code and corrected the wrong connection. Local echo on serial works as usual, even between the two, characters are being transferred, but they are black question marks instead of why I typed.

    /*
     * echo script
     */

    byte incomingByte;

    #include <SoftwareSerial.h>

    SoftwareSerial BTSerial(3, 2); // RX | TX

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

    void loop() {
      if (Serial.available()) {
        incomingByte = Serial.read();
        Serial.print((char)incomingByte);
        BTSerial.print((char)incomingByte);
      }

      if (BTSerial.available()) {
        incomingByte = BTSerial.read();
        Serial.print((char)incomingByte);
        BTSerial.print((char)incomingByte);
      }
    }

Any ideas?

========

Edited the Buadrate to 9600. Now everything works.

body:
Based on the above comments I provide here the full answer in the hope it will be useful in the future.

HC-05 has two modes. The **Communication Mode** and **AT Command Mode**. In the latter mode, HC-05 responds in kind of "config" way and many default settings of the communication mode can be change here. While the baud rate of the communication mode, and many other settings can be changed, the baud rate of the AT command mode is always fixed 38400 to avoid any confusions and mistakes. On the other hand, the **default** factory baud rate of the communication mode, i.e. before any change, is set to 9600. So the solution to my problem was to set the baud-rate to 9600 on my newly purchased HC-05 and I was able to make an echo bridge between HC-05 Bluetooth and serial. Here is the code:

    /*
     * echo script
     */

    byte incomingByte;

    #include <SoftwareSerial.h>

    SoftwareSerial BTSerial(3, 2); // RX | TX

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

    void loop() {
      if (Serial.available()) {
        incomingByte = Serial.read();
        BTSerial.print((char)incomingByte);
      }

      if (BTSerial.available()) {
        incomingByte = BTSerial.read();
        Serial.print((char)incomingByte);
      }
    }

After pairing HC-05 with OSX, I was able to open two OSX Terminals with one of these commands in the first terminal:

    screen /dev/cu.wchusbserial1410 9600

and in the other:

    screen /dev/cu.HC-05-SPPDev 9600

Everything worked properly, i.e. typing in one terminal produced characters in the other and vice versa. For changing the default baud-rate in the communication mode, I found a very good tutorial which can be found [here](http://www.martyncurrey.com/arduino-with-hc-05-bluetooth-module-at-mode/).


message:
strcmp() returns 0 when chars are different

I am trying to build a sketch that reads a single number from the Serial Monitor and uses it to light a 7 segment display with this number.

I need to compare the input with the known values, stored in a char array, to know which character was typed in and associate the matching binary combination to light the 7 segment display.

I have made a sample code extracted from the sketch, just to test if I am able to pass a char and get the correct result back:

<!-- language: lang-cpp -->

    char nums[] = "0123456789."; // The characters we will check against

    /* Tried also these, same results
          char nums[12] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', '\0'};
          char nums[] = "456789.0123";
    */

    void setup() {
      Serial.begin(9600);
      Serial.println("Write a single character"); Serial.println(" ");
    }

    void loop() {
      if (Serial.available() > 0) {
        char text = Serial.read(); // Read a single char from serial
        Serial.print("Character provided is: "); Serial.println(text);
        char c = parseChar(text); // Evaluate the char
        Serial.print("Character returned is: "); Serial.println (c);
        if (strcmp(c, text) == 0) { // Check if the returned char is the same
          Serial.print("      CORRECT character returned");
        } else {
          Serial.print("      WRONG character returned");
        }
        Serial.println(" ");
      }
    }

    char parseChar(char c) {
      int comp = 0;
      Serial.println("----- parseChar() START-----");
      Serial.print("  Parameter 'c' is: "); Serial.println(c);
      for (int i = 0; i < sizeof(nums) ; i++) { // Check the values of the array one by one
        comp = strcmp(c, nums[i]); // Compare the chars
        Serial.print("  Compare to nums["); Serial.print(i); Serial.print("] = "); Serial.print(nums[i]); Serial.print(" --> Result: "); Serial.println(comp);

        /* If the check matches, return the character at that index.
           For simplicity, it just returns the matching char of the array,
           that should be the same as the one sent in to the function.
        */
        if (comp == 0) {
          Serial.println("----- parseChar() END (found) -----");
          return nums[i];
        }
      }
      Serial.println("----- parseChar() END (not found)-----");
      return 0;
    }

The function works well for all numbers from 0 to 6. However, for any number over 6, or any other character, the strcmp() function returns always 0, so the returned character is the index 0 of the array, regardless of the character typed.

This is the Serial Monitor output for different characters:

    Write a single character

    Character provided is: 3
    ----- parseChar() START-----
      Parameter 'c' is: 3
      Compare to nums[0] = 0 --> Result: 1
      Compare to nums[1] = 1 --> Result: 1
      Compare to nums[2] = 2 --> Result: 1
      Compare to nums[3] = 3 --> Result: 0
    ----- parseChar() END (found) -----
    Character returned is: 3
          CORRECT character returned

    Character provided is: 6
    ----- parseChar() START-----
      Parameter 'c' is: 6
      Compare to nums[0] = 0 --> Result: -6
      Compare to nums[1] = 1 --> Result: 1
      Compare to nums[2] = 2 --> Result: 1
      Compare to nums[3] = 3 --> Result: 1
      Compare to nums[4] = 4 --> Result: 1
      Compare to nums[5] = 5 --> Result: 1
      Compare to nums[6] = 6 --> Result: 0
    ----- parseChar() END (found) -----
    Character returned is: 6
          CORRECT character returned

    Character provided is: 7
    ----- parseChar() START-----
      Parameter 'c' is: 7
      Compare to nums[0] = 0 --> Result: 0
    ----- parseChar() END (found) -----
    Character returned is: 0
          WRONG character returned

    Character provided is: g
    ----- parseChar() START-----
      Parameter 'c' is: g
      Compare to nums[0] = 0 --> Result: 0
    ----- parseChar() END (found) -----
    Character returned is: 0
          WRONG character returned

As you can see, the parseChar() function never returns a "not found" result, even for chars that are not in the array. In fact, it never loops through the array, as the first comparison returns 0 always.

I can't figure out why the strcmp() function returns 0 when the chars are different. Am I missing something?

body:
`strcmp` is not for comparing a single character like your `c` parameter. It is for comparing a null-terminated string. I'm a little surprised you didn't get a compiler error, but there it is.

If you want to compare individual characters, just compare them with `==`.


message:
Purposely create compile error to fail the upload

I would like to create a compile error so sketch does not upload in certain cases.

I have written a library with a function that adds pins being used to an array. If the same pin is used twice I want to fail the compilation (preferably with an error that explains why). Is this possible?

    void CheckPinNum(int newPinNum){
      for (int i=0; i <= PinArrayLength; i++){
        if (newPinNum == PinArray[i])
          failCompilation("You entered same pin twice!");
      }
    }

body:
To answer the question asked in the title:

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

    #if some_condition
    # error Some error message
    #endif

But note that this technique only works at _compile time_, which
probably makes it useless for you.


body:
It's impossible to check dynamic behavior compile time.

However, the best 'alternative' I can think of, is during the setup set all pin numbers (if that is possible).

And if something is wrong, let the 'user' or client know something is wrong. In extreme cases, just by putting the Arduino in an endless loop, in best cases, send a serial line, blink a light or whatever feedback.

You can do the same later on (when CheckPinNumber needs to be called in the loop, so not at setup), but the sooner you can do these checks, the better.


message:
Running multiple programs with one Arduino

Is it a problem to use multiple softwares to read the data that came from the same USB port simultaneously?

I have a board connected to a PC by USB, which is read by an application developed in C#. I display the data from the board in a table form.

Now I have to plot the data. The problem is that both the board and the software are deployed and can't be modified. So I have to create another program to do that, but the user should be able to run both softwares simultaneously.

Thank you!

body:
The question is not so much about Arduino, but about PC serial ports. There are programs/drivers out there that allow a user to "split" a serial port into two or more virtual serial ports, each of which can be opened by separate Windows applications, such as your C# programs.

Some of these programs or drivers are commercial and not free, and some are free.

https://www.fabulatech.com/serial-port-splitter-help/serial-port-splitting.html

http://www.eterlogic.com/help/vspe/UsageSplitPage.html

http://www.aggsoft.com/tcp-com/tcp-com-com-splitting.htm


message:
Joysitck with servo, LED array and buzzer

Does anybody know of a sketch that can turn a single servo 180 degrees clockwise/counterclockwise with the x axis of a joystick, light a bar graph LED with the Y axis, and sound a buzzer when the joystick button is depressed.

body:
You have a distinct set of requirements that you could turn into a sketch yourself.  I'm guessing you have never written a program before, in which case the problem really is you don't know how to do what you want to.

So, break the problem down into small chunks.  The less complex a problem the more likely you are to find a generic solution on the web that you can 'borrow'.

 1. How do you turn a servo?
 2. How do you read the position of a joystick?
 3. How do you light a LED bar graph?
 4. How do you sound a buzzer?

I'm pretty certain that you can find pages that tells you how to do each of those in separate sketches.  Once you have each of those working you need to merge the setup functions, making sure they don't over write each other and then tackle the loop functions (which will be more difficult).  BUT I know there are posts on here about how to merge two sketches into one.

I'm 99% certain you will not find a sketch that does what you want.  I'm 99% certain you will be able to coble together a solution that will do what you want if you break it down.

If you get stuck, post the code you have and explain your problem and people will help.

Good luck.


message:
Drive a 12V pump do I need a l293 driver

Me and my girlfriend are working on a small automatic plant watering system. Our first goal is to make an electrical 12V pump suck water out of a bottle.

As we were reading tutorials online we noticed that many people hook up a driver such as the l293 to their arduino in order to control the pump (essentially a brushed DC motor).

http://www.ti.com/lit/ds/symlink/l293.pdf

Our pump is 12V 4.2 W.

My question is do we really need a driver like that for just activating / deactivating the pump ?

In my understanding the driver offers an H-bridge setup allowing to control up to two motors in both directions.

Are there any other reasons to prefer this driver instead of a simple MOSFET / Transistor setup with such a simple use case like ours ?

Thank you for your help.

Best regards

body: Unless you wish to reverse the direction of the pump without reconnecting the wires in the opposite way, there is no need for a L293. A MOSFET that operates as a switch should be sufficient in your case. You can also try to PWM it and reduce/control the water flow.


message:
Arduino Interrupts Classes and Namespace

I'm working inside the Arduino IDE environment and have made a class that builds on the [Adafruit RDG LCD with interrupts][1] While looking at how to combine the `Attach Interrupt()` into my class I came across [this post about using namespaces][2]

> Why make a class then? What about a namespace?
>
> A class with one instance is like a group with one person in it.
>
> -nickgammon

Understanding that Mr.Gammon is kind of a big deal around these parts, I'd like to understand how to insert/alter my current class into a namespace format. Currently, the most in-depth tutorial [I've found is here][3], but I don't see how I would mix in the `Attach Interrupt()` function

Right now, my code looks like

    /**** Pre-Setup *****/
    #define Menu_PIN 3
    voltile bool flag;

    //Init Class
    class LcdMenu : public Adafruit_RGBLCDShield
    {
      public:
      MenuFoo()
    }
    LcdMenu LcdM;

    //run Setup
    void setup()   /****** SETUP: RUNS ONCE ******/
    {
      pinMode(Menu_PIN, INPUT_PULLUP);
      attachInterrupt(digitalPinToInterrupt(Menu_PIN), ProcMenu, FALLING);
    }

    void loop()
    {
      if(flag){
        LcdM.MenuFoo();
        flag=false;
      }
    }

    //Handles Inturrupts for Class
    void ProcMenu()
    {
      flag=true;
    }

    //define MenuFoo
    void LcdMenu::MenuFoo(){[code]}

As I understand it, Implementing a namespace would eliminate the need for the `ProcMenu()` function making my code easier to read/maintain.

  [1]: https://forums.adafruit.com/viewtopic.php?f=47&t=31107
  [2]: https://forum.arduino.cc/index.php?topic=160101.0
  [3]: https://luckyresistor.me/2014/10/31/how-and-why-to-use-namespaces/

body:
I don't it will change your design.

The main reason to use namespaces is to have an extra 'layer' of hierarchy.

Like a book that can be divided in chapters (classes).
But if you want to combine multiple books (projects) than you use name classes (e.g. to prevent name clashes of equally named class names).


body:
In this particular instance, and since you are inheriting from a class
of a known library, making your own class makes sense. You just have to
be aware that, although you can in principle have multiple instances of
a class, you can only have _one single handler_ for a particular
interrupt. Thus the handler cannot be a regular method of the class (a
method that knows it has been called for `this` instance), but it can be
a `static` method. Such a method is much like a regular function which
uses (abuses?) the class as a sort of namespace.

I would try something along these lines:

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

    class LcdMenu : public Adafruit_RGBLCDShield
    {
    public:
      LcdMenu();
      void begin([params]) {
        Adafruit_RGBLCDShield::begin([params]);
        attachInterrupt(digitalPinToInterrupt(Menu_PIN), handleInterrupt, FALLING);
      }
      void MenuFoo();
      void update() {
        if (flag) {
          MenuFoo();
          flag=false;
        }
      }
    private:
      static volatile bool flag;
      static void handleInterrupt() { flag = true; }
    }

    volatile bool LcdMenu::flag;

Then you just have to call `LcdM.update()` in `loop()`.


message:
Nano v3 dual power source use & detection

I would like to run a Nano 3.0 from both the VIN (mains power supply 7V) and USB power (backup). I understand it selects the highest voltage and switches to VIN at 6.6V. However I am unsure of the following:

1. How is it possible to detect which power source is being used?
2. How is it possible to detect if the source has been switched?
3. How is it possible to detect if the power source NOT in use has been disconnected.

body:
To check, if VIN is connected, you can connect VIN through a voltage divider to a digital pin (as suggested in the comment of Code Gorilla). For checking the USB connection you would have to connect VUSB to another digital pin. Since VUSB is not exposed on a pin, this could be difficult to do, but it is possible.

But note, that this would also show a disconnect, when the voltage drops (e.g. empty battery). When you want to detect real mechanical disconnects, you need a power jack with an extra switch integrated.

Let's take a look at the schematics: [Arduino Nano 3.0 Schematics][1]
[![Schematics of Arduino Nano v3.0 voltage supply][2]][2]
The selection of voltage supply is done by the diode D1. If the voltage resultung from the VIN regulator is higher than VUSB - diode_voltage_drop, the diode is closing and the power comes from VIN. If the voltage resulting from VIN is lesser, the current can flow from VUSB. How much power is really drawn from USB depends on the voltage difference.

So - to detect which source is actually used - you can measure the voltage on the diode with an analog measurement with the ADC or through connecting for example a comparator and using a digital pin.

Note that the voltage on the diode can be positive or negative, depending on which source is used.

  [1]: https://www.arduino.cc/en/uploads/Main/ArduinoNano30Schematic.pdf
  [2]: https://i.stack.imgur.com/DPGm2.png


message:
How do I create boundaries for the possible values of an integer?

I want to create an integer whose total value cannot go beyond a range of numbers when added to and subtracted from. For example, if the "total_value" started at 0 (of a total possible range between -5 and 5), and then, using a button that added 1 to the total value, I got to 5, if I was to press it again it would not go to six but either reset to 5 or block another input of +1.

How would I go about achieving something to this effect?

Liam

body:
You can not create a number with arbitrary upper and lower limits.  It is common in the C language to create an integer comprised of 16 bits.  Such an integer has a minimum of:

    -(2^15) = -32768

...and maximum of:

    (2^15) - 1 = +32767

Instead, after pressing the positive button, consider testing if "total_value" is 5 and skipping adding 1 to "total_value" if TRUE.  Conversely, after pressing the negative button, consider testing if "total_value" is -5 and skipping subtracting 1 from "total_value" if TRUE.


body:
For adding:

    total_value = total_value + 1;
    if (total_value > 5)
      total_value = 5;

And for subtracting:

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

    total_value = total_value - 1;
    if (total_value < -5)
      total_value = -5;

You may find a C or C++ tutorial very helpful.

---

Another method for adding:

    if (total_value < 5)
      total_value++;

And for subtracting:

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

    if (total_value > -5)
      total_value--;


body:
You are probably looking for the [constrain()](https://www.arduino.cc/reference/en/language/functions/math/constrain/) macro (an existing implantation of clamp logic, credit goes to @Edgar Bonet)

    value = constrain(value + input, -5, 5);

----------

If you get tired of writing `constrain()` you can even wrap it in a new type (which might be over-engeneering), producing something like following(code not tested)

    template<typename T>
    struct BoundValue {
     T value;
     const T vmin, vmax;
     //similar for other operators +,/,-=,...
     decltype(*this)& operator+=(T operand) { value = constrain(value + operand, vmin, vmax); return *this; }
     operator T() const { return value; }
     BoundValue(const T& vmin, const T& vmax) : vmin(vmin), vmax(vmax) {}
     BoundValue& operator=(const T& other) { value = constrain(other, vmin, vmax); return *this; }
    };

and use like variable of its argument type

 BoundValue<int> val(-5, 5);
 val += 6;//val = 5


message:
How do I connect my Ublox neo 6M GPS Module with arduino mega 2560?

I tried connecting RX of GPS to Pin 18 and TX of GPS to Pin 19 but I get an error that No GPS is detected,check wiring.VCC of GPS to 5V.

I have set baudrate to 115200.I am trying DeviceExample code of TinyGPS++ library.

body:
The default baud rate for ublox NEO-6M GPS devices is 9600, **not** 115200.

And try [NeoGPS](https://github.com/SlashDevin/NeoGPS).  It's smaller, faster, more accurate, more reliable and it comes pre-configured to use `Serial1` on a Mega.  Be sure to read the Installation instructions.  If it doesn't work, follow the Troubleshooting pages and try NMEAdiagnostic.ino.

NeoGPS has an example sketch (ubloxRate.ino) that can configure the NEO-6M to other baud rates, once you get the basic programs working at 9600.


message:
When i press a button to subtract 1 from 5 it skips to 3

, it's the same when I add 1 to -5 it skips displaying - 4 and goes straight to -3.

This is the code that i am using:

    //Testing the use of addition and subtraction with the menu options.

    #include <LiquidCrystal.h>

    LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

    int lcd_key     = 0;
    int adc_key_in  = 0;
    int calc_total;

    #define btnRIGHT  0
    #define btnUP     1
    #define btnDOWN   2
    #define btnLEFT   3
    #define btnSELECT 4
    #define btnNONE   5

    int read_LCD_buttons(){
        adc_key_in = analogRead(0);

        if (adc_key_in > 1000) return btnNONE;

        if (adc_key_in < 50)   return btnRIGHT;
        if (adc_key_in < 150)  return btnUP;
        if (adc_key_in < 300)  return btnDOWN;
        if (adc_key_in < 450)  return btnLEFT;
        if (adc_key_in < 700)  return btnSELECT;

        return btnNONE;

    }

    void setup(){
       lcd.begin(16, 2);
       lcd.setCursor(0,0);
       lcd.print (calc_total);

    }

    void loop(){

       lcd_key = read_LCD_buttons();
       calc_total = constrain(calc_total, -4, 4);

       switch (lcd_key){

           case btnRIGHT:{
                lcd.clear();
                calc_total = calc_total - 1;
                lcd.print (calc_total);
                delay(700);
                lcd.setCursor(0,0);
                break;
           }
           case btnLEFT:{
                lcd.clear();
                calc_total = calc_total + 1;
                lcd.print (calc_total);
                delay(700);
                lcd.setCursor(0,0);
                break;
           }
         }
    }

body:
The whole point of `constrain` function is to keep the values between `-4` and `4` (including). In your code you can go to the -5 and show it, but right after that it's adjusted to `-4` (and you are not displaying this value).

If you increment this value, you can get only result and this is  `-4 + 1 = -3`.


body:
Your main problem is that you aren't looking for a *change* in buttons. You're only doing your adding or subtracting *while* a button is pressed.

That means, all the time you're holding `btnLEFT` in your total is incrementing until it hits your limit.

You need to remember the button state from the previous iteration of `loop()` and compare it to the current state - and only if they differ do you need to do anything.

Also you should perform your constrain immediately after your addition or subtraction. As it is, you add or subtract, display the new value (I assume you do - I don't see the code for that), and only afterwards do you then chop the value back down to +/-4 (assuming it's outside the range). So your 5 becomes 4, and your next subtraction takes you to 3.


message:
Using timer2's ISR instead of timer1's in Arduino wiring.c breaks Serial object

I want to change *timer0* frequency because I need to use 4 PWM pins at a frequency lower than 500Hz and the SPI on an ATmega328. So I changed *timer2* to *Fast PWM* with 64 divisor, enabled the overflow interrupt for timer2 and disabled the overflow interrupt for timer0:

      TCCR2A = _BV(WGM21) | _BV(WGM20);
      TCCR2B = _BV(CS22);
      TIMSK2 |= (1 << TOIE2); // enable overflow interrupt for timer2
      TIMSK0 &= ~(1 << TOIE0); // disable overflow interrupt for timer0

and changed the ISR vector in *wiring.c* from `ISR(TIMER0_OVF_vect)` to `ISR(TIMER2_OVF_vect)`.

But `delay` doesn't work. What can be the problem?

body:
> Now everything works except for delay()

`delay()` uses `micros()` and `micros()` reads the hardware registers, like this:

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

    unsigned long micros() {
     unsigned long m;
     uint8_t oldSREG = SREG, t;

     cli();
     m = timer0_overflow_count;
    #if defined(TCNT0)
     t = TCNT0;
    #elif defined(TCNT0L)
     t = TCNT0L;
    #else
     #error TIMER 0 not defined
    #endif

    #ifdef TIFR0
     if ((TIFR0 & _BV(TOV0)) && (t < 255))
      m++;
    #else
     if ((TIFR & _BV(TOV0)) && (t < 255))
      m++;
    #endif

     SREG = oldSREG;

     return ((m << 8) + t) * (64 / clockCyclesPerMicrosecond());
    }

You would need to change all those references (TCNT0, TIFR0, TOV0 etc.) to use the Timer 2 equivalents.


message:
Assign string to an array value

I need to assign a string to an array value:

`char mystr[3] = "Hello";`

But when I run this code on arduino simulator: tinkercad.com, I get this error:

`1:17: error: initializer-string for array of chars is too long [-fpermissive]`

Why I'm getting this error?

body: You have asked the compiler to allocate 3 `char` of memory, and then you ask it to fill that memory with 6 `bytes` of data (5 characters, plus null-char for termination.)


message:
Do Arduino Megas Burn Out?

Im building a bedside alarm clock/home assistant. I have a few buttons that input, an LCD display and some RGB LEDs. The LCD and RGBs are only on when commanded to be on. I was wondering if I could leave the mega plugged in and constantly running or if that would burn it out. Im a bit new to this so sorry if this is dumb. If it would burn out, how long is its lifetime?

body:
As long as you operate the electronics within specification they will run for years and years. The first thing to probably fail will be the electrolytic capacitors that will dry out after maybe 10 years.

When reading datasheets and specifications the metric you are interested in is the **MTBF** - the [Mean Time Between Failures](https://en.wikipedia.org/wiki/Mean_time_between_failures).


message:
Trouble with Arduino -> PSOC4 communications over I2C! (Multi master/ slave config)

Hello Stack Exchangers!

I am currently working on a project which requires me to use PSOC4 - 049's to scan a series of inputs, and feed this data back to an arduino over I2C.

The arduino, or in this case a teensy 3.5, is the main unit which hosts a UI and retains key system variables. I wish to have the teensy send a few unsigned bytes to the arduino, and when user input is detected have the PSOC act as the master and send relevant information back to the arduino.

Unfortunately I've been trying for about a week now to no avail.

Currently I have 2 Teensy 3.5s sitting on my I2C bus and 1 PSOC4.
I send the first teensy a 'H' or 'L' character from a terminal over USB and it turns an LED high or low respectively,

This teensy then relays this character over the I2C Bus to the other teensy at address 0x10, which also toggles an LED.

The idea is that the first teensy then also forwards a value to the PSOC at address 0x11 but this simply isn't working for me!

I can't seem to get a single byte over to the PSOC let alone set up the full MMMS system I need!

Does anyone see what I'm doing wrong or have a good simple example of a PSOC project using Multi Master Multi Slave?

=-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-=
ARDUINO MASTER CODE     (Might be doing something wrong)
=-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-=
(Note that this function is part of a much larger project and is just being called from main at this time, much of the project is removed here but should not effect this code in any way)

    #include <Wire.h>
    void setup()
    {
         Wire.begin();
         Serial.begin(9600);
    }

    void loop()
    {checkCommand();}

    byte I2CTargetAddr[8] = {0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17}; //       Declares the addresses of the PSOCs

    void checkCommand() // Reads Serial Commands H or L, sets an LED, then     relays the instruction (hopefully) to the PSOC to do the same thing.
    {
      static int CCFR = 1;

      if (CCFR == 1)
      {
        pinMode(36, OUTPUT);  // Debug LED
        digitalWrite(36,HIGH);
        CCFR = 0;
      }

      char c;
      static char previousC = 'L';

      static byte low = 0;
      static byte high = 255;

      Wire.setClock(100000); // Set to 100kHz

      while(Serial.available())
      {
        c = Serial.read();

        if(c == 'H')
        {
          Wire.beginTransmission(I2CTargetAddr[0]);
          Wire.write('H');
          Wire.endTransmission();
          digitalWrite(36, HIGH);
        }

        else if(c == 'L')
        {
          Wire.beginTransmission(I2CTargetAddr[0]);
          Wire.write('L');
          Wire.endTransmission();
          digitalWrite(36, LOW);
        }
      }

    if(c == 'H')
    {
      Wire.beginTransmission(I2CTargetAddr[1]);
      Wire.write(high);
      Wire.endTransmission();
      //digitalWrite(high, HIGH);
    }

    else if(c == 'L')
    {
      Wire.beginTransmission(I2CTargetAddr[1]);
      Wire.write(low);
      Wire.endTransmission();
      //digitalWrite(low, LOW);
    }

      previousC = c;
    }

=-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=--=-=
ARDUINO TEST SLAVE CODE  (Seems to be totally fine)
=-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=--=-=

    #include <Wire.h>
    #define LED_1 23  // PWM Capable LED Pin

    void setup()
    {
      Wire.begin(0x10);
      Wire.onReceive(receiveEvent); // Calls the receiveEvent function when     something happens to the I2C bus
      pinMode(LED_1,OUTPUT);
      digitalWrite(LED_1, HIGH);
    }

    void loop()
    {
    }

    void receiveEvent(int howMany)
    {
      while(Wire.available())
      {
        char c = Wire.read();

        if (c == 'H'){digitalWrite(LED_1, HIGH);}
        if (c == 'L'){digitalWrite(LED_1, LOW) ;}
      }
    }

=-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-=-=-=-==-=-=-=-=-=-=-=-=-=
PSOC 4 Code
=-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-=-=-=-==-=--==-=-=-=-=-=-=

The topdesign includes a bootloadable component, a pin for LED Extern and LED Local, and an i2c block set as multi slave/ multi master at 100kb/s

-------------------------------MAIN.C---------------------------------

    #include <project.h>
    #include <main.h>

    extern uint8 I2CSlaveIn[BUFFER_SIZE];
    extern uint8 I2CSlaveOut[BUFFER_SIZE];
    extern uint8 I2CMasterIn[BUFFER_SIZE];
    extern uint8 I2CMasterOut[BUFFER_SIZE];

    /* Fast BootLoad ISR */
    CY_ISR_PROTO(bootloadISR_Handler);

    CY_ISR(bootloadISR_Handler)
    {
        Bootloadable_1_Load();   // Forces a restart of the bootloader,     triggered by the onboard button.
    }

    int main(void)
    {
        BootLoadSys_Start(); // Initialise easy bootloader tool
        bootloadISR_ClearPending();
        bootloadISR_StartEx(bootloadISR_Handler);

        initI2C(); // Initialised i2c

        CyGlobalIntEnable; /* Enable global interrupts. */

        uint8 transferredIn[BUFFER_SIZE];
        uint8 byteCount;
        uint8 lastVal = 0;

        LED_Local_Write(0);
        int i;

        for(;;)
        {
            if (0u != (MYI2C_I2CSlaveStatus() & MYI2C_I2C_SSTAT_WR_CMPLT)) //     Wait for master to complete Write
            {
                byteCount = MYI2C_I2CSlaveGetWriteBufSize();
                MYI2C_I2CSlaveClearWriteStatus();             // Take a wild guess

                for (i =0; i<byteCount; i++)
                {transferredIn[i] = I2CSlaveIn[i];} // Copy data from the buffer

                MYI2C_I2CSlaveClearWriteBuf();
            }

            if (transferredIn[0] != lastVal)
            {
                if (transferredIn[0] == 255u){LED_Local_Write(1);}
                if (transferredIn[0] == 0u  ){LED_Local_Write(0);}
            }

            lastVal = transferredIn[0];

        }
    }

----------------------------------I2C.C------------------------------------

    #include "project.h"
    #include "i2c.h"
    #include "main.h"

    uint8 I2CSlaveIn[BUFFER_SIZE];
    uint8 I2CSlaveOut[BUFFER_SIZE];
    uint8 I2CMasterIn[BUFFER_SIZE];
    uint8 I2CMasterOut[BUFFER_SIZE];

    void initI2C()
    {
        MYI2C_I2CSlaveSetAddress(MY_SLAVE_ADDR);

        MYI2C_I2CSlaveInitReadBuf( (uint8 *)I2CSlaveOut  , BUFFER_SIZE);
        MYI2C_I2CSlaveInitWriteBuf((uint8 *)I2CSlaveIn  , BUFFER_SIZE);

        MYI2C_Start();  // Calle after buffer setup
    }

----------------------------------I2C.h----------------------------------

    #define BUFFER_SIZE 1u // Sets Buffers size
    #define MY_SLAVE_ADDR 0x11u

    void initI2C();

body:
So it turns out I'm an idiot.
At some point in the last day or so I must have accidentally changed the pins that the I2C component is assigned to.

This code (or at least code very similar to this, after a couple of minor changes) works perfectly for the slave side.

Feel free to make use of it if you need it!


message:
running a dc motor with a small L298N module and an arduino and the L298N library

I have a small L298N module which I would like to use to run a couple of dc motors. The module I have is smaller than most of the ones you see on eBay, it looks like this...
[![enter image description here][1]][1]
I am trying to use the following library :
https://github.com/AndreaLombardo/L298N

I have managed to get the motor going forwards and backwards, but the problem is, this module doesn't have a pin for enable ( EN for PWM from the Arduino) and the library seems to require this; therefore I can't control the speed of the motors.

Does anyone have any experience with these modules? Is there a different technique I should be using? Is there another library that works with these kind of modules?

All help appreciated.

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

body:
PWM is used to control the duty cycle and not the voltage directly so your PWM will work directly on the input pins of motor driver and you will be able to control the speed.
just use analogWrite on the input pin which was held HIGH and HOLD the other pin to LOW. If you desire to change the direction while simultaneously controlling the speed. just analogWrite both the pins. Just keep in mind that the duty cycle of both the pins should not be tweaked simultaneously. while the speed is being controlled in one direction the other pin should be at analogWrite(other,0).


body:
 you can use this snippet in your code if you want

    void Loop()
    {
       //this is basically to demostrate how you can control the speed
       // and direction simultaneously
       for(i=0;i<256;i+=51)
       {
          analogWrite(motorForwardPin,i);
          analogWrite(motorBackwardPin,0);
          delay(2000);
       }
       for(i=0;i<256;i+=51)
       {
          analogWrite(motorForwardPin,0);
          analogWrite(motorBackwardPin,i);
          delay(2000);
       }
    }


message:
Not able to control digital pins using commands sent via HC-05 module

I am trying to control the LED on pin13 using the below code but it's not working.
With this code I am able to print to the Serial Monitor but the code has no effect on the any of the digital pins. I am unable to control the LED and so I have gotten stuck and can't advance further. I can't understand why it is happening even if I have excluded the new line from the Bluetooth app that I am using to send the strings and same on the Serial Monitor.

<!-- language: lang-cpp -->

    #include<SoftwareSerial.h>          // import the serial library

    SoftwareSerial bluetooth(6, 7);     // RX, TX

    void setup(){
      Serial.begin(9600);               //set baud rate
      bluetooth.begin(9600);
      pinMode(13, OUTPUT);
      digitalWrite(13, LOW);
    }

    void loop(){
      while (bluetooth.available()){
        char ch = bluetooth.read();
        message += ch;
      }

      if(!bluetooth.available()){
        if(message != ""){
          if(message.equalsIgnoreCase("on")){
            digitalWrite(13, HIGH);
          }else{
            digitalWrite(13, LOW);
          }
          Serial.println(message);
          message = "";
        }
      }
    }

body:
Your logic is a complete mess.  You have:

1. If a character is available, read it and add it to `message`.
2. If another character is available, compare what you have already stored with `on`.
  * If it's equal ('o' is not equal to 'on') turn on, otherwise turn off.
  * Print what you have stored.
3. Forget what you stored
4. Go to 1 (a character is still available since you never read it in stage 2).

Instead you need something more like:

1. If a character is available, read it into a variable.
2. If the character you read is a line ending character:
  * Compare your `message` with 'on' and take appropriate action
3. If the character you read is *not* a line ending character:
  * Add the character to `message`.
4. Go to 1.

Note how you only check once if there is a character available, and all your testing is done within that one `if` block.


message:
Send an multidimensional array of values from one arduino to another through serial port

I have connected two arduinos using pins: RX and TX and managed to send a string as an array of values:

    //sender

    char mystr[6] = "hello";

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

    void loop() {
      Serial.write(mystr);
      delay(1000);
    }

And receive it:

    //receiver

    char mystr[6];

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

    void loop() {
      Serial.readBytes(mystr,5);

      if(mystr[0] == 'h' && mystr[1] == 'e' && mystr[2] == 'l'){

        for(int i = 0;i < sizeof(mystr);i++){

          Serial.print(mystr[i]);

          if(i == sizeof(mystr) - 1){
           Serial.print("\r\n");
          }
        }
      }
      delay(1000);
    }

That worked fine! But I need to send and receive something like this:

    int a[3][4] = {
       {0, 1, 2, 3} ,
       {4, 5, 6, 7} ,
       {8, 9, 10, 11}
    };

How can I do that?

body:
Use two for loops to send the multidimensional array, and two for loops to receive the multidimensional array.

Sending:

    int a[3][4] = {
       {0, 1, 2, 3} ,
       {4, 5, 6, 7} ,
       {8, 9, 10, 11}
    };

    for (int x = 0; x < 3; x++)
    {
       for (int y = 0; y < 4; y++)
       {
          Serial.print(a[x][y]);
       }
    }

Receiving

    for (int x = 0; x < 3; x++)
    {
       for (int y = 0; y < 4; y++)
       {
          a[x][y] = Serial.read(); // Not sure about the exact prototype
       }
    }

If the sizes are fixed (like in your case 3 and 4), than you don't have to send the dimensions, just sent the values in order: 0, 1, 2, 3, 4, ... like above.

And when receiving them you know the first four values belong to row 0, next four values to row 1 etc.

If you need dynamic sizes, first send the number of rows and columns and than the values.

In that case instead of 3 and 4 define two constants and use them:

    #define NR_ROWS 3
    #define NR_COLUMNS 4

    int a[NR_ROWS][NR_COLUMNS] = {
       {0, 1, 2, 3} ,
       {4, 5, 6, 7} ,
       {8, 9, 10, 11}
    };

    for (int x = 0; x < NR_ROWS; x++)
    {
       for (int y = 0; y < NR_COLUMNS; y++)
       {
          Serial.print(a[x][y]);
       }
    }


message:
Arduino TimerOne breaks the program when calling "digitalRead"

I'm trying to make [this][1] project.

But i have a problem running this code. It appears to be `val = digitalRead(inPin);` breaks entire program. just because i call this from the `callback` function which attached as an interrupt function `Timer1.attachInterrupt(callback);`

Here is the more simplified problem simulation program,

    #include "TimerOne.h"

    int inPin = 7;   // sensing digital pin 7

    int val;

    void setup() {
      pinMode(inPin, INPUT);      // sets the digital pin 7 as input to sense receiver input signal

      Serial.begin(9600);
      Timer1.initialize(8);  // initialize timer1, and set the frequency; this drives both the LC tank as well as the pulse timing clock
      // note: modify this as needed to achieve resonance and good match with the desired tags
      // the argument value is in microseconds per RF cycle, so 8us will yield RF of 125kHz, 7us --> 143kHz, etc.

      Timer1.pwm(9, 512);

      Timer1.attachInterrupt(callback);
    }

    void callback()
    {
      val = digitalRead(inPin);//once you comment this line, it works fine
    }

    void loop() {
      Serial.print("Program running \n");

    }

Any help is much appreciated.

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

body:
The time between 2 interrupt triggers is only 8us. Also `digitalRead()` is a quite big function, that needs some time to execute (I don't know how much). That way it is to short for the Serial print command to execute in the leftover time. Make the following change and you will see, that it works.

<!-- language: lang-c -->

    void loop(){
      noInterrupts();
      Serial.print("Program running \n");
      interrupts();
      delay(1000);
    }
Now the interrupts are disabled during the execution of the `Serial.print()`, so that it can finish. After this the interrupts are enabled again and we wait for 1 second to give the interrupts some time before we are disabling them again.

The speed of the Arduino is limited, so you cannot do much, when constantly triggering interrupts in the pace of 8us. If you only want to check this digital input you can get the value directly with using the PINB registers (refer to [this side][1]), which works much faster.

Also you should consider making the variable `val` volatile, since it will can change everytime through your interrupt service routine.

  [1]: https://www.arduino.cc/en/Reference/PortManipulation


message:
I2C communication between Attiny85 as master and arduino UNO as slave

I want to make my Attiny85 and my Arduino UNO communicate together with I2C protocol. Since Attiny do not support Wire library, I use TinyWire by lucullusTheOnly and Wire on the Uno.

The Attiny is sending data as the master to the Uno, the slave.

Here is my code:

Master

    #include <TinyWire.h>

    byte slave_address = 10;

    void setup() {
     // config TinyWire library for I2C master functionality
     TinyWire.begin();
    }

    void loop() {
     TinyWire.beginTransmission(slave_address);
     TinyWire.send('c');
     // endTransmission sends the bytes in the buffer to the slave and returns 0 if there was no error
        TinyWire.endTransmission();
     delay(500);
    }

Slave

    #include <Wire.h>

    void setup() {
      Wire.begin(10);                // join i2c bus with address #10
      Wire.onReceive(receiveEvent); // register event
      Serial.begin(9600);           // start serial for output
    }

    void loop() {
      delay(100);
    }

    // function that executes whenever data is received from master
    // this function is registered as an event, see setup()
    void receiveEvent(int howMany) {
      while (1 < Wire.available()) { // loop through all but the last
        char c = Wire.read(); // receive byte as a character
        Serial.print(c);         // print the character
      }
      int x = Wire.read();    // receive byte as an integer
      Serial.println(x);         // print the integer
    }

I connect the pin like this :

    Arduino --> Attiny
    SCL ---- PIN 7
    SDA ---- PIN 5

I try to pull-up the clock and data line with 2.2k resistors but nothing happened, I receive nothing on the Uno from the Attiny.
Any idea ? Thanks !

body:
The pure master functionality of the TinyWire library is currently buggy. As a work around you can initiate the library on the ATTiny also as a slave with an address. When the `endTransmission()` function is called, the library switches temporarily to master mode for sending the bytes. I've tested this with your code in my own setup and it works. (Be sure, that the frequency in the ATTiny is set right. I tested the library only for 8MHz. For my own ATTiny's I had to do an extra step and set the correct fuses with avrdude)

I think the pure master part is blocking itself after the first transmission. I will add an issue in the github project. Maybe I can fix this in some time.

Chrisl aka lucullusTheOnly

EDIT: I had to think about this and looked into the library. The problem was found easily. In `twi.cpp` there is a `NOISE_TESTING` define block in the master send/receive function, which is constantly triggering error #6 (unexpected stop condition). In slave mode this doesn't happen, because directly before sending as a master it calls the master init function, which clears all USI flags, including the stop condition flag, that is polled in the send/receive function.

I have deactivated the `NOISE_TESTING` in the github project. If you don't want to download the current version, you can just open twi.h and comment the definition of `NOISE_TESTING`.


body:
I have the same issue even though I have the latest Github version with the NOISE_TESTING define block disabled.

I believe it has something to do with the line 359 in TWI.cpp where the stop condition isn't issued if a NACK happens:

          if( temp_result.result & (1<<TWI_NACK_BIT) )
      {
        if ( USI_TWI_state.addressMode )
          USI_TWI_state.errorState = USI_TWI_NO_ACK_ON_ADDRESS;
        else
          USI_TWI_state.errorState = USI_TWI_NO_ACK_ON_DATA;
        return (FALSE);
      }

I think it should be :

          if( temp_result.result & (1<<TWI_NACK_BIT) )
      {
        if ( USI_TWI_state.addressMode )
          USI_TWI_state.errorState = USI_TWI_NO_ACK_ON_ADDRESS;
        else
          USI_TWI_state.errorState = USI_TWI_NO_ACK_ON_DATA;
        USI_TWI_Master_Stop();
        return (FALSE);
      }

I tried it on ISIS in pure master only and it worked. I don't know if this is a viable solution or if it will cause any conflict with how the rest of the lib works.