body:
Initially I was sending sensor data to NodeJS using socketIO and this worked perfectly. I had to add a function to control an RGB LED using [this][1]. This also works but I'm unable to perform these two functions simultaneously.

I have tried to use two different ports on my Arduino. One to send data and another to control the LED but one overrides the other.

**Question:** Is there a way around this ? Is it practical to use two different ports?

**arduino sketch**

    if (client.connect(server, 4000)) {
        Serial.println("connected");
      }
      else {
        // if you didn't get a connection to the server:
        Serial.println("connection failed");
      }

      pinMode(pin, OUTPUT);
    }

    void loop()
    {

      //if you are connected and data is available
      if (client.available()) {
        char c = client.read();
       // Serial.print("Message is :  ");
        Serial.print(c);

        // '1' was received, return '1' for HIGH
        if (c == '1') {
          pinVal = HIGH;
        //  client.print("ON");
        }
        else if (c == '0') {
          pinVal = LOW;
        //  client.print("OFF");
        }

        //turn led pin to new position
        digitalWrite(pin, pinVal);

      }

    int chk = DHT.read11(DHT11_PIN);
      int t = DHT.temperature;
      int h = DHT.humidity;

              // send data to the server
            sendData(t, h);

      Serial.print("Temperature = ");
      Serial.print(t);
      Serial.print( "," );
      Serial.print("Humidity = ");
      Serial.print(h);
      Serial.print("\n");
       delay(6000);

    }

    void sendData(int temperature, int humidity)
    {
      if(!client.connected())
      {
        if (client.connect(server, 3000)) {

          Serial.println("Sending data...");
          // send the HTTP PUT request:
          client.print("GET /weatherserver/");
          client.print(temperature);
          client.print("/");
          client.print(humidity);
          client.print("/");

          client.println(" HTTP/1.1");
          client.println("Host: localhost");
          client.println("User-Agent: arduino-barom");
          client.println("Connection: close");
          client.println();
          client.stop();
        } else {
           Serial.println("Could not connect.");
           client.stop();
        }
      }
      delay(6000);
    }

  [1]: https://github.com/sergiomajluf/node-session/blob/master/socket/arduino/server-w-tcp.js

title: SocketIO Arduino TCP Port ISSUE

Answers: 2

body:
I'm not sure what you are doing, but you seem to be using two different protocols on two different ports.  So does you server side code open two ports? and does it accept the two different protocols?

If I was you I would change the RGB control to use REST (like you are doing with the DHT)  So you would send something like `GET /RGB/<id>/<state>`.

I'm not sure how your temperature is arriving at the server since you have sent a GET command rather than a PUT command (this could be the bug you are looking for).

body:
I implemented a better solution differentiating the client as `EthernetClient clientA` & `EthernetClient clientB`
> Client A handles TCP port and Client B handles HTTP GET Request.


body:
I am currently using an Arduino Mega with a fast vibration sensor to trigger the components operation (force sensor, temperature sensor) and also toggle sleep mode.

I am very new at this and I have been doing some googling, but I just can't seem to understand it.

So, my questions are:

1. How would I toggle(on/off) sleep mode?
2. How would I use interrupts (timer, pin change interrupt?) for an analog pin that triggers when the vibration sensor is triggered, resulting in other components operating?

I am currently working on a Mega, but I will eventually move on to the Arduino Mini Pro. I hope there are no exclusive problems later on.

I realize that this is not a professional question, but I find these tasks very challenging.

Please help me. An example link or perhaps example code to help me understand better.

Thank you very much.

title: Arduino Mega prototype analog timer interrupts: newbie question

Answers: 1

body:
> How would I use interrupts (timer, pin change interrupt?) for an analog pin that triggers when the vibration sensor is triggered, resulting in other components operating?

Thee best and most authoritative answer to that and all your other questions about the chip can be found in thee device data sheet and the compiler manual. Read them thoroughly and then write code to the data sheet to experiment.

Your can fire example have an analog interrupt where the chip constantly does ADC on the pin attached to the sensor and you can test the value of the ADC to see if certain trigger conditions are met and take appropriate actions.

The same with timers, etc. The data sheet is your best friend.


body:
I am working with an Arduino on a project for which timing is very important. I use TimerOne to trigger timer interrupts and use micros() for delays (delayMicroseconds() was causing problems worse than the one explained below). The program is sending a manual PWM signal to an LED and it is very important that the signal is sent with an error that is less than 8 microseconds (ideally, the signal is sent at the same time in each period). My test code is shown below:

    #include <TimerOne.h>
    #include <SPI.h>

    const int LED_PIN = 3;
    const int CHIP_SELECT = 12;

    const int PERIOD = 4000;
    const double DUTY_CYCLE = .5;
    const int HIGH_TIME = PERIOD * DUTY_CYCLE;
    const int LOW_TIME = PERIOD - HIGH_TIME;
    const int INITIAL_SIGNAL_DELAY = LOW_TIME / 2;
    const int HIGH_TIME_TOTAL_DELAY = INITIAL_SIGNAL_DELAY + HIGH_TIME;

    const int RESISTOR_VALUE = 255;

    boolean triggered = false;
    boolean data = false;

    unsigned long triggeredTime;
    unsigned long s;
    unsigned long e;

    boolean found;
    int i = 0;

    void setup()
    {
      s = micros();

      Timer1.initialize(PERIOD);
      Timer1.attachInterrupt(trigger);

      pinMode(LED_PIN, 3);
      pinMode(CHIP_SELECT, OUTPUT);

      SPI.begin();

      digitalWrite(CHIP_SELECT, LOW);
      SPI.transfer(B00010001);
      SPI.transfer(RESISTOR_VALUE);
      digitalWrite(CHIP_SELECT, HIGH);

      e = micros();

      Serial.begin(115200);
      Serial.print("s: ");
      Serial.println(s);
      Serial.print("e: ");
      Serial.println(e);
    }

    void loop()
    {
      if(triggered)
      {
        while(micros() - triggeredTime < INITIAL_SIGNAL_DELAY)
        { }
        s = micros();
        digitalWrite(LED_PIN, data);
        while(micros() - triggeredTime < HIGH_TIME_TOTAL_DELAY)
        { }
        digitalWrite(LED_PIN, LOW);

        data = !data;
        triggered = false;

        e = micros();
        //micros();

        if(s % 100 > 28 || s % 100 < 12)
        {
         found = true;
        }

        if(!found)
        {
          Serial.print("s: ");
          Serial.println(s);
        }
        else
        {
          Serial.print("ERROR: ");
          Serial.println(s);
        }
        //Serial.print("e: ");
        //Serial.println(e);
      }
    }

    void trigger()
    {
      triggeredTime = micros();
      triggered = true;
    }

(it should be noted that the first signal sent is always xx20, usually 5020).

So, with this code, I eventually get an error. I am not sure why, but this error occurs at the same point every single time:

    .
    .
    .
    s: 1141020
    s: 1145020
    s: 1149020
    ERROR: 1153032
    ERROR: 1157020
    ERROR: 1161020
    .
    .
    .

Now, the really weird part is if I remove the comments before micros() (the micros() right after e = micros()), there is no error (or at least there is not an error within the first 30 seconds). I was wondering if anybody could provide an explanation for why this happens. I have dedicated many hours trying to get the timing working properly and everything was working well until I encountered this error. Any help would be very much appreciated. Thank you!

title: Issue with Arduino Timing

Answers: 1

body:
the code flow doesn't make a lot of sense to me. seems to me that you can simplified quite a bit.

>if(s % 100 > 28 || s % 100 < 12)

I would use a few brackets to make it clear to the compiler what you want it to do.


body:
In recent project, I have to take reading from MAP sensor. So basically, we used analog pin for this. But in my case, I don't get proper result which actually I want.

When I'm taking readings through multi-meter then I got proper readings. Means when I start the vehicle then it's show 0.99 V. When I provide full throttle then voltage also increase and it's reach to 1.66 V. And finally when suddenly come back to normal throttle then also voltage decrease around like 0.48 V and then within a second again show normal 0.99 V.

Here, when I'm taking readings from MAP sensor through multi-meter then I'm providing ground to multi-meter. And when I taking readings from MAP sensor through Arduino then I'm not providing any ground to Arduino. Because I think it may be damage my Arduino.

So, I think this is also one possibility and may be possible that's why I'm not getting that type of voltage output through Arduino.

Here, the ground which I provide to multi-meter is from 12V DC battery which is used in CNG Auto rickshaw. So, that's why I'm not providing ground to Arduino. So, give me some suggestions about this. What should I do for this. Providing ground to Arduino or not.

Here, it's my code.

    int kMAP1 = 0;
    float kMAP2 = 0;

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

    void loop()
    {
      kMAP1 = analogRead(A0);
      kMAP2 =  kMAP1 * (5.0 / 1023.0);

      Serial.print("MAP1: ");
      Serial.print(kMAP1);

      Serial.print("\t");

      Serial.print("      MAP2: ");
      Serial.println(kMAP2);

      delay(1000);
    }

And it's my serial monitor output.

    MAP1: 490       MAP2: 2.39
    MAP1: 433       MAP2: 2.12
    MAP1: 270       MAP2: 1.32
    MAP1: 0           MAP2: 0.00
    MAP1: 447       MAP2: 2.18
    MAP1: 401       MAP2: 1.96
    MAP1: 518       MAP2: 2.53
    MAP1: 487       MAP2: 2.38
    MAP1: 344       MAP2: 1.68
    MAP1: 374       MAP2: 1.83
    MAP1: 611       MAP2: 2.99
    MAP1: 429       MAP2: 2.10
    MAP1: 647       MAP2: 3.16
    MAP1: 668       MAP2: 3.26
    MAP1: 460       MAP2: 2.25
    MAP1: 489       MAP2: 2.39
    MAP1: 278       MAP2: 1.36
    MAP1: 277       MAP2: 1.35
    MAP1: 318       MAP2: 1.55
    MAP1: 383       MAP2: 1.87
    MAP1: 238       MAP2: 1.16
    MAP1: 237       MAP2: 1.16
    MAP1: 134       MAP2: 0.65
    MAP1: 191       MAP2: 0.93
    MAP1: 230       MAP2: 1.12
    MAP1: 308       MAP2: 1.51
    MAP1: 479       MAP2: 2.34
    MAP1: 388       MAP2: 1.90
    MAP1: 544       MAP2: 2.66
    MAP1: 518       MAP2: 2.53
    MAP1: 419       MAP2: 2.05
    MAP1: 544       MAP2: 2.66
    MAP1: 586       MAP2: 2.86
    MAP1: 544       MAP2: 2.66
    MAP1: 575       MAP2: 2.81
    MAP1: 184       MAP2: 0.90
    MAP1: 202       MAP2: 0.99
    MAP1: 883       MAP2: 4.32
    MAP1: 671       MAP2: 3.28
    MAP1: 884       MAP2: 4.32
    MAP1: 487       MAP2: 2.38
    MAP1: 403       MAP2: 1.97
    MAP1: 184       MAP2: 0.90
    MAP1: 426       MAP2: 2.08
    MAP1: 412       MAP2: 2.01
    MAP1: 428       MAP2: 2.09
    MAP1: 434       MAP2: 2.12
    MAP1: 420       MAP2: 2.05
    MAP1: 312       MAP2: 1.52
    MAP1: 414       MAP2: 2.02
    MAP1: 435       MAP2: 2.13
    MAP1: 405       MAP2: 1.98
    MAP1: 418       MAP2: 2.04
    MAP1: 515       MAP2: 2.52
    MAP1: 462       MAP2: 2.26
    MAP1: 578       MAP2: 2.83
    MAP1: 332       MAP2: 1.62
    MAP1: 330       MAP2: 1.61
    MAP1: 164       MAP2: 0.80
    MAP1: 425       MAP2: 2.08
    MAP1: 345       MAP2: 1.69
    MAP1: 226       MAP2: 1.10
    MAP1: 0           MAP2: 0.00
    MAP1: 97       MAP2: 0.47
    MAP1: 872       MAP2: 4.26
    MAP1: 55       MAP2: 0.27
    MAP1: 492       MAP2: 2.40
    MAP1: 531       MAP2: 2.60
    MAP1: 1023       MAP2: 5.00
    MAP1: 43       MAP2: 0.21
    MAP1: 6           MAP2: 0.03

title: Not getting proper readings on Arduino from MAP Sensor

Answers: 3

body:
Although the circuit isn't shown and description isn't perfectly clear, evidently there is some question about how to connect up the various grounds.

Voltage, being “the difference in electric potential energy between two points per unit electric charge” [ref [Voltage article in Wikipedia](https://en.wikipedia.org/wiki/Voltage)], is measured between two points in an electric circuit.  If the two points are in unrelated and isolated circuits meaningful measurements can't be taken.

In typical [MAP sensor circuits](https://www.google.com/search?q=MAP+sensor+circuit&num=50&tbm=isch&tbo=u&source=univ&sa=X&ved=0ahUKEwiwipG7ucfRAhUH92MKHbzeC4oQsAQIGw&biw=1538&bih=804), the sensor output is relative to automotive ground, so your Uno's analog ground should be connected to automotive ground.  Whether this is electrically safe depends on several things:
• Sensor output voltage range – The multimeter readings showed a safe range.  The range is narrow compared to the Uno ADC's default +5V range; if you want a bit or two more resolution, you could either set up a 2 V external ADC reference, or could amplify the sensor output up to a range of about 5 V, or could use a unity gain op amp circuit followed by a voltage divider to get into a 0-to-1.1 V range, and use the internal 1.1 V bandgap reference.
• Uno power supply ground voltage – If the Uno's supply is isolated, its ground can be connected to automotive ground with no problem.  Or, if its supply ground already connects to automotive ground, no problem.  Where a problem might occur is if you measure a large voltage between automotive ground and Uno ground.  If so, connect a 100 Ω resistor between the two grounds and measure the voltage across it.  If the voltage is near zero, you can connect the grounds or could leave them connected by a small resistor like that.  If, on the other hand, some appreciable voltage appears across the resistor, or if it disappears in a puff of smoke, then they can't connect safely and you would need to use a different power supply for the Uno that doesn't have such a problem.
• Ground wire topology – The wiring path from Uno ground to automotive ground should not share any segments with high current devices.   In normal operation, or in case of a [load dump](https://en.wikipedia.org/wiki/Load_dump), several volts difference can arise between the ends of a piece of ground wire to a high current device.

body:
The ground does need to be connected. I have also added a RC filter to stabilize the sensor reading.

Connection :

>Arduino 5V  ----> MAP Vcc
>
>Arduino GND ----> MAP GND
>
>Arduino Analog Pin A0 <---- RC Filter <---- MAP Output pin

Using this connection, I get the proper readings.

Readings on Serial Monitor :

    // When Vehicle not start //
    MAP1: 376         MAP2: 1.84
    MAP1: 376         MAP2: 1.84
    MAP1: 376         MAP2: 1.84
    MAP1: 376         MAP2: 1.84
    MAP1: 376         MAP2: 1.84
    MAP1: 376         MAP2: 1.84
    MAP1: 376         MAP2: 1.84
    MAP1: 376         MAP2: 1.84
    MAP1: 376         MAP2: 1.84
    MAP1: 376         MAP2: 1.84
    MAP1: 376         MAP2: 1.84
    MAP1: 376         MAP2: 1.84
    MAP1: 376         MAP2: 1.84
    MAP1: 376         MAP2: 1.84

    //When start vehicle//
    MAP1: 343         MAP2: 1.68
    MAP1: 332         MAP2: 1.62
    MAP1: 341         MAP2: 1.67
    MAP1: 255         MAP2: 1.25
    MAP1: 215         MAP2: 1.05
    MAP1: 336         MAP2: 1.64
    MAP1: 320         MAP2: 1.56
    MAP1: 321         MAP2: 1.57
    MAP1: 308         MAP2: 1.51
    MAP1: 316         MAP2: 1.54
    MAP1: 326         MAP2: 1.59
    MAP1: 326         MAP2: 1.59
    MAP1: 325         MAP2: 1.59
    MAP1: 177         MAP2: 0.87
    MAP1: 219         MAP2: 1.07
    MAP1: 216         MAP2: 1.06
    MAP1: 220         MAP2: 1.08
    MAP1: 208         MAP2: 1.02
    MAP1: 211         MAP2: 1.03

    //Provide full throttle//
    MAP1: 319         MAP2: 1.56
    MAP1: 324         MAP2: 1.58
    MAP1: 341         MAP2: 1.67
    MAP1: 349         MAP2: 1.71
    MAP1: 353         MAP2: 1.73
    MAP1: 352         MAP2: 1.72
    MAP1: 352         MAP2: 1.72
    MAP1: 356         MAP2: 1.74
    MAP1: 357         MAP2: 1.74
    MAP1: 359         MAP2: 1.75
    MAP1: 355         MAP2: 1.74
    MAP1: 354         MAP2: 1.73
    MAP1: 327         MAP2: 1.60

    //Suddenly come back to normal throttle//
    MAP1: 181         MAP2: 0.88
    MAP1: 181         MAP2: 0.88
    MAP1: 192         MAP2: 0.94
    MAP1: 205         MAP2: 1.00
    MAP1: 201         MAP2: 0.98
    MAP1: 210         MAP2: 1.03
    MAP1: 218         MAP2: 1.07
    MAP1: 222         MAP2: 1.09

    //Provide full throttle again//
    MAP1: 309         MAP2: 1.51
    MAP1: 375         MAP2: 1.83
    MAP1: 395         MAP2: 1.93
    MAP1: 376         MAP2: 1.84
    MAP1: 261         MAP2: 1.28
    MAP1: 360         MAP2: 1.76
    MAP1: 307         MAP2: 1.50
    MAP1: 361         MAP2: 1.76
    MAP1: 259         MAP2: 1.27

    //Suddenly back again normal throttle//
    MAP1: 156         MAP2: 0.76

    //Again provide full throttle//
    MAP1: 295         MAP2: 1.44
    MAP1: 267         MAP2: 1.30
    MAP1: 287         MAP2: 1.40
    MAP1: 372         MAP2: 1.82
    MAP1: 380         MAP2: 1.86
    MAP1: 375         MAP2: 1.83
    MAP1: 229         MAP2: 1.12
    MAP1: 359         MAP2: 1.75
    MAP1: 339         MAP2: 1.66
    MAP1: 337         MAP2: 1.65
    MAP1: 359         MAP2: 1.75
    MAP1: 344         MAP2: 1.68

    //Again suddenly back to normal throttle//
    MAP1: 121         MAP2: 0.59
    MAP1: 164         MAP2: 0.80
    MAP1: 202         MAP2: 0.99

    //Again provide full throttle//
    MAP1: 310         MAP2: 1.52
    MAP1: 339         MAP2: 1.66
    MAP1: 356         MAP2: 1.74
    MAP1: 361         MAP2: 1.76
    MAP1: 274         MAP2: 1.34

    //Again suddenly back to normal throttle//
    MAP1: 127         MAP2: 0.62
    MAP1: 178         MAP2: 0.87
    MAP1: 221         MAP2: 1.08
    MAP1: 247         MAP2: 1.21
    MAP1: 224         MAP2: 1.09

    //Again provide full throttle//
    MAP1: 292         MAP2: 1.43
    MAP1: 278         MAP2: 1.36
    MAP1: 265         MAP2: 1.30
    MAP1: 367         MAP2: 1.79
    MAP1: 328         MAP2: 1.60
    MAP1: 358         MAP2: 1.75

    //Again suddenly back to normal throttle//
    MAP1: 182         MAP2: 0.89
    MAP1: 174         MAP2: 0.85
    MAP1: 242         MAP2: 1.18
    MAP1: 253         MAP2: 1.24
    MAP1: 261         MAP2: 1.28

    //Vehicle stop//
    MAP1: 307         MAP2: 1.50
    MAP1: 360         MAP2: 1.76
    MAP1: 375         MAP2: 1.83
    MAP1: 375         MAP2: 1.83
    MAP1: 375         MAP2: 1.83
    MAP1: 376         MAP2: 1.84
    MAP1: 375         MAP2: 1.83
    MAP1: 375         MAP2: 1.83
    MAP1: 376         MAP2: 1.84
    MAP1: 376         MAP2: 1.84
    MAP1: 377         MAP2: 1.84
    MAP1: 377         MAP2: 1.84
    MAP1: 377         MAP2: 1.84
    MAP1: 377         MAP2: 1.84

body: I once used an arduino to check the map sensor on my ford f150.  As an FYI, I will state that the ford map gave a digital pulse as output for the engine computer and was not analogue as the one you seem to be using.  I'm only commenting here for others who might be having trouble with a MAP sensor, so that they realize that some give pulse outputs and not voltage outputs.  So, I'm not sure about your map sensor, or turning the pulses into an average reading, but I simply used the interrupt to count pulses over a second and then recorded those readings over several minutes of drive time.  (I was having intermittent engine stumbling and I was ruling out the various sensors as causing the trouble.)  I was checking to make sure the MAP sensor didn't completely drop out from time to time.  In the end, it was my ignition module giving out due to heat fatigue that was the problem.  But, I can say that with a handful of resistors and a probe I was able to check all the sensors in the vehicle in short time...except for the oxygen sensor which I was afraid to damage due to its sensitivity.


body:
I'm going to write a sketch that would light up the first LED (D1) of the training shield at the beginning, then move the LED light to the left or to the right whenever you press the S1 or S2 buttons, respectively. When the LED is already at the first (D1) or the last (D8), it should no longer move when going further to the left or right, respectively.

Looks exactly like this: https://www.youtube.com/watch?v=_KQQTdDMgOU

Here's what I made so far:

    int x = 0;

    void setup() {
      for(int i=11; i <= 18; i++) {
        pinMode(i, OUTPUT);
      }
    }

    void loop() {
      x = digitalRead(pushButtonPin);
      if (pushButtonState == HIGH) {
        // turn LED on:
        digitalWrite(ledPin, HIGH);
      } else {
        // turn LED off:
        digitalWrite(ledPin, LOW);
      }
    }

title: Controlling a button

Answers: 1

body:
What you made so far is only turn on and off LED according to button state. I believe there's more efficient code out there, but you can try:

    int x = 11;

     void setup() {
     for(int i=11; i <= 18; i++) pinMode(i, OUTPUT); //assuming the led is on pin 11-18
     }

     void turnLED(int num)
     {
      for(int i=11; i <= 18; i++)
       if (num==i) digitalWrite(i,HIGH); else
          digitalWrite(i,LOW);
     }

     void loop() {

     if (digitalRead(buttonRight))
     {
      x++;
      if (x>18) x=18;
     }
     else if (digitalRead(buttonLeft))
     {
      x--;
      if (x<11) x=11;
     }
     turnLED(x); //turn LED on according to value of 'x'
     delay(500);
    }


body:
Is I can install Suse or Debian Linux Installation on Raspberry PI 3. I yet to try. Based on the answer I can opt for it. Because I need in particular either of this OS for my requirement in classified project. Does this PCB design supports this OS.

Any advice or suggestions is greatly appreciated.

Answers: 1

body:
It is always best to try then post in one of the Stack Exchange groups.

This question is very general.  So the answer will also be vague as the actual porting of a Linux OS distribution to a new platform is not trivial and contains many steps.  And not all of them may have been completed to the extent to suit your needs.

Evidently you can run Debian on a Raspberry Pi.  But there are a few issues.  [Look here][1] and do the research to understand if these limitations will cause you to abandon this path.

As for Suse, evidently it is a "specially packaged version of SUSE".  So may not actually have all the features a normal Suse distribution has.  [Look here][2] to decide if it will work for you.

  [1]: https://wiki.debian.org/RaspberryPi
  [2]: https://www.suse.com/products/arm/raspberry-pi/


body:
I am trying to reduce current consumption on my project. Right now it is using ~1.28mAh, it should be possible to get it much lower (I am using AA batteries as the power source).

The ATtiny85 has its fuses set to run at 1MHZ, with BOD disabled.

I am using [this board][1] to mount the CPU. I desoldered the power LED and the regulator, feeding power directly from the batteries to the 5V input.

Nothing was connected to any other pins while measuring, just 5V and GND. The code was running in debug mode, so every 8 seconds it flashed a debug LED. I don't know for how much this could account.

Full code:

    #include <avr/sleep.h>
    #include <avr/power.h>
    #include <avr/wdt.h>
    #include <avr/interrupt.h>

    #define DEBUG (true)
    #define INT_PIN (0)
    #define OUT_PIN (2)
    #define LED_PIN (1)

    /***************************************************
     *  Name:        ISR(WDT_vect)
     *
     *  Returns:     Nothing.
     *
     *  Parameters:  None.
     *
     *  Description: Watchdog Interrupt Service. This
     *               is executed when watchdog timed out.
     *
     ***************************************************/
    EMPTY_INTERRUPT(WDT_vect);
    EMPTY_INTERRUPT(PCINT0_vect);

    /***************************************************
     *  Name:        enterSleep
     *
     *  Returns:     Nothing.
     *
     *  Parameters:  None.
     *
     *  Description: Enters the arduino into sleep mode.
     *
     ***************************************************/
    void enterSleep() {
      set_sleep_mode(SLEEP_MODE_PWR_DOWN);
      sleep_enable();
      sleep_cpu();
      sleep_disable(); /* First thing to do is disable sleep. */

      #if DEBUG
        digitalWrite(LED_PIN, HIGH);
        for (uint16_t dbg = 0; dbg < 65535; dbg++);
        digitalWrite(LED_PIN, LOW);
      #endif
    }

    /***************************************************
     *  Name:        setup
     *
     *  Returns:     Nothing.
     *
     *  Parameters:  None.
     *
     *  Description: Setup for the serial comms and the
     *                Watch dog timeout.
     *
     ***************************************************/
    void setup() {
      pinMode(INT_PIN,INPUT);
      pinMode(OUT_PIN,OUTPUT);
      pinMode(LED_PIN,OUTPUT);
      ADCSRA &= ~_BV(ADEN); // ADC off
      power_all_disable();
    }

    /***************************************************
     *  Name:        enterSleep
     *
     *  Returns:     Nothing.
     *
     *  Parameters:  None.
     *
     *  Description: Main application loop.
     *
     ***************************************************/
    void loop() {
      digitalWrite(OUT_PIN, LOW);
      digitalWrite(LED_PIN, LOW);
      /*** Setup the WDT ***/
      wdt_reset();
      /* In order to change WDE or the prescaler, we need to
       * set WDCE (This will allow updates for 4 clock cycles).
       * WDTCR on ATTINY85 / WDTCSR on ATMEGA
       */
      WDTCR |= (1<<WDCE) | (1<<WDE);
      /* set new watchdog timeout prescaler value */
      WDTCR = 1<<WDP0 | 1<<WDP3; /* 8.0 seconds */
      /* Enable the WD interrupt (note no reset). */
      WDTCR |= _BV(WDIE);
      // sleep for 8 seconds x 43200 = 96 hours = 4 days
      for (uint16_t i = 0; i < 43200; i++)
        enterSleep();
      wdt_reset();
      wdt_disable();
      GIMSK |= _BV(PCIE); // Enable Pin Change Interrupts
      PCMSK |= _BV(PCINT0); // Use PB0 as interrupt pin
      enterSleep();

      #if DEBUG
        digitalWrite(LED_PIN, HIGH);
      #else
        digitalWrite(OUT_PIN, HIGH);
      #endif
      enterSleep();
      PCMSK &= ~_BV(PCINT0); // Turn off PB0 as interrupt pin
    }

  [1]: http://makbit.com/web/firmware/breathing-life-into-digispark-clone-with-attiny-mcu/

title: Reduce current consumption on ATtiny85

Answers: 1

body: Today I measured again without the development board. Just the CPU, same setup otherwise (original code, using the FTDI cable as power source) and I got a reading of about 6-8µA. I guess that answers it! Thanks everyone for your help!


body:
I would like to check the status of the sensors with Arduino UNO. For example, when I turn on the robot, I would like to check if all the sensors are connected and ready to be read or not. Maybe one sensor is unplugged and I want to detect this situation.

I read something about pull up resistors, but I didn't find any clear example of my problem. Also, I don't have any idea how to connect the resistor, how to calculate the resistor needed, as well as how to use the pull up resistor for digital and analog sensors.

Any schema, explanations and example would be very helpful!

title: Is there any way to check with Arduino UNO if a sensor is connected and ready to be read?

Answers: 1

body:
Basically pull-up resistor pulls up the line, when nobody/nothing is doing otherwise (for example wire unconnected, or connected to INPUT, or to I2C bus, which is not doing something right now ...). If some device (or Arduino) sets the wire to LOW (0V, GND, ground), the it overrules the resistor and the wire is LOW.

So the value of the resistor must be high enought to anable any attached device to draw the wire LOW. So if you know, how much of current can a device sink and what is considered LOW value on input, then you can compute the minimal value of the resistor from Ohm law (and the Vcc, where the resistor is connected). If you do not want calculate anything, just put 10KOhm between the wire and Vcc and it would probabelly work just fine.

---

About detecting sensor - you have to know, what sensor and where is supposed to be attached (as you construct the robot). So you just send any command to the sensor (probabelly to read a value) and see, if you get answer and the answer make a sense (eg. temperature is like 0-100 Celcius, or so). If it works OK, then the sensor is connected and can be used, otherwise you should stop the robot, light big red light and wait for user to repair what is broken. Thing also about the type of sensor, if it needs some time to "boot up" and it it needs some time to "seatle the value and answer" to provide that time before testing (like with delay()).

---

The pull-up resistors fits there in the way, that they are connected to Arduino, so if there is no connection to sensor, then the unconnected pin is not "floating" (and possibly return any random or not random value), but is weakly drawn up ti HIGH, so if the connetor is broken/unattached, then all reads are just plain HIGH, no communication from sensor (or any noise to be messing with the detection). So you can detect "no answer" status and after a while (when sensor really, really should answer, but did not) flash that big red light.


body:
I recently bought a micro SD storage shield for my arduino project, this is the [link][1]. My final goal is to log information every 100 ms about the temperature and pressure of my device using another one of my sensors. However, I started by testing out the SD card through the SdInfo class that comes as an example with the SdFat library. This is the outcome (through the Serial monitor):

    SdFat version: 20160719

    Assuming the SD is the only SPI device.
    Edit DISABLE_CHIP_SELECT to disable another device.

    Assuming the SD chip select pin is: 10
    Edit SD_CHIP_SELECT to change the SD chip select pin.

    type any character to start

    init time: 748 ms

    Card type: SDHC

    Manufacturer ID: 0X28
    OEM ID: BE
    Product: 68BHO
    Version: 0.8
    Serial number: 0XD50B3A66
    Manufacturing date: 11/2010

    cardSize: 32026.66 MB (MB = 1,000,000 bytes)
    flashEraseSize: 128 blocks
    eraseSingleBlock: true
    OCR: 0XC0FF8000

    SD Partition Table
    part,boot,type,start,length
    1,0X0,0XC,8192,62543872
    2,0X0,0X0,0,0
    3,0X0,0X0,0,0
    4,0X0,0X0,0,0

    Volume is FAT32
    blocksPerCluster: 64
    clusterCount: 976992
    freeClusters: 976905
    freeSpace: 32011.22 MB (MB = 1,000,000 bytes)
    fatStartBlock: 9310
    fatCount: 2
    blocksPerFat: 7633
    rootDirStart: 2
    dataStartBlock: 24576

    type any character to start

    cardBegin failed
    SD errorCode: 0XA
    SD errorData: 0X5

This is the code of the class SdInfo:

    /*
     * This program attempts to initialize an SD card and analyze its structure.
     */
    #include <SPI.h>
    #include "SdFat.h"
    /*
     * SD chip select pin.  Common values are:
     *
     * Arduino Ethernet shield, pin 4.
     * SparkFun SD shield, pin 8.
     * Adafruit SD shields and modules, pin 10.
     * Default SD chip select is the SPI SS pin.
     */
    const uint8_t SD_CHIP_SELECT = SS;
    /*
     * Set DISABLE_CHIP_SELECT to disable a second SPI device.
     * For example, with the Ethernet shield, set DISABLE_CHIP_SELECT
     * to 10 to disable the Ethernet controller.
     */
    const int8_t DISABLE_CHIP_SELECT = -1;
    SdFat sd;

    // serial output steam
    ArduinoOutStream cout(Serial);

    // global for card size
    uint32_t cardSize;

    // global for card erase size
    uint32_t eraseSize;
    //------------------------------------------------------------------------------
    // store error strings in flash
    #define sdErrorMsg(msg) sdErrorMsg_F(F(msg));
    void sdErrorMsg_F(const __FlashStringHelper* str) {
      cout << str << endl;
      if (sd.card()->errorCode()) {
        cout << F("SD errorCode: ");
        cout << hex << int(sd.card()->errorCode()) << endl;
        cout << F("SD errorData: ");
        cout << int(sd.card()->errorData()) << dec << endl;
      }
    }
    //------------------------------------------------------------------------------
    uint8_t cidDmp() {
      cid_t cid;
      if (!sd.card()->readCID(&cid)) {
        sdErrorMsg("readCID failed");
        return false;
      }
      cout << F("\nManufacturer ID: ");
      cout << hex << int(cid.mid) << dec << endl;
      cout << F("OEM ID: ") << cid.oid[0] << cid.oid[1] << endl;
      cout << F("Product: ");
      for (uint8_t i = 0; i < 5; i++) {
        cout << cid.pnm[i];
      }
      cout << F("\nVersion: ");
      cout << int(cid.prv_n) << '.' << int(cid.prv_m) << endl;
      cout << F("Serial number: ") << hex << cid.psn << dec << endl;
      cout << F("Manufacturing date: ");
      cout << int(cid.mdt_month) << '/';
      cout << (2000 + cid.mdt_year_low + 10 * cid.mdt_year_high) << endl;
      cout << endl;
      return true;
    }
    //------------------------------------------------------------------------------
    uint8_t csdDmp() {
      csd_t csd;
      uint8_t eraseSingleBlock;
      if (!sd.card()->readCSD(&csd)) {
        sdErrorMsg("readCSD failed");
        return false;
      }
      if (csd.v1.csd_ver == 0) {
        eraseSingleBlock = csd.v1.erase_blk_en;
        eraseSize = (csd.v1.sector_size_high << 1) | csd.v1.sector_size_low;
      } else if (csd.v2.csd_ver == 1) {
        eraseSingleBlock = csd.v2.erase_blk_en;
        eraseSize = (csd.v2.sector_size_high << 1) | csd.v2.sector_size_low;
      } else {
        cout << F("csd version error\n");
        return false;
      }
      eraseSize++;
      cout << F("cardSize: ") << 0.000512*cardSize;
      cout << F(" MB (MB = 1,000,000 bytes)\n");

      cout << F("flashEraseSize: ") << int(eraseSize) << F(" blocks\n");
      cout << F("eraseSingleBlock: ");
      if (eraseSingleBlock) {
        cout << F("true\n");
      } else {
        cout << F("false\n");
      }
      return true;
    }
    //------------------------------------------------------------------------------
    // print partition table
    uint8_t partDmp() {
      cache_t *p = sd.vol()->cacheClear();
      if (!p) {
        sdErrorMsg("cacheClear failed");
        return false;
      }
      if (!sd.card()->readBlock(0, p->data)) {
        sdErrorMsg("read MBR failed");
        return false;
      }
      for (uint8_t ip = 1; ip < 5; ip++) {
        part_t *pt = &p->mbr.part[ip - 1];
        if ((pt->boot & 0X7F) != 0 || pt->firstSector > cardSize) {
          cout << F("\nNo MBR. Assuming Super Floppy format.\n");
          return true;
        }
      }
      cout << F("\nSD Partition Table\n");
      cout << F("part,boot,type,start,length\n");
      for (uint8_t ip = 1; ip < 5; ip++) {
        part_t *pt = &p->mbr.part[ip - 1];
        cout << int(ip) << ',' << hex << int(pt->boot) << ',' << int(pt->type);
        cout << dec << ',' << pt->firstSector <<',' << pt->totalSectors << endl;
      }
      return true;
    }
    //------------------------------------------------------------------------------
    void volDmp() {
      cout << F("\nVolume is FAT") << int(sd.vol()->fatType()) << endl;
      cout << F("blocksPerCluster: ") << int(sd.vol()->blocksPerCluster()) << endl;
      cout << F("clusterCount: ") << sd.vol()->clusterCount() << endl;
      cout << F("freeClusters: ");
      uint32_t volFree = sd.vol()->freeClusterCount();
      cout <<  volFree << endl;
      float fs = 0.000512*volFree*sd.vol()->blocksPerCluster();
      cout << F("freeSpace: ") << fs << F(" MB (MB = 1,000,000 bytes)\n");
      cout << F("fatStartBlock: ") << sd.vol()->fatStartBlock() << endl;
      cout << F("fatCount: ") << int(sd.vol()->fatCount()) << endl;
      cout << F("blocksPerFat: ") << sd.vol()->blocksPerFat() << endl;
      cout << F("rootDirStart: ") << sd.vol()->rootDirStart() << endl;
      cout << F("dataStartBlock: ") << sd.vol()->dataStartBlock() << endl;
      if (sd.vol()->dataStartBlock() % eraseSize) {
        cout << F("Data area is not aligned on flash erase boundaries!\n");
        cout << F("Download and use formatter from www.sdcard.org!\n");
      }
    }
    //------------------------------------------------------------------------------
    void setup() {
      Serial.begin(9600);

      // Wait for USB Serial
      while (!Serial) {
        SysCall::yield();
      }

      // use uppercase in hex and use 0X base prefix
      cout << uppercase << showbase << endl;

      // F stores strings in flash to save RAM
      cout << F("SdFat version: ") << SD_FAT_VERSION << endl;
      if (DISABLE_CHIP_SELECT < 0) {
        cout << F(
               "\nAssuming the SD is the only SPI device.\n"
               "Edit DISABLE_CHIP_SELECT to disable another device.\n");
      } else {
        cout << F("\nDisabling SPI device on pin ");
        cout << int(DISABLE_CHIP_SELECT) << endl;
        pinMode(DISABLE_CHIP_SELECT, OUTPUT);
        digitalWrite(DISABLE_CHIP_SELECT, HIGH);
      }
      cout << F("\nAssuming the SD chip select pin is: ") <<int(SD_CHIP_SELECT);
      cout << F("\nEdit SD_CHIP_SELECT to change the SD chip select pin.\n");
    }
    //------------------------------------------------------------------------------
    void loop() {
      // Read any existing Serial data.
      do {
        delay(10);
      } while (Serial.available() && Serial.read() >= 0);

      // F stores strings in flash to save RAM
      cout << F("\ntype any character to start\n");
      while (!Serial.available()) {
        SysCall::yield();
      }

      uint32_t t = millis();
      // initialize the SD card at SPI_HALF_SPEED to avoid bus errors with
      // breadboards.  use SPI_FULL_SPEED for better performance.
      if (!sd.cardBegin(SD_CHIP_SELECT, SPI_HALF_SPEED)) {
        sdErrorMsg("\ncardBegin failed");
        return;
      }
      t = millis() - t;

      cardSize = sd.card()->cardSize();
      if (cardSize == 0) {
        sdErrorMsg("cardSize failed");
        return;
      }
      cout << F("\ninit time: ") << t << " ms" << endl;
      cout << F("\nCard type: ");
      switch (sd.card()->type()) {
      case SD_CARD_TYPE_SD1:
        cout << F("SD1\n");
        break;

      case SD_CARD_TYPE_SD2:
        cout << F("SD2\n");
        break;

      case SD_CARD_TYPE_SDHC:
        if (cardSize < 70000000) {
          cout << F("SDHC\n");
        } else {
          cout << F("SDXC\n");
        }
        break;

      default:
        cout << F("Unknown\n");
      }
      if (!cidDmp()) {
        return;
      }
      if (!csdDmp()) {
        return;
      }
      uint32_t ocr;
      if (!sd.card()->readOCR(&ocr)) {
        sdErrorMsg("\nreadOCR failed");
        return;
      }
      cout << F("OCR: ") << hex << ocr << dec << endl;
      if (!partDmp()) {
        return;
      }
      if (!sd.fsBegin()) {
        sdErrorMsg("\nFile System initialization failed.\n");
        return;
      }
      volDmp();
    }

I have noticed that the SD card is detected only upon start up, after that it all goes to errors. I had the same situation using the default SdInfo class from the built-in Arduino examples, sometimes it would register the card, sometimes it wouldn't. **Why does this happen and how can I ensure it always reads the card?**

I have already read [this][2] question and ensured my wiring is proper and I have also formatted my card using the software and SdCard.org, it is a Fat32 format.

This is my setup:

[![Image 1][3]][3]

and

[![Image 2][4]][4]

  [1]:
https://www.amazon.com/gp/product/B00SL0QWDU/ref=oh_aui_detailpage_o01_s00?ie=UTF8&psc=1

  [2]: https://arduino.stackexchange.com/questions/17062/sd-card-fails-to-initialize
  [3]: https://i.stack.imgur.com/9HJ5d.jpg
  [4]: https://i.stack.imgur.com/QhN5H.jpg

title: Why is SD card failing to begin?

Answers: 1

body:
SdInfo is an example, but I hope you know there's no reason to call `sd.begin`  to re-initialize the SD library.  The example is really intended to scan several different cards, not the same card.

`sd.begin` is normally something you would do once, in `setup`, even if something else is using SPI (e.g., Ethernet).  You probably won't get this error in your "real" sketch.

**But to answer your question:**

I see that your card takes a long time to initialize (almost a full second).  The error code says that the card does not re-initialize within 2 seconds.  I had a [similar problem](https://arduino.stackexchange.com/questions/21368#21373), and the solution was to edit the SD library and slow down how quickly it asked the card, "Are you initialized yet?"

Error code 0x0A is SD_CARD_ERROR_ACMD41, so perhaps you can use the same technique in this loop, line 171 of SdSpiCard.cpp:

      // initialize card and send host supports SDHC if SD2
      arg = type() == SD_CARD_TYPE_SD2 ? 0X40000000 : 0;

      while (cardAcmd(ACMD41, arg) != R1_READY_STATE) {
        // check for timeout
        if (((uint16_t)millis() - t0) > SD_INIT_TIMEOUT) {
          error(SD_CARD_ERROR_ACMD41);
          goto fail;
        }
        delay( 150 ); // <-- wait a little
      }

###Update

There is a related question and answer [here](https://arduino.stackexchange.com/questions/3850/sd-begin-fails-second-time).  Calling `sd.begin` twice is actually an open issue in the library.


body:
I am currently sending data via my bluetooth and to it I send with me 4 different values looking like this:

    byte[] myByte = {"HelloOne", "HelloTwo", "HelloThree", "HelloFour"};
 WriteAsync(myByte);

And now I am looking for a way to store all these Hello's in different values.

What I have started with is something like this:

    if (Bluetooth.available())
    {
     while (true)
     {
       delay (50);
       char c = Bluetooth.read();
       readString += c;

       if (readString.length() >0) {

        if (readString[0] == "HelloOne")
        {
           Serial.println ("Hello One has been sent!");
        }

        if (readString[1] == "HelloTwo")
        {
           Serial.println ("Hello Two has been sent!");
        }

        if (readString[2] == "HelloThree")
        {
           Serial.println ("Hello Three has been sent!");
        }

        if (readString[3] == "HelloFour")
        {
           Serial.println ("Hello Four has been sent!");
        }

       }

     }

    }

And I have not actually been able to debugg (not currently at home but eager to get to fix this problem asap) so there is a slim chance that my current code might be working? Very unlikely though.

So my question is, what is the correct way to get each value out in a byte array that is being sent with bluetooth to arduino?

title: How to get each byte in byte array out and be able to work with them on their own?

Answers: 1

body:
Sorry if this sound patronising, its not meant to, I'm just trying to cover all aspects.

    byte[] myByte = {"HelloOne", "HelloTwo", "HelloThree", "HelloFour"};
    WriteAsync(myByte);

You are assigning 4 strings to the array `mByte`.  A string (lets ignore the Arduino type string for now) is a char* or a char[], so:

    char hello1[] = "HelloOne";
    char hello2[] = "HelloTwo";
    char hello3[] = "HelloThree";
    char hello4[] = "HelloFour";
(You don't need to do this in the code, how you have done it is fine, it just shows what you are really saying)

In English mByte should be an array of strings which in code is

    char* mByte[] = {"HelloOne", "HelloTwo", "HelloThree", "HelloFour"};

You could do it as

    char mByte[][] = {"HelloOne", "HelloTwo", "HelloThree", "HelloFour"};//ERROR

But this won't compile, because the inner array (the text) is different length and the compiler doesn't like that.

Assuming that `writeAsync` takes a byte as a parameter then the code to write the data becomes this:

    for (int stringCounter = 0; stringCounter < 4; ++stringCounter)
    {
        // get a pointer to the first element of the string
        // & means get the address (so the value can be set to a pointer)
        // (byte*) means cast (change) the value into a byte pointer.
        byte* currentLetter = (byte*)(&mByte[stringCounter][0];)
        // currentLetter != NULL means the pointer is not equal to NULL, because looking at a null pointer will crash the code.
        // *currentLetter != NULL means the thing pointed to by currentLetter is not the end of the string.
        while (currentLength != NULL || *currentLength != NULL)
        {
            // Write the thing pointed to by the pointer to the function.
            writeAsych(*currentLetter);
            currentLetter++;  // Move on the pointer
        }
    }

Sorry I can't compile that at the moment, but it looks about write.  I hope it helps you understand it.


body:
Here is the answer: All pins corresponding to the G row are connected to ground. All Pins corresponding to the V row are connected to NodeMCU's 3V3 pin.

D row pins tagged from 0 to 8 correspond to NodeMCU's D1-D8 pins. D row pins tagged with SD2, SD3 corresponds to NodeMCU's SD2, SD3 pin
UTART/SPI section:

Tags corresponding to the pins are self explanatory.
Near the white-colored power switch we have a pin called "AD". I couldn't figure how this motor shield's "AD" pin is interfaced to NodeMCU. Do you have any idea?

Following on https://arduino.stackexchange.com/questions/25260/basic-question-esp8266-board-pins, I can't seem to map the pins on its motor shield to software (the ones named UART/SPI, the GPIOs and the Analog Inputs). See the third image, with a NodeMCU installed.

[![Motor Shield][1]][1]

The GPIOs seem to conflict with the motors on Arduino, and I have no idea what to do here. Documentation is pretty much useless.

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

  [1]: https://i.stack.imgur.com/Q3URi.jpg
  [3]: https://i.stack.imgur.com/RXJJo.jpg

title: Following on ESP8266 Board pins, how do they map on the motor shield?

Answers: 1

body:
You see the pins marked `PWMA`, `PWMB`, `DA` and `DB`? Those are the pins that control the motors (`PWMx` is the speed, `Dx` is the direction). Whatever pins on your ESP8266 board plug into those holes are the pins you need to use in your code. How those pins map to names and numbers in the Arduino API depends entirely on what the board is you're plugging in and what the author of the board definition files was thinking at the time.

In short, look at your board (*which we cannot see*) and see what GPIO pins are in the same location as the pins I pointed out. Then control those pins in your software.


body:
I'm having an issue trying to use a normal non-member function of my main sketch file as a callback.  I can't get the function pointer to invoke from a function other than it was saved.  More info below;

MotorEncoder.h

    typedef void (*cb)(int16_t,int16_t);
    class MotorEncoder
      ...
      private:
        cb _motor_callback;

Program.ino

    cb encoder_cb = NULL;
    ...
    encoder_cb = function_that_accepts_2_int16
    DC_Encoder_1.move(motor_pos, speed, motor_id, encoder_cb);

**EDIT:** I want to edit the description as to not confuse anyone.  The code with the callbacks above is all correct.  The issue was I was working with open-source software and another developer was setting the selected serial-port connection back to the bluetooth channel in-correctly.  The callback was executed, I was connected to the ATMega2560 via serial connection to a raspberry pi and was looking for the callback to show there, not monitoring bluetooth so I didn't see any data come across.  Document your code.

title: Typedef Function Pointer Invoking Issue

Answers: 1

body:
This answer contains a few debugging guidelines, as I don't know what the problem is and don't see how one could tell without a good deal more of information.

I suggest creating a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) (MCaVe) of your code, not just snippets, so that other people can compile and run the code, thus being able to observe what happens in more detail and perhaps with added debugging output.

I'm presuming your callback is triggered as a consequence of an interrupt occurring.  I suggest you write the MCaVe to depend on a pin-change interrupt, rather than a motor-controller interrupt, to allow testing on a system consisting of no more than an Arduino with a button, a serial interface, and perhaps a few LED indicators.  Pressing the button would change pin voltage and cause an interrupt; your ISR would turn on an LED to signal it handled the interrupt, then trigger the callback.  The callback routine would turn on another LED as its signal.  The main loop would read the pin register bits for the two LEDs, record and report the times they came on, and turn them off after a second or two.  If you get a simple setup like this to work, the technique probably would carry over to your motor-controller case; or if not, probably being a smaller program and setup should be easier to debug and figure out why not.


body: I have students using an arduino to control a fan.  We have multiple types of fans. We want to turn the fan off/on with digital HIGH.  When the 5V fan is plugged into 5V and ground, it runs.  When I ground it and attached the power side to a pin set to HIGH the voltage drops down to 2.2V??? When the fan is not plugged into the pin there is 5V.  Why would the power drop when the fan is plugged in?

title: Fan dropping voltage?

Answers: 2

body:
Most digital pins on Arduinos are qualified to handle up to 25 mA typically and 40 mA at most.  If more current than that is drawn or sunk, the pin voltage will drop or rise, out of specification.  This is due to resistance in the pin drivers, and by Ohm's law, voltage equal to current times resistance will develop.  That “lost” power (voltage times current) is converted to heat within the microcontroller, and can damage it.

The fan motors probably draw rather more than 25 mA; they probably require a few hundred mA.  You can add transistors or motor controllers between the Arduinos and the fans to deal with such current loads.

body:
Absolute Maximum Current per Pin is 40mA (in Arduino Uno) so when you connect the fan with the I/O pins at that time the fan may draw more current from the pin and because of this the voltage level of the pin may drop down. Because Fan or Motor want more current then the capacity of Arduino pins capacity so if you want to On/Start the Fan/Motor then you have to connect Fan/Motor Driver between the Arduino Pin and Fan/Motor. And you have to provide external power source to the motor driver circuit.
For your reference:
[![Transistor base Motor Driver Circuit][1]][1]
[![Motor Driver Module][2]][2]

  [1]: https://i.stack.imgur.com/qJQdL.png
  [2]: https://i.stack.imgur.com/4SKoI.jpg


body:
I am using an MH-Z19 CO2 sensor with an Arduino Mega using UART. As per the specifications of this sensor, after we send a command, we expect the response in a particular 9 byte format (with starting bytes as 0xFF and 0x86).

    byte cmd[9] = {0xFF, 0x01, 0x86, 0x00, 0x00, 0x00, 0x00, 0x00, 0x79};
    byte response[9];
    Serial.flush();
    Serial.write(cmd,9);
    while (Serial.available()<9) {}
    for(int n=0; n<9; n++) {
      response[n] = Serial.read();
    }
    if (response[0] != 0xFF) {
      //Error
      predictCo2 = 0;
    } else if (response[1] != 0x86) {
      //Error
      predictCo2 = 1;
    } else {
      predictCo2=((response[2]*256)+response[3]);
    }

I wait till all the 9 bytes are filled in to read the values.

The problem here is that, when I turn the board ON, most of the times the response isn't in the required format (starting bytes aren't 0xFF or 0x86).
But, if I press the Arduino reset button, it starts reading values in proper format straight away.

I'm wondering why this is happening. Why is the UART response not in the proper format immediately after I turn on the Arduino, and I have to explicitly do a reset? Is the reset button clearing the serial stream? How can this be achieved through software?

I included `serial.flush()` before sending the command, but that didn't help either.

title: UART communication issue on Arduino Mega

Answers: 1

body:
`Serial.flush()` only empties the output buffer, so that won't achieve anything. Reading exactly 9 bytes and hoping they match the input stream is not very effective, as you found. If you are out of sync with the incoming bytes, you will stay out of sync.

It would be better to keep reading (single bytes) until you get 0xFF or 0x86 and then read the rest.


body:
I have an Arduino Leonardo and a GPS module "NEO 6M"

Pinout:

    PPS->free
    rxd->11
    txd->10
    gnd->gnd
    vcc->5v

I'm running this code:

    #include "SoftwareSerial.h"
    SoftwareSerial gps(10,11);
    void setup(){
      Serial.begin(9600);
      gps.begin(9600);
    }

    void loop(){
      while (gps.available())
        Serial.write(gps.read());
    }

In serial monitor I'm getting random characters like this

[![Screenshot of serial monitor][1]][1]

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

Where am I going wrong?

I tried the same with an Arduino Mega but have the same result.

title: Arduino and GPS module Neo 6m

Answers: 1

body: Solved: GPS module was broken. Now I use another GPS module, same model. Sorry for my English.


body:
I want my Arduino to drive a LED strip.
The LED strip in particular is the 3528 non-waterproof type.
To power this up, I need a 12V power supply.
My LED strip is going to be 5 meters.

Now my questions are:

1. Is it important on how many amps, my powers supply will feed? One guy did it with 12V, 5A power supply. Considering the length (5m), is a particular amperage value necessary?

2. Can I power up the Arduino Nano with the power from the power supply? Voltage wise, I am clear, since the nano can handle 12 volts... What I am scared of is the amperage... Considering that I need a particular value of amps to power up my LED strip, can the nano handle this many amps? Is there a limit to how many amps the power supply line that I will feed my Arduino has to be?

title: Powering up LED strip - How many amps?

Answers: 3

body:
> 1) Is it important on how many amps, my powers supply will feed?

Yes.  You need the PSU to be able to supply as much current as you will need for everything you are powering form it.

You don't say how many LEDs will be on this strip (only the length of the strip) and I am not sure how much current/power a single one consumes, but **for illustration** let's imagine there are 100 LEDs on your strip and each one takes 0.8W.

100 LEDs x 0.8W per LED = 80W.

P = VI, where P=Power, V=voltage, I=current.

So I = P/V = 80 / 12 = 6.66A -- call it 7A.

The amount taken by the Nano will be small in comparison - if you said 0.5A you'd be safe.

So with these figures you'd need a 7.5A PSU.

> Considering that i need a particular value of amps to power up my LED strip, can the nano handle this many amps?

You can power the Arduino from the same power supply, yes.  The Arduino will *draw* whatever current it needs.  (Think of it this way: mains sockets are 13A - a desk lamp won't draw 13A.)  What matters is that the supply can supply at least enough current, and that the voltage is correct.

As mentioned in the comments, you can't drive 3528s directly from the Nano - but you don't ask about that so presume you either know how to do it, or will ask another question.

body:
Usually strips have not individual LEDs, but are composed of a lot of "pieces" in parallel, and each piece is composed by three leds in series along with a resistor.

Usually the strips are composed by 60 leds/m (i.e. pieces of 5cm), but sometimes also 120 leds/m or 30 leds/m. Let's assume it is the 60 leds/m version (you can check the length of the piece you can cut - which should be 5 cm - and that it contains 3 leds).

This means that in 5m there are 100 pieces. Now, usually the 3528 leds absorb 20mA of current for each segment (the 5050 version should be rated at 60). This means that the whole led strip should absorb 2A @ 12V.

Now the power supply. 2A is the nominal current the whole strips should absorb. Add about 200mA for the nano, and increase a bit the current requirement not to stress the power supply: you get a 12V 3A power supply at least (note that, while 12V should remain the same, you can take any current greater than this value - if for instance you have a 12V 5A power supply it is perfectly fine).

Now, the nano. It surely can't handle the 2A current. This means that you can power the arduino nano from the 12V. BUT beware: you should connect the 12V power to the VIN input (so the onboard regulator lowers it to 5V). Then you can't power the LEDs directly from the nano, but you need a transistor to decouple them. You can take any nMOS with a drain current greater than 3A or an NPN with collector current >3A and build the appropriate curcuit to drive them, then connect the + terminal of the strip to the +12V wire, the transistor source (or emitter) to the ground wire and the gate (base) should be driven by the nano.

body:
Because there are three LEDs in series, you cannot drive these LEDs from a 5V supply. The LED strips say "+12V" on them to mark the anode and that's the maximum voltage we suggest. We've found that if you're ok with them being a little dimmer, even 9VDC works very well.

Each segment of 3 LEDs draws approximately 20 milliAmperes from a 12V supply, per string of LEDs. So for each segment, there is a maximum 20mA draw from the red LEDs, 20mA draw from the green and 20mA from the blue. If you have the LED strip on full white (all LEDs lit) that would be 60mA per segment.

To find the total maximum current draw per meter, we would multiply 60mA x 10 (ten segments per meter for the 30/LED per meter strip) = 0.6 Amps per meter OR 60mA x 20 (twenty segments per meter for the 60/LED per meter strip) = 1.2 Amps per meter. Again, that's assuming you would have all the LEDs on at once and that you are powering it from 12V. If you're going to be PWM-fading between colors, maybe 1/2 of that is what you'll be drawing. Still, you do need to have a fairly decent power supply to run this strip, all those LEDs add up!


body:
I'm using a max7219 like this one max7219. When I first tested my circuit, I used an 8x8 display and the code worked just fine. Now, after I modified the code with the one that can be found online at [arduino code][1] and changed the display with the chained one, the text appears to be mirrored on the matrix display.

[![like in this picture][2]][2].

Below, I'll attach part of the code. Please help me find the problem.

    #include <MD_Parola.h>
    #include <MD_MAX72xx.h>
    #include <SPI.h>

    // Define the number of devices we have in the chain and the hardware interface

    #define MAX_DEVICES 4
    #define CLK_PIN  13
    #define DATA_PIN 11
    #define CS_PIN  10

    // Hardware SPI connection
    MD_Parola P = MD_Parola(CS_PIN, MAX_DEVICES);
    // Arbitrary output pins
    // MD_Parola P = MD_Parola(DATA_PIN, CLK_PIN, CS_PIN, MAX_DEVICES);

    void setup(void)
    {
      P.begin();
      P.displayText("Hello", PA_CENTER, 0, 0, PA_PRINT, PA_NO_EFFECT);
    }

    void loop(void)
    {
      P.displayAnimate();
    }

  [1]: https://github.com/MajicDesigns/MD_Parola
  [2]: https://i.stack.imgur.com/bzlIH.jpg

title: max7219 chained display showing mirrored text

Answers: 4

body:
Check the configuration in MD_MAX72xx.h file and ensure you have the right module selected.

For example there is a define

    #define USE_PAROLA_HW 0

if your hardware is this item then turn off the other hardware settings and turn this one on so it reads as follows:

    #define USE_PAROLA_HW 1

there many other settings if it is not there then you will have to experiment until you find the correct one.

body: In library, change `#define USE_GENERIC_HW 0`  to `#define USE_GENERIC_HW 1` is the solution.

body:
Since version 3.0 `MD_MAX72xx.h` no longer supports that definition. Now the hardware type is defined as a parameter on creation (in the "Example" file you are using - not in `MD_MAX72xx.h`)

    #define HARDWARE_TYPE MD_MAX72XX::FC16_HW
    ...
    MD_Parola P = MD_Parola(HARDWARE_TYPE, CS_PIN, MAX_DEVICES);

Note that I've changed the hardware type from `PAROLA_HW` to `FC_16`.

body:
In latest version of `#include <MD_Parola.h>`, `#include <MD_MAX72xx.h>` you have to define the following and characters will display correctly.

    #define HARDWARE_TYPE MD_MAX72XX::FC16_HW


body:
Background: I'm looking to start on my first real electronics project and I have an Arduino Uno I bought a while back. I've only done a few of the starter Arduino tutorials and that was a while back as well. Starting from very little electronics knowledge, I'm trying to get a bit of advice on how to tackle my first project.
**TL;DR:** I have an Arduino Uno but very little experience with it or electronics.

Project: I want an object that locks, I want the duration of the time it stays locked for to increase by ~1-3% every time it locks. I want to put my nicotine products in there to gradually pull myself off nicotine. I have designed a rough 3D model of the box, which I can 3D print so now I'm looking at the electronics.
**TL;DR:** A box which stays locked for longer, every time it locks.

Electronics: A microcontroller/Arduino/Pi to increase the locking duration; a locking circuit and some form of power supply.

My 2 questions are

1. Would the Arduino Uno be suited to this type of project?

2. What sort of components should I be looking for for the locking circuit and power supply (I'm thinking some sort of solenoid actuator and a battery pack)?

title: Would an Arduino Uno be suitable for a simple time-based locking circuit?

Answers: 2

body:
It is a great occasion to use the Arduino!

There are many tutorials for the Arduino out there, so thats a good place to start. This forum is a good place to ask any Arduino related question if you need to do so.

---

***The following contains MY OPINION***

In my opinion, an Arduino Nano would be great for this project. It is really user friendly and can pretty much accomplish many things. A Pro Mini would be better, but seeing sa you're a beginner, stick with the Nano.

A good long lasting batteRY would be a simple USB power bank. It outputs 5V and has a lot of juice. For a locking circuit, a simple servo would work **IF THE THINGS THAT IS IN THAT "SAFE" ISN'T 1M $$**. A servo does a decent job as a lock.

---

Good luck!

body:
Regarding your second question about what components to use, there are a couple arguments for a servo over a solenoid.

A solenoid in the energized state is relatively power hungry compared to a servo, which only requires any appreciable power while actually moving. Also, on power loss or interruption a servo fails as-is; a solenoid goes to the off position, which could cause an unwanted change of state for the lock.


body:
I'm attempting to use the pin labeled 'ADC7' from the Atmega328p TQFP package. The Atmega documentation suggests that can be used either as an analog or digital I/O point. I'm trying to configure it as a digital output.

Referencing the documentation (and specifically arduino_pins.h), I determined the associated pin number was 21. Thus I called pinMode(21, OUTPUT). However, this pin does not appear to be working with my SPI device. I previously tested that the device worked, but I made a last second change of pin and am now using ADC7.

So my question, is there an additional step required to configure this pin as a digital output? I noticed that this pin doesn't exist on the DIP Atmega328p (used on the Arduino Uno), so I'm not sure if I have to add another line of code somewhere.

Any ideas?

Regards,

title: How do you configure ADC7 on the Arduino Pro Mini as a digital output?

Answers: 5

body: Those are analog pins only. They can't be used as outputs or digital inputs.

body:
Gerben's answer probably is correct, but there are some interesting discrepancies in Atmel datasheets for various models of the ATmega168 and ATmega328, as outlined below.

Some Atmel datasheets refer to ADC6 and ADC7 as PE2 and PE3, while others just refer to them as ADC6 and ADC7.

Regarding port E, the 2014 ATmega168PA and 2015 ATmega168 datasheets say nothing, don't list any of PE0 to PE3, and don't specify port membership for ADC6 and ADC7.  They show pins 3 and 6 on the LQFP as Gnd and Vcc, vs PE0 and PE1 as in the ATmega168PB sheet.

Regarding port E, the 2015 ATmega168PB datasheet says:

    Table 15-12.  Port E Pins Alternate Functions
         Port Pin       Alternate Function
           PE3          ADC7 (ADC Input Channel 7)
           PE2          ADC6 (ADC Input Channel 6)
           PE1          NONE
           PE0          ACO (AC Output Channel 0)

Regarding port E, the 2016 ATmega168PB datasheet, Atmel-42176G-ATmega48PB/88PB/168PB_Datasheet_Complete-03/2016, says the following
and also lists several Alternate Functions while referring to
Timer/Counters 3 and 4 (although there seem to be no registers in the
register summary relevant to such Timer/Counters):

"Port E is an 4-bit bi-directional I/O port with internal pull-up
resistors (selected for each bit). The Port E output buffers have
symmetrical drive characteristics with both high sink and source
capability. As inputs, Port E pins that are externally pulled low will
source current if the pull-up resistors are activated. The Port E pins
are tri-stated when a reset condition becomes active, even if the clock is not running."

    Table 19-12.  Port E Pins Alternate Functions
     Port Pin            Alternate Function
     PE3                 ADC7 (ADC Input Channel 7)
                         T3 (Timer/Counter 3 External Counter Input) & PCINT27
     PE2                 ADC6 (ADC Input Channel 6)
                         ICP3 (Timer/Counter3 Input Capture Input)
                         SS1 (SPI1 Bus Master Slave select) & PCINT26
     PE1                 T4 (Timer/Counter 4 External Counter Input)
                         SCL1 (2-wire Serial1 Bus Clock Line) & PCINT25
     PE0                 ACO (AC Output Channel 0)
                         ICP4 (Timer/Counter4 Input Capture Input)
                         SDA1 (2-wire Serial1 Bus Data Input/Output Line) & PCINT24

body:
According to everything you can find in [the datasheet](http://www.atmel.com/Images/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_Datasheet.pdf) about ADC6 and ADC7 they are analog only pins.

The pinout for the TQFP-32 as used on the Pro Mini shows those two pins as *only* having the analog functions:

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

I suspect the color coding of the pins may be wrong - they should be solid green. They have no port names on the pins, purely the ADCx designation.

The block diagram for the chip shows the ADC6/7 pins being separate from a port:

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

As you can see the other 6 pins are referred to by the digital port they share, but ADC6 and 7 are known purely as ADC6 and ADC7.

The pin function table, 6-1, shows ADC6 and ADC7 as the only functions on those pins. No digital port names, nothing - just purely analog input.

So in summary, for the ATMega328P chip used in the Arduino Pro Mini you cannot use those two pins for digital at all, only for analog input.

  [1]: https://i.stack.imgur.com/NVdFq.png
  [2]: https://i.stack.imgur.com/y2nqK.png

body: This may be a little left field, but I use the ADC6 and ADC7 inputs to detect switches.  I just don't use the digitalRead() function, but instead use analogRead() function.  Using a resistor network and switches and some decoder software code in our sketch, we can use a single input pin to interface with many more switches.  The switches can only be on one at a time, but in many instances, this would be OK.

body:
I appreciate this is an old question but those pins are subtly different on the ATMEGA328PB compared to the ATMEGA328P which I discovered recently. See the Microchip app note AT15007, page 3.

[Microchip AT15007 app note][1]

  [1]: http://ww1.microchip.com/downloads/en/Appnotes/Atmel-42559-Differences-between-ATmega328P-and-ATmega328PB_ApplicationNote_AT15007.pdf


body:
At the moment I am using a separate function to display byte arrays like these:

    const PROGMEM unsigned char arab4[] = {
      0x00, 0x00, 0x00, 0x00,
      0xf0, 0xff, 0xff, 0x01,
      0xf8, 0xff, 0xff, 0x01,
      0xf8, 0xff, 0xff, 0x00,
      0x04, 0xf8, 0x0f, 0x00,
      0x00, 0x7c, 0x00, 0x00,
      0x00, 0x0e, 0x00, 0x00,
      0x80, 0x03, 0x00, 0x00,
      0xc0, 0x01, 0x00, 0x00,
      0x60, 0x00, 0x00, 0x00,
      0x20, 0x00, 0x00, 0x00,
      0x10, 0x00, 0x00, 0x00,
      0x18, 0x00, 0x00, 0x00,
      0x08, 0x10, 0x06, 0x00,
      0x0c, 0x70, 0x0f, 0x00,
      0x04, 0xf8, 0x0f, 0x00,
      0x04, 0x78, 0x06, 0x00,
      0x06, 0x20, 0x00, 0x00,
      0x06, 0x80, 0x00, 0x00,
      0x06, 0xc0, 0x01, 0x00,
      0x06, 0xc0, 0x03, 0x00,
      0x0e, 0xe0, 0x01, 0x00,
      0x1c, 0x80, 0x01, 0x00,
      0x1c, 0x00, 0x00, 0x00,
      0x7c, 0x00, 0x00, 0x00,
      0xf8, 0x00, 0x00, 0x00,
      0xf0, 0x07, 0x00, 0x00,
      0xe0, 0x7f, 0x00, 0x3c,
      0xc0, 0xff, 0xff, 0x0f,
      0x00, 0xff, 0xff, 0x01,
      0x00, 0xf0, 0x1f, 0x00,
      0x00, 0x00, 0x00, 0x00};

My function for displaying uses Adafruit libraries

    #include <RGBmatrixPanel.h>
    #include <Adafruit_GFX.h>

Finally my Function:

    void xbm32_n (const PROGMEM unsigned char bild[32],word cchsv) {

    int i = 0;
    while(i<32){

        for(int k=4*i;k<(4+4*i);k++)
        {

        for(int ii = 0; ii<8; ii++){

           int bit = ((pgm_read_byte(&(bild[k]))) >> ii) & 1;
           if(bit == 1) { matrix.drawPixel(ii+8*k-4*8*i, i, cchsv);}}}

       i++   ;
        }
       }
The inner workings are as follows:

The function draws each 32 bit row with the color chosen on the Panel depending on the 4 bytes in each "row" of the hex array.

Essentially 2 loops *(to draw the row in byte increments)* with outer while loop *(to move to next row)*.
The calculation of the *pixel positions* can be seen inside the `matrix.drawPixel(x-pos,y-pos,color-value)` Adafruit-function, and were made up by experimenting long hours.

See for the whole .ino File [here](https://www.dropbox.com/s/tnrt9iq6dunaon4/sketch_led32-painter.ino?dl=0)

**Notes on the file**

---
It also features among others

> *(like a displaying shifting 8x8 symbol-array saved in `const PROGMEM byte IMAGES2[][8]` used in the function `bildlauf(1,...)`*

an updated function `void xbm32_4c(char bild[32],word* cchsvar[4], int duration,int cseq[4]))` where:

 - `word* cchsvar[4]` points to four color data values

 - `cseq[4]` is the sequence for displaying the colors in each panel
   quadrant

The subdivision of the panel is realized via `if()` and `else if()` commands checking the conditions for positions:

`x = (ii+8*k-4*8*i) </>` *some value*
 *&&* `y = i </>` *some value*

---

**Function input:**

 - `bild[32]` is used for the hex array as in my case `arab4[]`
 - `cchsv` is a color data value . I am using sparkfun 32 LED Matrix and
   found the following function for hsv color space to work well:

          word hsvcolor(int h, int s, int b ) { //Try HSV colors http://colorizer.org/
          int hue1, sat1, bright1;
          word result;

          hue1=map(h, 0, 360, 0, 1535);
          sat1=map(s, 0, 100, 0, 255);
          bright1=map(b, 0, 100, 0, 255);
          result = matrix.ColorHSV(hue1,sat1,bright1,true);

          return result;
        }

**Current Issues to solve:**

I am using Font Forge to create XBM Files in helping me create the hex letter array, but found it very clumsy to export, as the width size must be a multiple of eight to adjust height by deleting 0x00 rows.

At the moment I am searching for easier ways to "correct" the exported XBM arrays (like using 8x8 Editor [8x8 Editor](http://xantorohara.github.io/led-matrix-editor/), only for 32x32 Matrices).
Is there a possibility for this?

Alternatively it would also help to create a function to truncate hex arrays to fit 32x32 dimensions somehow.

Additionally, in Arabic there is the issue of variant glyphs for the different letter positions (isolated, medial, initial, final). It seems possible to create byte arrays for all variants but "correcting" each bitmap so that a scrolling effect (I plan to upgrade to 64x32 LED Matrix) "adds up" visually seems daunting. I am happy for suggestion on realizing this challenge as well.

I am aware that there is a Adafruit function for bitmaps:
`void Adafruit_GFX::drawBitmap()`

I couldn't get it to work with my hex array, also the possibility on how to change quadrant colors or other subdivisions lead me to write my own version I modified from 8x8 Panel case. I am not sure whether there are inefficiencies in the code I have written, I therefore am happy for suggestions.

title: 32x32 RGB-LED Matrix displaying Arabic Font with Font Forge more easily

Answers: 1

body:
The solution to creating Arabic characters with typographic ligature and scrolling them, is:

 Using the application _RTB RichText to Bitmap_ :

 1. Set width-size of bitmap in increments of 32*n while using a height
        initially bigger than 32
 _(saving the bmp will allow for cropping of rows so that bigger letters can be produced, a bit offset to fit height 32)_

 1. Saving the bmp and editing it _(take care that bitmap rows are saved in rows, if not switch scanning line mode)_

 Also the byte    endian for output must be rightly chosen: _("Lsb" for pc-editing, uploading to    arduino for use in the function provided [here](https://www.dropbox.com/s/gwigwdbofgksi6t/sketch_led32-64-painter-finally-2.ino?dl=0), it is in
        "Msb")_

 The cropped characters bitmap must be then reloaded into RTB Pixel Editor on a fitting canvas (generate an empty one) and set to a different scanning mode (rows now in columns) with byte endian Msb

 2. Group the array of hex elements in pairs of four (you can use
    notepad++ and
 _regex find:_
    `(((0[xX][0-9a-fA-F,]{2})[,]){3}((0[xX][0-9a-fA-F,]{2})))`

    _replace:_ `{/1}`

Using a suiting arduino scrolling [function](https://www.dropbox.com/s/gwigwdbofgksi6t/sketch_led32-64-painter-finally-2.ino?dl=0) (on top of adafruit    libraries)

 1. Insert 32x(4_hex) chunks of your bitmap data in the file provided
    above as array element in:
 `const PROGMEM unsigned char
    I[][32][4]= {{here},{here},...,{here}}`

 2. Adjust _main loop_ code for scrolling direction (here r to l) via increment or
    decrement and number of scrolls (panel-size is here chosen 32):

    `int es=64; while (es>0) {   scroller01(I,32,dpink,es,go);   --es; }`

 3. Verify if you need to load a chunk of your bitmap group to `const
    PROGMEM unsigned char I[][32][4]` , so that scrolling is fluid and
    does not jump when the arduino re-cycles

The Question got solved in detour via another question  in this exchange (see  [here](https://arduino.stackexchange.com/questions/34328/on-extending-scrolling-8x8-bitmap-to-32x32-or-32x64-see-clip) ). I am answering it to resolve parts of it.

The scrolling is slow when extended fully onto 64x32 Panels with arduino Mega 2560.

For a clip see:
>!  www.dropbox.com/s/qth8iuygra1wx9b/VID-20170210-WA0000.mp4?dl=0

 If somebody comes up with a more efficient,faster way, please do share!


body:
I have this simple that is supposed to keep a log for me with a fixed number of entries. When I add to the log the oldest replaced is by the second oldest etc and the new entry added. Except when I add another entry both that and the one before have the same value (My C isn't any good, I'm more a ruby and lua guy).

What am I doing wrong here?

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

    #define log_size 5
    #define line_height 12
    char *log_lines[log_size] = {"Hello", "World"};

    void addToLog(char *text) {
      for(int i = log_size - 1; i > 0; i--) {
        log_lines[i] = log_lines[i-1];
      }
      log_lines[0] = text;
    }

    void printLog() {
      for(int i = 0; i < log_size; i++) {
        Serial.print(i);
        Serial.print(" ");
        Serial.println(log_lines[i]);
      }
    }

    void loop(void)
    {
      char msg[20];
      sprintf(msg, "%d", millis());
      addToLog(msg);
      printLog();
      delay(1000);
    }

The output after the first addToLog is

    0 1000
    1 Hello
    2 World

second addToLog is

    0 2001
    1 2001
    2 Hello
    3 World

title: Push to 2D array (log) but last value pushed is everywhere

Answers: 2

body:
It is easy - in your log you store POINTERS to strings.

And you then create variable on the stack (ouch) and put its address to the log.

Then you leave the function (loop) (so that variable is forgotten and can be overwritten by anything). I will not say it is luck, that nothing uses the stack enought to make a problem before the loop is called again, as it disguise the problem. The POINTER in log_lines[0] points to UNALLOCATED place (where the variable msg once was).

Then the loop allocates variable msg (at the same place, as its previous run by the chance) so the POINTER stored in log_lines[0] (still pointing to the same place) points to the variable msg (and its content). By pure (bad) luck.

Then you overwrite the variable msg with a new value, so the log_lines[0] point to that new value.

Then you move the content of log_lines up, so the log_lines[1] now points to the variable msg (and its NEW value) as well as log_lines[0].

Then you assign log_lines[0] with address of variable msg (which it accidetally already contains)

Then you wonder, why variable msg accesed via log_lines[1] is exactly same as the (same) variable msg accesed vial log_lines[0] and why it contains the last (NEW) value, which you assigned into it.

---

Some of possible solutions are:

1) allocate place on heap (memaloc it) in the addToLog function, copy the text into it and store pointer to THIS place (and do not forget deallocate   last log_lines before overwriting it - if it is not null (as untinitialized values are all 0)) which could lead to (relativelly) expensive heap manipulations and possible memory fragmentation.

2) allocate log_lines as array of char arrays of given len, copy the content of each line in another loop inside addToLog and then copy(and possibly truncate) the text to the log_line[0]

3) keep static index of last used log_line and in addToLog just increment it (wrapping around the len of the array), then overwrite the line pointed by index with (truncated) text and in printLog just start cycle on the index and climb (wrapping around len of the array) until you are again at index (which you would not print again and stop)

body:
Here is a solution which does not use dynamic allocation nor does it
copy any log message. It's essentially a zero-copy implementation of
gilhad's solution 3. The idea is: instead of having an `addToLog()`
function that takes an already prepared message (which it would need to
copy), you have a `get_log_buffer()` function that tells you where to
write the message in the first place. This way you can `snprintf()`
directly into the right place in memory.

    const size_t LOG_SIZE = 5;
    const size_t MSG_SIZE = 20;

    char log_stack[LOG_SIZE][MSG_SIZE];  // circular log buffer
    size_t log_index;  // next available slot in the circular buffer

    // Return the address of the next available message slot.
    char *get_log_buffer()
    {
        char *buffer = log_stack[log_index];
        if (++log_index == LOG_SIZE) log_index = 0;  // increment index
        return buffer;
    }

    void print_log()
    {
        Serial.println(F("--------"));
        for (size_t i = 0, j = log_index; i < LOG_SIZE; i++) {
            j = (j ? j : LOG_SIZE) - 1;  // decrement index
            if (log_stack[j][0]) {  // should be a non-empty message
                Serial.print(i);
                Serial.print(" ");
                Serial.println(log_stack[j]);
            }
        }
    }

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

    void loop()
    {
        snprintf(get_log_buffer(), MSG_SIZE, "%lu", millis());
        print_log();
        delay(1000);
    }

Note that `log_stack` and `log_index` are zero-initialized by the C
runtime. Note also the use of `snprintf()` instead of `sprintf()` in
order to avoid buffer overruns.


body:
I have made a button with an LED using an arduino micro. It's connected to my pc and when I hit the button, the LED activates and a recording on Reaper (digital audio workstation) is started. When I hit the button again, the LED turns off and the recording stops and is saved.

I want the LED to flash at the BPM rate of the project in Reaper. So it needs to read the amount of Beats per minute the project is set to.

Is there any way the arduino can read this value?
Without the flashing LED, the program works fine. Here's the code:

    #include <Keyboard.h>

    boolean toggle = false;
    int inPin = 2;
    int outPin = 3;

    int state = HIGH;
    int ledOn;
    int reading;
    int previous = LOW;

    long time = 0;
    long debounce = 200;

    void setup() {
      // make pin 2 an input and turn on the
      // pullup resistor so it goes high unless
      // connected to ground:
      pinMode(inPin, INPUT_PULLUP);
      pinMode(outPin, OUTPUT);
      Keyboard.begin();
    }

    void loop()
    {
      reading = digitalRead(inPin);
      ledOn = digitalRead(outPin);

      // if the input just went from LOW and HIGH and we've waited long enough
      // to ignore any noise on the circuit, toggle the output pin and remember
      // the time
      if ((reading == LOW) and (ledOn == LOW)) {
        state = HIGH;
        Keyboard.press((char) 128);
        Keyboard.press('r');
        delay(50);
        Keyboard.releaseAll();
        delay(300);
      }

      if ((reading == LOW) and (ledOn == HIGH)) {
        state = LOW;
        Keyboard.press((char) 32);
        delay(10);
        Keyboard.releaseAll();
        delay(100);
        Keyboard.press((char) 177);
        delay(10);
        Keyboard.releaseAll();
        delay(300);

        time = millis();
      }

      digitalWrite(outPin, state);

      previous = reading;
    }

title: Get data from a running exe on my pc

Answers: 0


body:
The Arduino documentation provides two examples to store data in the EEPROM.

https://www.arduino.cc/en/Reference/EEPROMPut stores data in the EEPROM and the EEPROMGet example reads the data back and writes it out.

These examples work fine on my Arduino Uno, but on my ESP8266 (NodeMCU) the EEPROMGet example code is unable to retrieve the data EEPROMPut should have stored previously. Instead it's just returning some random bits and bytes.

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

Any ideas? I haven't found anything about known incompatibilities related to the ESP8266 boards...

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

title: EEPROM put and get not working on ESP8266 (NodeMCU)

Answers: 2

body:
The ESP8266 doesn't have any EEPROM. Instead it emulates it using Flash.

In order not to wear out your flash you have to "commit" changes to the flash once they have been queued for writing - otherwise they will be lost.

Instead of using the Arduino examples you should be using the ESP8266 specific examples included with the ESP8266 EEPROM emulation library (but also [here]( https://github.com/esp8266/Arduino/tree/master/libraries/EEPROM/examples)).

body:
**EEPROM for the ESP8266/NodeMCU**

This is a bit different from standard EEPROM class for Arduino. You need to call `EEPROM.begin(size)` before you start reading or writing, size being the number of bytes you want to use. Size can be anywhere between 4 and 4096 bytes.

`EEPROM.write` does not write to flash immediately, instead you must call `EEPROM.commit()` whenever you wish to save changes to flash. `EEPROM.end()` will also commit, and will release the RAM copy of EEPROM contents.

EEPROM library uses one sector of flash located just after the SPIFFS.


body:
I have an Arduino Mega clone and I haven't used it for a while. I remember it not working so when I plugged it in and tried uploading the code to it and sure enough it didn't work. So I plugged in an Uno and it worked. The Mega is a 2560 Atmel. Here's my code:
<!-- language-all: lang-cpp -->

    #define distanceForward A0
    #define distanceLeft A1
    #define distanceRight A2
    #define distanceRightAngle A3
    #define distanceLeftAngle A4
    #define distanceBack A5
    int talk = 2;

    void setup() {
      Serial.begin(9600);
      pinMode(talk, OUTPUT);
      pinMode(distanceForward, INPUT);
      // /\ Ir distance sensor pin for input signal to arduino, Front Facing
      pinMode(distanceLeftAngle, INPUT);
      // /\ Ir distance sensor pin for input signal to arduino, Left Angle
      pinMode(distanceRightAngle, INPUT);
      // /\ Ir distance sensor pin for input signal to arduino, Right Angle
      pinMode(distanceLeft, INPUT);
      // /\ Ir distance sensor pin for input signal to arduino, Left
      pinMode(distanceRight, INPUT);
      // /\ Ir distance sensor pin for input signal to arduino, Right
      pinMode(distanceBack, INPUT);
      // /\ Ir distance sensor pin for input signal to arduino, back
    }

    void hall_roam() {
      Serial.write("forward");
      if (analogRead(distanceLeftAngle) < 30) {
        Serial.write("right");
        if (analogRead(distanceLeftAngle) > 30) {
          Serial.write("forward");
        }
        if (analogRead(distanceRightAngle) < 30) {
          Serial.write("left");
          if (analogRead(distanceRightAngle) < 30) {
            Serial.write("forward");
          }
          if (analogRead(distanceForward) < 60) {
            Serial.write("stop");
            if ((analogRead(distanceLeft) < 60) && (analogRead(distanceRight) < 60)) {
              Serial.write("left");
              if (analogRead(distanceForward) > 60) {
                Serial.write("stop");
              }
            }
          }
          if ((analogRead(distanceLeft) > 60) && (analogRead(distanceRight) > 60)) {
            Serial.write("left");
            if (analogRead(distanceForward) > 60) {
              Serial.write("stop");
            }
          }
          if ((analogRead(distanceLeft) > 60) && (analogRead(distanceRight) < 60)) {
            Serial.write("left");
            if (analogRead(distanceForward) > 60) {
              Serial.write("stop");
            }
          }
          if ((analogRead(distanceLeft) > 60) && (analogRead(distanceRight) < 60)) {
            Serial.write("left");
            if (analogRead(distanceForward) > 60) {
              Serial.write("stop");
            }
          }
          if ((analogRead(distanceLeft) < 60) && (analogRead(distanceRight) > 60)) {
            Serial.write("right");
            if (analogRead(distanceForward) > 60) {
              Serial.write("stop");
            }
          } else {
            Serial.write("forward");
          }
        }
      }
    }

    void roam() {
      Serial.write("forward");
      if (analogRead(distanceForward) < 60) {
        Serial.write("stop");
        Serial.write("left");
        if (analogRead(distanceForward) > 60) {
          Serial.write("stop");
          Serial.write("forward");
        }
      }
    }

    void talkbb8() {
      pinMode(talk, HIGH);
      pinMode(talk, LOW);
    }

    void chill() {
      Serial.write("stop");
      talkbb8();
    }

    void loop() {
      if ((analogRead(distanceLeft) < 60) && (analogRead(distanceRight) < 60)) {
        hall_roam();
      } else if ((analogRead(distanceForward) < 60) && (analogRead(distanceBack) < 60)) {
        Serial.write("left");
        if ((analogRead(distanceLeft) < 60) && (analogRead(distanceRight) < 60)) {
          Serial.write("stop");
          hall_roam();
        }
      } else {
        roam();
      }
    }

If there's a bracket out of place or something it's probably nothing. I'm talking about the characters. Is there anything in the characters that would screw up the upload like the three "!!!" problem I heard about or something like that. It's possible that the USB chip in it isn't recognized by my iMac. If so how do I fix that?

title: Why do I get avrdude: stk500v2_ReceiveMessage(): timeout error when uploading to Arduino Mega?

Answers: 5

body:
The error message basically means that the programmer is unable to contact the `boot-loader` on the device. The code you're trying to upload has no bearing on the problem.

There could be one of the four possible reason behind it. They are:

 1. Wrong Port Selected:

    If `TX/RX` led is not blinking, then you may have selected wrong port. If one of both of them are blinking then, you aren't using the wrong port. It might be worth checking again though, sometimes USB COM devices install on strange port numbers.

 2. Board is not in `Bootloader` Mode:

    The `Arduino Mega` is not executing the `bootloader` for some reason. If the programmer is not resetting the micro before attempting to connect, this might be the reason. Try to reset the board (press and release the button) while the programmer is attempting to connect. Sometimes software that runs in a tight loop will prevent the `bootloader` from connecting.
Barring that, the fuses might have gotten messed up or the code erased. You would need to reflash the bootloader and proper fuses, again, see the appropriate info page for your device.

 3. Arduino Mega 2560 only: ATmega8U/16U software

    Might not be working and would need reprogramming. See the Programming section on the info page, you will need the firmware and Atmel-compatible DFU (device firmware update) software on your computer to` reflash` the target.

 4. Hardware damage:

    There could be hardware damage to the board, AVR(s), or FTDI chip. Time to buy another board.

You can check this [answer][1].

  [1]: https://stackoverflow.com/questions/19645441/avrdude-stk500v2-receivemessage-timeout

body:
If you have a timeout issue please ensure the crystal used on board is 16 Mhz.

change

    mega.menu.cpu.atmega2560.upload.protocol=wiring
To:

    mega.menu.cpu.atmega2560.upload.protocol=stk500v2

I had this problem after changing crystal value and changing parameters solved the above problem.

body:
I tried all the solutions listed on this page:

- changed ports,
- checked correct port on Arduino IDE,
- restarted,
- reconnected,
- bought a new arduino mega,
- etc.

Nothing worked.

Finally gave up and used the web version of the Arduino IDE and it worked just fine.

body:
If you have a timeout issue please ensure the crystal used on board is 16 Mhz.

change

mega.menu.cpu.atmega2560.upload.protocol=wiring
To:

mega.menu.cpu.atmega2560.upload.protocol=stk500v2

Thank you!
Solved my problem!

body:
I had the same issues on MAC OSX El Capitan (older iMAC) using IDE 1.8.x and of course JAVA performed an update.  I regressed the Arduino AVR drivers to 1.6.21 (as instructed online) and this did not resolve the Timeout errors.

I gave up and used IDE 1.8.9 on my OSX MB Pro, and it worked flawlessly.

I think that Java versions and IDE drivers were the issue.


body:
I need to capture a single parallel 'snapshot' from a 10-bit shaft encoder. I understand that I can read individual bits and shift them into position, but any given input pin might change while reading the bits sequentially, which would give an bogus value. In fact, given the asynchronous nature of the device this is guaranteed to happen on occasion.

I've read hints that it might be possible to combine pins into a 'port' for this purpose but I can't find any examples. Is this ability available only on certain processors? Or is there some way to latch the input pins while scanning them into a pair of bytes, to avoid them changing while I read?

If not I suppose I could use external latches but I'm hoping to avoid additional hardware.

It did occur to me that I could sync readings using an ISR triggered by a change in the LSB, but alas, this encoder outputs Gray code. :(

title: Reading multiple DI pins in parallel as one byte/word

Answers: 4

body:
Without knowing the encoder in question (which you seem extremely reluctant to disclose for some reason that I have trouble understanding) it is hard to give a good answer. However ...

---

The 8-bit AVR processors can only read 8 bits atomically. This is indeed called a port. The Atmega328P (used in the Uno) organizes its I/O ports as ports B, C and D (I don't know where A went).

Exposed on the board are PORTB (bits 0 to 5), PORT C (bits 0 to 5) and PORT D (bits 0 to 7) - that's 20 pins in total.

Thus, port D is the closest you will get, as you could read 8 bits at once. However having said that, two of those bits are used for serial I/O so you couldn't use the serial hardware at the same time.

To read all of port D you could just do this:

    byte foo = PIND;

(For inputting it is PINx, for outputting it is PORTx).

---

What could help is an I/O expander such as the MCP23017.

> I'm hoping to avoid additional hardware

Well, that's a pity.

---

I'm a tiny bit surprised that the device doesn't support some sort of "latching" of the data which gives you a finite time to extract the information from it. However without reading the datasheet I can't comment further.

body:
If you would like to read multiple inputs, you can access port register directly. For 8 bit AVR:

    DDRA = 0;            // set pins A0-A7 as input, modeInpit() in Arduino
    uint8_t data = PINA; // read all A0-A7 inputs (8 bits)

To read more than 8 bits, you need 32 bit ARM based MCU/board like Arduino Due, other Atmel SAM, STM32Fxxx MCU etc. For STM32, there is Arduino like IDE available - [http://www.stm32duino.com/][1]

Even on 32 bit MCU you can read only 16 GPIO simultaneously (GPIO registers are 32 bit but handles 16 GPIO).

  [1]: http://www.stm32duino.com/

body:
I mean, *you could* look up the port and the pin in the port and read in the portByte. This example does work:

    //given two GPIOs on a port(PortC) eg: 12(right button) & 13(left button)
    byte portByte = (*portInputRegister(digitalPinToPort(rightButtonGpio)));
    rightButtonPinHigh = portByte & (digitalPinToBitMask(rightButtonGpio));
    leftButtonPinHigh = portByte & (digitalPinToBitMask(leftButtonGpio));

However, in my experience, your output will look pretty much the same as if you had done two sequential Arduino blessed `digitalRead`. I suppose you might (in the example above) get the leftButtonHigh value 1 instruction ealier, but I don't know if the register can even update at that resolution.

body:
I'm sure time has already passed for this persons project. But for those visiting this page for whatever reason (mine was different than the information here) here is a solution I would implement. Also this is assuming the individual is not willing to use a latched external buffer where they can read from it however they need to. Simply split the total pins among 2 registers making sure the following
1. The pins used are in sequential order to both the MCU and the encoder (gray coding will require some thought to this).
2. Group as many on a single register as possible and this will be the low order value.

Read from the low order value first (the one that will be changing at the highest rate). Then read from the high order value (where it will be far less likely to change between the low order and the high order read). You need to understand bit masks and bit shifting to do this...

uint16_t nEncoder = (PINB & 0x1F);   // Example if your 5 pins are the low ones on PORTB

uint16_t nEncoder = ((PINB & 0x7C) >> 2);  // Example if your 5 pins are 6:2 where you pull your set of pins off of PORTB then bitshift them down into their proper place.

then you read in the high order part

nEncoder |= ((PIND & 0x1F) << 5);  // Example if your 5 pins are the low ones on PORTD. However you pull them off of the next port, you will need to make sure you bitshift them into the upper 10 bits of nEncoder to get your final value.

In the above, you can see that the more bits (pins) you can use on your first register (port), the less likely your second read will have a pin change.

Gray coding will be different than binary. The above example assumes binary where the high order bit will change the least and the low order the most. Gray coding is specifically used because of how minimally the bits change in-between each number change (i.e. they are suppose to only have 1 bit change per number change no matter the number rather than 10 bits change when a binary count rolls over - i.e. it minimizes this exact problem). So for the original poster, most of this should be irrelevant (since they said they were using a gray code encoder).

But for those seeking an optimal solution (for binary counters or just because) where they cannot stick all pins on a single port. Splitting it between two registers with only two reads will optimize your read time and minimize the pin change possibility.