body:
I'm making alarm with input from pulse sensor. When it detect high heart rate then it send a text message. Everything works fine when i am using potentiometer (as input) for simulating triggering SMS. I made several heart rate trigger options based on ages, so i'm using switch-case in my loop. I'm using PulseSensor Playground library and some sample skecth that came from with it, but when i put program that read beat per minute and put that value inside if statement it become doesn't work at all. Even if i put the BPM value to serial monitor it only display 0. What can i do to fix this problem? Thanks

Here is my program:

    #define USE_ARDUINO_INTERRUPTS true
    #include <PulseSensorPlayground.h>
    #include <SoftwareSerial.h>
    #include <JC_Button.h>

    const int OUTPUT_TYPE = SERIAL_PLOTTER;
    const int PulseSensor = A0;
    const int THRESHOLD = 550;

    PulseSensorPlayground pulseSensor;
    SoftwareSerial SIM800L(2, 3);  //(RX | TX)
    const byte switchButton = 4;
    int LED1 = 5;   //ages range 1
    int LED2 = 6;   //ages range 2
    int LED3 = 7;   //ages range 3
    int greenLED  = 8;    //for normal heart rate
    int yellowLED  = 9;   //for medium heart rate
    int redLED = 10;      //for high heart rate

    Button mybutton(switchButton);
    boolean SMSsent = false;
    int x = 0;

    void setup(){
      mybutton.begin();
      pinMode(LED1, OUTPUT);
      pinMode(LED2, OUTPUT);
      pinMode(LED3, OUTPUT);
      pinMode(greenLED, OUTPUT);
      pinMode(yellowLED, OUTPUT);
      pinMode(redLED, OUTPUT);

      Serial.begin(115200);
      pulseSensor.analogInput(PulseSensor);
      pulseSensor.setSerial(Serial);
      pulseSensor.setOutputType(OUTPUT_TYPE);
      pulseSensor.setThreshold(THRESHOLD);

      SIM800L.begin(115200);
      Serial.println("SIM800L ready");
    }

    void led_for_ages_range_1(){
      digitalWrite(LED1, HIGH);
      digitalWrite(LED2, LOW);
      digitalWrite(LED3, LOW);
    }
    void led_for_ages_range_2(){
      digitalWrite(LED1, LOW);
      digitalWrite(LED2, HIGH);
      digitalWrite(LED3, LOW);
    }
    void led_for_ages_range_3(){
      digitalWrite(LED1, LOW);
      digitalWrite(LED2, LOW);
      digitalWrite(LED3, HIGH);
    }

    void led_indicator_1(){
      digitalWrite(greenLED, HIGH);
      digitalWrite(yellowLED, LOW);
      digitalWrite(redLED, LOW);
    }
    void led_indicator_2(){
      digitalWrite(greenLED, LOW);
      digitalWrite(yellowLED, HIGH);
      digitalWrite(redLED, LOW);
    }
    void led_indicator_3(){
      digitalWrite(greenLED, LOW);
      digitalWrite(yellowLED, LOW);
      digitalWrite(redLED, HIGH);
    }

    void range_1_indicator(){
      int BPMval = pulseSensor.getBeatsPerMinute();

      if (BPMval > 60 && BPMval < 85){
        led_indicator_1();
        SMSsent = false;
      }
      else if (BPMval > 86 && BPMval < 100){
        led_indicator_2();
        if(SMSsent == false){
          text_message_1();
          SMSsent = true;
        }
      }
      else if (BPMval > 101){
        if(SMSsent == false){
          text_message_2();
          SMSsent = true;
        }
      }
      else {
        SMSsent = false;
      }
    }

    void range_2_indicator(){
      int BPMval = pulseSensor.getBeatsPerMinute();

      if (BPMval > 60 && BPMval < 75){
        led_indicator_1();
        SMSsent = false;
      }
      else if (BPMval > 76 && BPMval < 90){
        led_indicator_2();
        if(SMSsent == false){
          text_message_1();
          SMSsent = true;
        }
      }
      else if (BPMval > 91){
        if(SMSsent == false){
          text_message_2();
          SMSsent = true;
        }
      }
      else {
        SMSsent = false;
      }
    }

    void range_3_indicator(){
      int BPMval = pulseSensor.getBeatsPerMinute();

      if (BPMval > 60 && BPMval < 70){
        led_indicator_1();
        SMSsent = false;
      }
      else if (BPMval > 71 && BPMval < 80){
        led_indicator_2();
        if(SMSsent == false){
          text_message_1();
          SMSsent = true;
        }
      }
      else if (BPMval > 81){
        if(SMSsent == false){
          text_message_2();
          SMSsent = true;
        }
      }
      else {
        SMSsent = false;
      }
    }

    void text_message_1(){
      int BPMval = pulseSensor.getBeatsPerMinute();
      SIM800L.write("AT+CMGF=1\r");
      delay(100);
      Serial.println("SIM800L set destination number.");
      SIM800L.write("AT+CMGS=\"0123456789\"\r");
      delay(100);
      Serial.println("Sending text message...");
      SIM800L.write("Your heart rate are: ");
      SIM800L.write(BPMval);
      SIM800L.write(" BPM");
      SIM800L.write("\r");
      Serial.println("Your heart rate are: ");
      Serial.print(BPMval);
      Serial.println(" BPM");
      SIM800L.write((char)26);
      delay(100);
      Serial.println("SMS sent.");
    }

    void text_message_2(){
      int BPMval = pulseSensor.getBeatsPerMinute();
      SIM800L.write("AT+CMGF=1\r");
      delay(100);
      Serial.println("SIM800L set destination number.");
      SIM800L.write("AT+CMGS=\"0123456789\"\r");
      delay(100);
      Serial.println("Sending text message...");
      SIM800L.write("Warning! Your heart rate are: ");
      SIM800L.write(BPMval);
      SIM800L.write(" BPM");
      SIM800L.write("\r");
      Serial.println("Warning! Your heart rate are: ");
      Serial.print(BPMval);
      Serial.println(" BPM");
      SIM800L.write((char)26);
      delay(100);
      Serial.println("SMS sent.");
    }

    void loop(){
      //int BPMval = pulseSensor.getBeatsPerMinute();
      static enum {OPTION_ONE, OPTION_TWO, OPTION_THREE} condition;
      while (x == 0){
        mybutton.read();
        switch (condition){
          case OPTION_ONE:
          led_for_ages_range_1();
          range_1_indicator();
          if (mybutton.wasReleased()){
            condition = OPTION_TWO;
          }
          break;

          case OPTION_TWO:
          led_for_ages_range_2();
          range_2_indicator();
          if (mybutton.wasReleased()){
            condition = OPTION_THREE;
          }
          break;

          case OPTION_THREE:
          led_for_ages_range_3();
          range_3_indicator();
          if (mybutton.wasReleased()){
            condition = OPTION_ONE;
          }
          break;
        }
      }
    }

title: Problem with Pulse Sensor signal

Answers: 1

body:
You forgot `pulseSensor.begin()` and you don't use `pulseSensor.sawNewSample()`. See the examples of the library.

The library uses interrupts to measure the pulse. (It takes time, which would otherwise block the loop execution). The `begin()` function starts this interrupts.

The value measured by interrupts is accessible with `getBeatsPerMinute()` and `sawNewSample()` function indicates that new value is available.

The library can work without interrupts (PulseSensor_BPM_Alternative.ino), but even then the `begin()` function initializes the library and `sawNewSample()` is then the function which **reads** the sensor.


body:
I am not able to upload sketch because my Windows 8.1 PC is not able to recognise it. It used to work fine but suddenly my driver disappeared from my device manager and no light is shown on the Arduino uno led also.

I tried to uninstall and install the Arduino IDE again but still didn't work.

Note:- whenever I connect the USB cable to my PC, I see a dim light glowing for few milli seconds.

Update:- Also my Arduino board is not dead since it worked when connected to other pc but not working with my windows pc.

What could be the problem? How do I install the port driver back?

title: Problem with Arduino driver! Port option not visible. How to resolve it?

Answers: 3

body:
Sometimes Windows will disable a given USB port if it think's the attached device is malfunctioning.  Try using a different USB port on your PC.  If that does't work try
rebooting your PC.

body:
No LED = no power being supplied. That would imply a bad port, a bad cable, or a damaged board (open circuit due to a damaged trace or part).

A brief LED can mean the board was drawing too much current and the computer shut down that port to protect itself. That would imply a damaged board (short circuit due to burned out part, bad wiring if you have any on the board, or something conductive touching your board where it shouldn't (anywhere!).

Try substituting ports, cables, & Arduinos - one thing at a time - until something changes to give you a clue to what component is faulty.

You might also have a driver problem, but a good board/cable/port should power up anyway.

body:
Problem solved

I connected the arduino with my motor shield on top of it which stopped the power supply from pc. Now its working fine.


body:
Been working on this project for some time now, like title states when I un-comment `setSyncProvider(RTC.get)` in the setup the program fails to get any of the `Alarm.timerOnce` to run.

I have been stuck for a while and couldn't find anything while just googling so I thought I might enlist the minds of stack.

    #include <Wire.h>
    #include <TimeLib.h>
    #include <TimeAlarms.h>
    #include <DS1307RTC.h>  // a basic DS1307 library that returns time as a time_t

    //#define DS1307_I2C_ADDRESS 0x68 // the I2C address of Tiny RTC
    //byte second, minute, hour, dayOfWeek, dayOfMonth, month, year;

    int curPin = 7, //  Current sense (middle terminal) connected to analog pin A7
      prePin = 6,     //  Pressure sense (green terminal) connected to analog pin A6
      ignPin = 7,     //  Igniter output pin D7
      solPin = 8,     //  Solenoid output pin D8
      genPin = 9,     //  Generator output pin D9
      tonePin = 11,   //  Tone output pin D11
      ligPin = 3,     //  Light sense pin A3
      intPin = 3,     //  Interupt pin D3 runs double bang

      runTime = 20,   //  minutes to run for

      state = 0;      //  state of operation

    bool operate = false, // True if within operating time
       timeIsSet = false; // true if time till next opperation is set
    double cur;

    void setup() {
      Wire.begin();
      pinMode(13,OUTPUT);
      pinMode(ignPin, OUTPUT);
      pinMode(solPin, OUTPUT);
      pinMode(genPin, OUTPUT);
      Serial.begin(9600);
      //setSyncProvider(RTC.get);  //******************************************
      Alarm.alarmRepeat(dowMonday,7,30,0,OnAlarm);
      Alarm.alarmRepeat(dowTuesday,7,30,0,OnAlarm);
      Alarm.alarmRepeat(dowWednesday,7,30,0,OnAlarm);
      Alarm.alarmRepeat(dowThursday,7,30,0,OnAlarm);
      Alarm.alarmRepeat(dowFriday,7,30,0,OnAlarm);
      Alarm.alarmRepeat(dowSaturday,8,30,0,OnAlarm);
      Alarm.alarmRepeat(dowSunday,10,0,0,OnAlarm);
      Alarm.alarmRepeat(20,0,0,OffAlarm);
      tone(tonePin, 31, 1000);
      randomSeed(analogRead(0)); // nothing connected to 0 so read sees noise

      OnAlarm();
    }

    void loop() {
      if ((analogRead(ligPin) > 30) && operate == true)
      {
        if (timeIsSet == false)
        {
          tone(tonePin, 58, 500);
          int randm = random(27,36);
          Alarm.timerOnce(randm,operation);
          Serial.println(randm);
          timeIsSet = true;
        }
      }
      digitalClockDisplay();
      Alarm.delay(1000); // wait one second between clock display
    }

    void operation(){
      tone(tonePin, 100, 1000);
      Alarm.timerOnce(12,after20m);
      digitalWrite(genPin, HIGH);
    }

    void after20m(){
      digitalWrite(genPin, LOW);
      Alarm.timerOnce(5,after5s);
      digitalWrite(solPin, HIGH);
      tone(tonePin, 494, 1000);
      timeIsSet = false;
    }

    void after5s(){
      tone(tonePin, 200, 1000);
      digitalWrite(solPin, LOW);
      Alarm.timerOnce(1,after1s);
    }

    void after1s()
    {
      digitalWrite(ignPin, HIGH);
      Alarm.delay(500);
      digitalWrite(ignPin, LOW);
    }

    void OnAlarm() {
      operate = true;
    }

    void OffAlarm() {
      operate = false;
    }

    // Convert normal decimal numbers to binary coded decimal
    byte decToBcd(byte val)
    {
    return ( (val/10*16) + (val) );
    }
    // Convert binary coded decimal to normal decimal numbers
    byte bcdToDec(byte val)
    {
    return ( (val/16*10) + (val) );
    }

    void digitalClockDisplay() {
      // digital clock display of the time
      Serial.print(hour());
      printDigits(minute());
      printDigits(second());
      //Serial.print(operate);
      Serial.println();
    }

    void printDigits(int digits) {
      Serial.print(":");
      if (digits < 10)
        Serial.print('0');
      Serial.print(digits);
    }

title: TimeAlarms stops working when using setSyncProvider(RTC.get) DS1307

Answers: 1

body:
Problem existed in the TimeAlarms library,

    Q: How many alarms can be created?
    A: Up to six alarms can be scheduled.
    The number of alarms can be changed in the TimeAlarms header file (set by the constant
    dtNBR_ALARMS,
    note that the RAM used equals dtNBR_ALARMS  * 11)

so how I fixed it was to edit `#define dtNBR_ALARMS 6  // max is 255` to `#define dtNBR_ALARMS 14   // max is 255` in the `TimeAlarms.h` file.


body: Every time I try to upload code to my arduino I always get this error : avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x17. How do i fix it ?

Answers: 1

body:
Welcome to the community! I'm not able to comment yet so i'll answer here.
Try changing the connection to other USB port.
If that doesnt work check this question, the solutions can be similar (Juraj is right in the comments) :
[avrdude: stk500_getsync(): not in sync: resp=0x00," aka Some Dude Named Avr Won't Let Me Upload My Program][1]

Good Luck!

  [1]: http://"avrdude: stk500_getsync(): not in sync: resp=0x00," aka Some Dude Named Avr Won't Let Me Upload My Program


body:
I am investigating the use of a 3-position-switch for one of my projects to switch between different settings using just one analog input pin. For the three positions I am using ground/0V, ~2.5V (via 2x10k voltage divider) and full 5V. I am doing this also because I am planning to use a 5-position rotary switch in a similar way in the future.

Due to tolerances and noise, the readings on the analog pin are not precisely 0, 511, 1023, but rather 0-1, 509-512 and 1021-1023. To take this into account, I am using the `map` function like this:

 const byte alarmSwitchPin = A0;
 int alrmSwState;
 byte alrmSet;
 byte alrmPrevSet;

 void setup() {
   Serial.begin(9600);
   pinMode(alarmSwitchPin, INPUT);

 }

 void loop() {

   alrmSwState = analogRead(alarmSwitchPin);       // Read input

   byte alrmSet = map(alrmSwState, 0, 1023, 0, 2); // Boil input down to three cases

   if (alrmSet != alrmPrevSet) {                   // Only if state of switch has changed
  switch (alrmSet) {
    case 0:
   Serial.println("Low");
   break;
    case 1:
   Serial.println("Medium");
   break;
    case 2:
   Serial.println("High");
   break;
  }
  alrmPrevSet = alrmSet;
  delay(200);                                   // For testing purposes
   }
 }

I only want the setting to change (or, in this case, the console to print) when the state has actually changed. This does not work, though, because the `map` function is doing its math in integer, which fails in mapping the High position (in this case).

What are my options if I want to stick with the `switch` method? I am curious if it is possible to get this done without `if` statements and conditions or, as a more general question, what the best option is to properly map the 10 bit analog input to just 3 cases/numbers.

PS: I thought `analogReadResolution()` might be an option but I am working with Arduino UNO where this is unavailable.

title: How to boil down analog input to just three cases?

Answers: 4

body:
Replace the line:

  byte alrmSet = map(alrmSwState, 0, 1023, 0, 2);

with

  byte alrmSet = alrmSwState / ((1023 / 3) + 1);

And this should do what you want.  Note that in C fractional results are truncated (not rounded)

body:
You might also consider reading the value several times and summing them, then base your decision on the sum.

This is equivalent to averaging the values but without dividing by 'n', since you don't care about the actual number, just the band it falls into. This will have the effect of improving the signal to noise ratio, since we assume that high-reading errors are as likely as low-reading errors, so their sum tends toward zero as the sum of the real value, V, tends toward (n*V).

Use an int or larger variable for the sum, depending on how many readings you choose to take each time.

body:
The simplest fix to your problem is to change the `map()` call to

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

    byte alrmSet = map(alrmSwState, 0, 1024, 0, 3);

In the call above, the mapped intervals are of the semi-open type, e.g.
[a, b), where the start values (namely 0) are understood as being
_inclusive_ and the end values (1024 and 3) are _exclusive_.

Although not clear from the documentation, this is the proper way to use
the `map()` function. Otherwise, the truncated division gives you very
uneven intervals. Compare:

         x       map(x, 0, 1023, 0, 2)
    ----------------------------------
       0 –  511     0
     512 – 1022     1
    1023            2

         x       map(x, 0, 1024, 0, 3)
    ----------------------------------
       0 –  341     0
     342 –  682     1
     683 – 1023     2

The result you get is very close to Jeff Wahaus’ answer.

What I find annoying about this approach is that a 32-bit integer
division, which `map()` uses internally, is a very expensive operation
on the small 8-bit Arduinos. If instead of 342 and 683, you use 256 and
768 as thresholds, then you can make the decision by just looking at the
high byte of the analog reading:

    uint16_t alrmSwState = analogRead(alarmSwitchPin);

    alrmSet = alrmSwState / 256;

    if (alrmSet != alrmPrevSet) {
        switch (alrmSet) {
            case 0:
                Serial.println("Low");
                break;
            case 1:
            case 2:
                Serial.println("Medium");
                break;
            case 3:
                Serial.println("High");
                break;
        }
        alrmPrevSet = alrmSet;
        delay(200);
    }

Note that the division by 256 is optimized by the compiler into a much
cheaper bit shift, but this is the case only if `alrmSwState` is of an
unsigned integer type. That's why it is declared above as `uint16_t`.

body:
Just three lines of code are needed for the conversion.

    almSet=0;
    if (alrmSwState>300) almSet++;   // increment almSet
    if (alrmSwState>600) almSet++;


body:
the code error says this and im not sure what to do please i need urgent help :([![arduino code error message][1]][1]`

    // Easy bluetooth controlled scrolling text

    // by Yoruk for Instructable

    // 26 02 15 : first code
    // 03 03 15 : buffer updating
    // 04 03 15 : faster version, both buffers
    // 05 03 15 : cleaning and help

    /*
    WIRING :
     pin 12 - DataIn of the first led matrix module
     pin 11 - CLK of the first led matrix module
     pin 10 - CS of the first led matrix module

     pin 9 : RX pin of the bluetooth module
     pin 8 : TX pin of the bluetooth module

     5V : 5v of the matrix module, 5v of the bluetooth module
     GND : the two GND signals of the matrix modules and the bluetooth module

     WARNING : Use a 3v3 arduino card (nano...) or a level converter !!!

     Wire the matrix modules in serie. See the Instructable steps.

     */

    //Librairie for the LEDs matrix
    #include "LedControl.h"

    // virtual serial lib, used with bluetooth
    #include <SoftwareSerial.h>

    //How many matrixes we have ?
    int MatrixNumber =5;

    //virtual serial port bluetooth configuration
    SoftwareSerial BT(8, 9);   //pin 8 : virtual RX    pin 9 :  virtual TX

    // the delay between each screen display (ms)
    int SpeedDelay = 12;

    //total string lenght. The first message is 25 characters long (including spaces)
    int LongueurChaine=25;

    char incomingByte; //incoming data from the BT link

    // the two pixels arrays
    char Buffer[200];   //contient tout les pixels de TOUTE LA PHRASE
    char Buffer_inverse[200]; //contient tout les pixels de TOUTE LA PHRASE, mais symetrises pour affichage sur ecran inverses

    // the message array
    char Phrase[50];

    //here we set up the led matrix
    LedControl lc=LedControl(12,11,10,MatrixNumber);

    // character lib
    int fontDefinitions[480] = {
        0x00,0x00,0x00,0x00,0x00,/*space*/ // is 32 in ASCII
        0x00,0xF6,0xF6,0x00,0x00,/*!*/
        0x00,0xE0,0x00,0xE0,0x00,/*"*/
        0x28,0xFE,0x28,0xFE,0x28,/*#*/
        0x00,0x64,0xD6,0x54,0x08,/*$*/
        0xC2,0xCC,0x10,0x26,0xC6,/*%*/
        0x4C,0xB2,0x92,0x6C,0x0A,/*&*/
        0x00,0x00,0xE0,0x00,0x00,/*'*/
        0x00,0x38,0x44,0x82,0x00,/*(*/
        0x00,0x82,0x44,0x38,0x00,/*)*/
        0x88,0x50,0xF8,0x50,0x88,/***/
        0x08,0x08,0x3E,0x08,0x08,/*+*/
        0x00,0x00,0x05,0x06,0x00,/*,*/
        0x08,0x08,0x08,0x08,0x08,/*-*/
        0x00,0x00,0x06,0x06,0x00,/*.*/
        0x02,0x0C,0x10,0x60,0x80,/*/*/
        0x7C,0x8A,0x92,0xA2,0x7C,/*0*/
        0x00,0x42,0xFE,0x02,0x00,/*1*/
        0x42,0x86,0x8A,0x92,0x62,/*2*/
        0x44,0x82,0x92,0x92,0x6C,/*3*/
        0x10,0x30,0x50,0xFE,0x10,/*4*/
        0xE4,0xA2,0xA2,0xA2,0x9C,/*5*/
        0x3C,0x52,0x92,0x92,0x0C,/*6*/
        0x80,0x86,0x98,0xE0,0x80,/*7*/
        0x6C,0x92,0x92,0x92,0x6C,/*8*/
        0x60,0x92,0x92,0x94,0x78,/*9*/
        0x00,0x00,0x36,0x36,0x00,/*:*/
        0x00,0x00,0x35,0x36,0x00,/*;*/
        0x10,0x28,0x44,0x82,0x00,/*<*/
        0x28,0x28,0x28,0x28,0x28,/*=*/
        0x00,0x82,0x44,0x28,0x10,/*>*/
        0x40,0x80,0x8A,0x90,0x60,/*?*/
        0x7C,0x82,0xBA,0xBA,0x62,/*@*/
        0x3E,0x48,0x88,0x48,0x3E,/*A*/
        0xFE,0x92,0x92,0x92,0x6C,/*B*/
        0x7C,0x82,0x82,0x82,0x44,/*C*/
        0xFE,0x82,0x82,0x82,0x7C,/*D*/
        0xFE,0x92,0x92,0x92,0x82,/*E*/
        0xFE,0x90,0x90,0x90,0x80,/*F*/
        0x7C,0x82,0x82,0x8A,0x4E,/*G*/
        0xFE,0x10,0x10,0x10,0xFE,/*H*/
        0x82,0x82,0xFE,0x82,0x82,/*I*/
        0x84,0x82,0xFC,0x80,0x80,/*J*/
        0xFE,0x10,0x28,0x44,0x82,/*K*/
        0xFE,0x02,0x02,0x02,0x02,/*L*/
        0xFE,0x40,0x20,0x40,0xFE,/*M*/
        0xFE,0x60,0x10,0x0C,0xFE,/*N*/
        0x7C,0x82,0x82,0x82,0x7C,/*O*/
        0xFE,0x90,0x90,0x90,0x60,/*P*/
        0x7C,0x82,0x82,0x86,0x7E,/*Q*/
        0xFE,0x90,0x98,0x94,0x62,/*R*/
        0x64,0x92,0x92,0x92,0x4C,/*S*/
        0x80,0x80,0xFE,0x80,0x80,/*T*/
        0xFC,0x02,0x02,0x02,0xFC,/*U*/
        0xF8,0x04,0x02,0x04,0xF8,/*V*/
        0xFC,0x02,0x0C,0x02,0xFC,/*W*/
        0xC6,0x28,0x10,0x28,0xC6,/*X*/
        0xC0,0x20,0x1E,0x20,0xC0,/*Y*/
        0x86,0x8A,0x92,0xA2,0xC2,/*Z*/
        0x00,0x00,0xFE,0x82,0x00,/*[*/
        0x00,0x00,0x00,0x00,0x00,/*this should be / */
        0x80,0x60,0x10,0x0C,0x02,/*]*/
        0x20,0x40,0x80,0x40,0x20,/*^*/
        0x01,0x01,0x01,0x01,0x01,/*_*/
        0x80,0x40,0x20,0x00,0x00,/*`*/
        0x04,0x2A,0x2A,0x2A,0x1E,/*a*/
        0xFE,0x12,0x22,0x22,0x1C,/*b*/
        0x1C,0x22,0x22,0x22,0x14,/*c*/
        0x1C,0x22,0x22,0x12,0xFE,/*d*/
        0x1C,0x2A,0x2A,0x2A,0x18,/*e*/
        0x10,0x7E,0x90,0x80,0x40,/*f*/
        0x18,0x25,0x25,0x25,0x1E,/*g*/
        0xFE,0x10,0x10,0x10,0x0E,/*h*/
        0x00,0x12,0x5E,0x02,0x00,/*i*/
        0x02,0x01,0x01,0x11,0x5E,/*j*/
        0xFE,0x08,0x08,0x14,0x22,/*k*/
        0x00,0x82,0xFE,0x02,0x00,/*l*/
        0x3E,0x20,0x1C,0x20,0x1E,/*m*/
        0x3E,0x20,0x20,0x20,0x1E,/*n*/
        0x1C,0x22,0x22,0x22,0x1C,/*o*/
        0x3F,0x24,0x24,0x24,0x18,/*p*/
        0x18,0x24,0x24,0x3F,0x01,/*q*/
        0x3E,0x10,0x20,0x20,0x10,/*r*/
        0x12,0x2A,0x2A,0x2A,0x04,/*s*/
        0x00,0x10,0x3C,0x12,0x04,/*t*/
        0x3C,0x02,0x02,0x02,0x3E,/*u*/
        0x30,0x0C,0x02,0x0C,0x30,/*v*/
        0x38,0x06,0x18,0x06,0x38,/*w*/
        0x22,0x14,0x08,0x14,0x22,/*x*/
        0x38,0x05,0x05,0x05,0x3E,/*y*/
        0x22,0x26,0x2A,0x32,0x22,/*z*/
        0x00,0x10,0x6C,0x82,0x82,/*{*/
        0x00,0x00,0xFF,0x00,0x00,/*|*/
        0x04,0x02,0xFF,0x02,0x04,/*|, arrow*/
        0x82,0x82,0x6C,0x10,0x00,/*}*/
        0x08,0x10,0x18,0x08,0x10/*~*/
    };

    void setup() {

        //matrix modules init
        for(int adresse=0;adresse<MatrixNumber;adresse++) {
            /*The MAX72XX is in power-saving mode on startup*/
            lc.shutdown(adresse,false);
            /* Set the brightness to a medium values */
            lc.setIntensity(adresse,4);
            /* and clear the display */
            lc.clearDisplay(adresse);
        }

    //    BufferBuilding("Hi ! Sent me a message...", 25);   //first message on the led screen

        BufferBuilding("text", 4);   //first message on the led screen

        Serial.begin(9600); //we also set the normal serial link, for debug

        BT.begin(9600);      // bluetooth initialisation

        //we sent a message on the phone to tell the user that he can do someting...
        BT.println("Hi ! I'm waiting for a message. Type it and press SEND.");

    }

    void loop() {

        DrawText( LongueurChaine); //draw the message, in a loop

        //or, if we get something on the virtual bluetooth port...
        if (BT.available() > 0) {

            LongueurChaine = BT.available(); //incoming string lenght

            for  (int i = 0; i < LongueurChaine; i++) {

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

                Phrase[i] = incomingByte; ///store the character into the string array

            }

            //debug features, to check :
            Serial.print("Display: ");
            Serial.println(Phrase);
            Serial.print("Length : ");
            Serial.println(LongueurChaine);

            //buffers cleaning, to store the new message
            for(int k = 0; k < 200; k++) {
                Buffer[k]=0;
                Buffer_inverse[k]=0;

            }

            //we create the new buffers, so the new message will be drawn when leaving the sub
            BufferBuilding(Phrase, LongueurChaine);
        }

    }

    void BufferBuilding(char * stringToDisplay, byte stringLength)
    {
        int i =0;

        //loop on every characters (on the string)
        for(int k = 0; k < stringLength; k++) {
            //here we call the characters library
            int caract= k;
            Buffer[i+0] =  fontDefinitions[((stringToDisplay[caract] - 32) * 5) + 0];
            Buffer[i+1] =  fontDefinitions[((stringToDisplay[caract] - 32) * 5) + 1];
            Buffer[i+2] =  fontDefinitions[((stringToDisplay[caract] - 32) * 5) + 2];
            Buffer[i+3] =  fontDefinitions[((stringToDisplay[caract] - 32) * 5) + 3];
            Buffer[i+4] =  fontDefinitions[((stringToDisplay[caract] - 32) * 5) + 4];
            Buffer[i+5] =  B00000000;  //one blank column of leds between two characters
            i=i+6;
        }

        // here, we create a second buffer, to display the message on the switched matrixes
        for(int k = 0; k < stringLength*6; k++) {
            for(int i = 0; i < 8; i++) {
                bitWrite(  Buffer_inverse[k] ,i,  bitRead(Buffer[k] ,7-i) )   ;
            }
        }
    }

    void DrawText( byte stringLength) {

        for(int k = 0; k < stringLength*6; k++) {

            delay(SpeedDelay);

    //delay(10000);
            //k is the column

            //buffer drawing
            for (int m = 0; m < MatrixNumber; m++) {  //loop on the matrix
                if (m % 2 ==  0) //check is the module is upside-down or not...
                {
                    //here, the matrix is flipped upside-down
                    for (int i = 0; i < 8; i++) {  //loop on the columns

                          lc.setRow(m,7-i,Buffer[i+k+8*m]);
                    }
                }
                else
                {
                    //classical
                    for (int i = 0; i < 8; i++) {  //loop on the columns

                           lc.setRow(m,i,Buffer_inverse[i+k+8*m]);
                    }
                }
            }
        }

    }

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

title: ATmega328, arduino nano v3 code error saying insufficient ram memory

Answers: 2

body:
You can free up RAM by moving large arrays and strings into Flash.  By default all strings and arrays are placed into RAM.  The disadvantage to putting data into Flash is that you will not be able to modify it at runtime.

To place an array in Flash use the PROGMEM compiler directive:

    static const unsigned char PROGMEM my_array[] = { 0x00, 0x01, 0x02 ... };

When doing this your likely to notice, besides more available RAM, that many library functions can longer access the array you've placed into FLASH.  The AVR microcontrollers have to use special instructions to read data out of Flash memory.  Some library functions handle this automatically but many do not.  In order to access the data you'll have to implement a function that copies the data out of Flash and into RAM.

Here is an example of a function to copy Flash data into RAM:

    char *Get_Flash_String(const char *FlashString)
    {
     static char buff[MAX_FLASH_STRING_LENGTH+1];
     int i, len;

     len = strlen_P(FlashString);
       for (i = 0; i <= len; i++)
        buff[i] = pgm_read_byte_near(FlashString + i);

     return(buff);
    }

Note that the function above assumes you're reading a NULL terminated string out of flash.  If you're reading an array you don't want to use strlen() to determine the length.

body:
The font definition table takes 960 bytes of RAM - nearly 1/2 of the the total usage. You can regain 480 bytes just by declaring that array as `uint8_t`; 1 byte each entry instead of 2 bytes each for `int`s. You can regain the remaining 480 if you still need to, by moving that table to program memory. The Arduino.cc site has a good [discussion with examples][1]. Just pay attention to the data-types you use if you do that; the functions to read data out of program memory each return one specific type.

  [1]: https://www.arduino.cc/reference/en/language/variables/utilities/progmem/


body:
I'm using a nano v3, the SD module and a 64GB microSD card.
Writing to the card works fine.
But I can't print out the free space left on the card.

I'm using this code:

    /*
      SD card read/write

     This example shows how to read and write data to and from an SD card file
     The circuit:
     * SD card attached to SPI bus as follows:
     ** MOSI - pin 11
     ** MISO - pin 12
     ** CLK - pin 13

     created   Nov 2010
     by David A. Mellis
     modified 9 Apr 2012
     by Tom Igoe

     This example code is in the public domain.

     */

    #include <SPI.h>
    //#include <SD.h>
    #include "SdFat.h"
    SdFat SD;

    #define csPin 4
    File myFile;
    SdFat sd;

    int startMillis;
    int duration;

    uint32_t freeKB;

    void setup() {
      // Open serial communications and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }

      Serial.print("Initializing SD card...");

      if (!SD.begin(csPin)) {
        Serial.println("initialization failed!");
        return;
      }
      Serial.println("initialization done.");

      // open the file. note that only one file can be open at a time,
      // so you have to close this one before opening another.
      myFile = SD.open("test.txt", FILE_WRITE);
      if (myFile) {
        myFile.close();
        Serial.println("done.");
      } else {
        // if the file didn't open, print an error:
        Serial.println("error opening test.txt");
      }
    }

    void loop() {
      myFile = SD.open("test.txt", FILE_WRITE);

      for (int j = 0; j < 1000; j++) {
        myFile.println(j);
      }
      myFile.close();
      startMillis = millis();
      ShowFreeSpace();
      duration = millis() - startMillis;
      Serial.print("Took ");
      Serial.print(duration);
      Serial.println("ms to calculate");
      delay(1000);
    }

    void ShowFreeSpace() {
      // Calculate free space (volume free clusters * blocks per clusters / 2)
      long lFreeKB = sd.vol()->freeClusterCount();
      lFreeKB *= sd.vol()->blocksPerCluster()/2;

      // Display free space
      Serial.print("Free space: ");
      Serial.print(lFreeKB);
      Serial.println(" KB");
    }

What am I doing wrong?

title: cannot show free space of SD card with arduino nano

Answers: 1

body: You have two instances of SdFat class. In setup() you `begin` the `SD` and for free space you try to use `sd`. Delete `SdFat sd;` line and in ShowFreeSpace use `SD.vol()`.


body:
I want to use ESP32 to control and use a dimmer for 6 LED panels in my bedroom. The specification of each panel is mentioned in the diagram. Although in the diagram it shows ONLY 1 MOSFET and 1 LED Panel but in reality there are 6 LED Panels therefore I am guessing that each of the 6 LED Panel will need a separate MOSFET.

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

I would like to know:

1. What MOSFET (Part number or model number, company name,  etc) should I use for the above LED panel connected with ESP32 (I guess voltage of ESP32 is 3.3 v) ?

2. Will each LED panel need separate MOSFET (6 LED Panels will need 6 seperate MOSFET) or can 1 MOSFET be connected to all 6 LED Panel ?

3. If I am using 6 LED Panels what should be the specification of Power Supply (Voltage & Amps) ?

4. If I use 6 set of MOSFET & LED Panels, can all MOSFETs be connected to a single PWM pin in ESP32 or does each MOSFET needs to be connected to separate PWM pins in ESP32 ?

5. Is the above circuit okay, or would you suggest some other components to be added apart from MOSFET?

6. What will be connection between power supply, LED and MOSFET.
I am guessing that 'Positive of Power Supply --> Positive of LED Panel', 'Negative of LED Panel -->  Source of MOSFET' and 'Drain of MOSFET --> Negative of Power Supply'. Kindly correct me if I am wrong.

Thanks.

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

---

To add more information regarding the LED panel:

1. It is 15W LED Panel (note it is not LED Bulb or LED Strip).
   Link to LED panel is [15W LED Panel][1]

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

2. Below is the picture of Driver that came with the LED Panel, note the below driver is non-dimmable.

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

  [1]: https://teknolite.in/project/plx-sq/
  [2]: https://i.stack.imgur.com/Qev5H.jpg
  [3]: https://i.stack.imgur.com/jxy3X.jpg

Kindly help.

title: ESP32 Dimmable LED Panel with MOSFET

Answers: 1

body:
Your plan has more flaws. First as Juraj wrote in a comment, you can't dim a switching power supply of the LED bulb. But this would not work as you plan even if you use a classic incandescent light bulb with AC. You can't control it with PWM. AC is dimmed with [phase control][1], which requires a zero crossing detection to turn off power for part of the AC wave.

  [1]: https://en.wikipedia.org/wiki/Phase-fired_controller


body:
i have a personal challenge that is to make a arduino avoidance robot it has a"hc-sr04 ultrasonic sensor, a servo, bread board(for the sharing of vcc and gnd), l9110s motor driver, and two dc motors, and also the arduino uno itself"
but when i assembled it and upload the code it works if it's plugged in my laptop but if i plugged it in to a battery it keeps on restarting and doesn't run [![`enter image description here`][1]][1]

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

title: why my arduino uno r3 restart when plugged in to a battery(9v)

Answers: 1

body:
Let me guess: the Arduino resets just as one of the motors starts (or should start) right?

The 9v battery is incapable of supplying enough current for much of anything but a few LEDs. When the Arduino first turns on a motor, it needs, and tries to draw, more current than the battery can supply, resulting in the battery voltage dropping below the Arduino's voltage-regulator's minimum input voltage, and the Arduino is shut off. That stops the current draw, the battery voltage recovers, power up the Arduino, which resets (as they always do on power-up), and the cycle keeps repeating.

Try powering it from a more capable battery of greater than 7 volts. 5 AA cells in series, for example would provide 7.5 volts. This won't last terribly long but should work for a while. A second (third, ...) string of 5 in parallel with the first should double the life. Using C or D cells instead will increase the life a lot more.


body:
I'm a total noob when it comes to Arduino. I'm slowly learning stuff. I was trying this code which basically gets input in Arduino1(master) and displays the character in serial monitor of Arduino2(slave). The code words just find but I just need the slave to wait until the master sends the next character. Right now, the slave is continuously printing the character.

Master code:

        #include "Wire.h"
        char ch;

        void setup() {

          Serial.begin(9600);
          Wire.begin();

        }

         void loop() {
          while(Serial.available()==0)
          {}
          ch=Serial.read();
          delay(1000);
          Serial.print("The character that you entered is ");
          Serial.println(ch);

          Wire.beginTransmission(9);
          Wire.write(ch);
          Wire.endTransmission();

            }

Slave code:

    #include "Wire.h"
    char x;

    void setup() {

      Serial.begin(9600);
      Wire.begin(9);
      Wire.onReceive(Event);

    }
    void Event(char bytes){
      x = Wire.read();
    }

    void loop() {

      Serial.print("The character that you entered in the other Arduino is ");
      Serial.println(x);
    }
I know that this will be simple but I just can't quite figure out what to do. Please help me out

title: How do I stop the slave from running the code until master sends a new value? I2C

Answers: 1

body:
    #include "Wire.h"
    volatile char x;
    volatile bool received;

    void setup() {
      Serial.begin(9600);
      Wire.begin(9);
      Wire.onReceive(Event);
    }

    void Event(char bytes){
      x = Wire.read();
      received = true;
    }

    void loop() {

      if (received) {
        received = false;
        Serial.print("The character that you entered in the other Arduino is ");
        Serial.println(x);
      }
    }


body: I would like to know how to connect a NRF24 receiver and Micro SD card module to Arduino board. I have already connected the NRF24 module to the arduino board but now i can't connect the Micro SD card module since the ports like 13,12,11 are used by the NRF24 module. Is there a way to connect those two modules?. I'm trying to save the receiving data on the Micro SD card.

title: How to connect NRF24 receiver and Micro SD Card Module to Arduino UNO

Answers: 1

body:
SPI is a *multi-drop bus* protocol. That means that multiple devices can share the same physical communication medium (wires).

The only thing that needs to be "unique" for a device is its *chip select* pin which the master device (Arduino) uses to choose which of the devices on the SPI bus it's talking to.

So you can share pins 11, 12 and 13, but choose a different *chip select* pin for each device.

However, SD cards are notorious for not working well with other devices (especially with some cheap breakout boards) and your mileage may vary.


body:
Can we potentially use an ultrasonic sensor to differentiate between objects based on the reflective capacity of the object?
For example to differentiate between metals and biodegradable wastes.

title: Can an ultrasonic sensor differentiate b/w objects?

Answers: 1

body:
No. No, you can't. All they sense is the "time of flight".

The closest you would come would be to have a sensor which can detect physical properties of the target.  That could be colour, sound absorption, etc.  You'd need something that sends out a "broad spectrum" signal (white light, white noise, etc) and detects the *reflected spectrum* (colour sensor, wide-band microphone) and do spectral analysis of it.  The signal would also have to be fairly tightly focussed to exclude signals from the environment.

All-in-all not something for a little Arduino to consider without lots of extra expensive hardware.


body:
I would like to use ESP32 to speed control my AC ceiling fan which is 220V AC 100 W.

Will the below AC dimmer work with ESP32 to speed control the ceiling fan which is 220V AC 100 W?

If not, kindly suggest a commonly used PWN dimmer that works with ESP32 to speed control ceiling fan with 220V 100W?

This is the link to [Speed controller available on Amazon][1].

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

  [1]: https://www.amazon.in/gp/product/B078Q8TBRN/ref=ox_sc_saved_title_1?smid=A2E29Q4MEZXUIP&psc=1
  [2]: https://i.stack.imgur.com/3Urab.jpg

title: Speed controller for Ceiling Fan 220V AC 100W

Answers: 1

body:
In theory, it should work to control the speed of fan. The [manufactures description][1] mentions "fan regulator". One of the pictures shows on the backside of the module that it is for 2 A (5 A peek). This should be good for 230 V / 100 W motor.

The module gives you [a basic circuit to control AC][2]. It reports zero-crossing and has an optocoupler switch to turn AC on and off. The dimming does your sketch, by cutting parts of the AC wave out in precise timing.

[The example sketch][3] is not good. It has delay in interrupt. With this implementation the sketch will not be able to do much else.

EDIT: I tested it and it works with fan too. The delay in interrupt is to create a short pulse to turn on the triac. The triac then turns self off on next zero-crossing. And Robotdyn changed the specs to 10 A.

  [1]: https://robotdyn.com/ac-light-dimmer-module-1-channel-3-3v-5v-logic-ac-50-60hz-220v-110v.html
  [2]: https://robotdyn.com/pub/media/0G-00005677==Mod-Dimmer-5A-1L/DOCS/Schematic==0G-00005677==Mod-Dimmer-5A-1L.pdf
  [3]: https://robotdyn.com/pub/media/0G-00005677==Mod-Dimmer-5A-1L/DOCS/Glow.ino


body:
So I can't see the distance of the proximity sensor anymore as soon as I type the code for the piezo buzzer. I've tried many things but it doesn't work.. Can anybody help me fixing this?

    int trigPin = D7;
    int echoPin = D8;
    int BLUE = D3; //D3 zit in blauw
    int GREEN = D4;
    int RED = D5;
    int piezoPin = D10;

    void setup() {// deze code gaat maar 1 keer
      Serial.begin (115200);
      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);

      pinMode(GREEN, OUTPUT);
      pinMode(BLUE, OUTPUT);
      pinMode(RED, OUTPUT);

    }

    void loop() { //code wordt steeds herhaalt
      long duration, distance;
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);
      digitalWrite(trigPin, HIGH); // trig zendt een signaal uit
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);
      duration = pulseIn(echoPin, HIGH); // kijkt hoelang het duurt totdat signaal heen en weer gaat
      distance = (duration/2) / 29.1;
      // omdat het signaal heen wordt gezonden moet het door twee gedeelt worden
      // snelheid van geluid door lucht is circa 29 microseconden per cm dus gedeelt 29.

        Serial.print(distance);
        Serial.println(" cm");

    //afstand wordt in cm weergegeven in serial monitor

      delay(500);

       if ((distance > 100) && (distance <= 150)){ //dit gebeurd er als de afstand vanaf sensor tussen groter dan 100 cm en gelijk aan of kleiner dan 150 cm is.
        analogWrite(BLUE, 0);
        analogWrite(GREEN, 255);
        analogWrite(RED, 0);

        tone(piezoPin, 1000, 1000); // toon duurt 1 seconden
        delay(2000); // 2 seconden geen geluid
        tone(piezoPin, 1000, 1000);
        delay(2000);

       }

       else if ((distance > 50) && (distance <= 100)){ //dit gebeurd er als de afstand vanaf sensor tussen groter dan 50 cm en gelijk aan of kleiner dan 100 cm is.
        Serial.println("Ga weg!");

        analogWrite(BLUE, 0);
        analogWrite(GREEN, 102);
        analogWrite(RED, 252);

        tone(piezoPin, 1000, 700); // toon duurt 0.7 seconden
        delay(1000); // 1 seconde geen geluid
        tone(piezoPin, 1000, 700);
        delay(1000);

      }

      else if ((distance >= 0) && (distance <= 50)){ //dit gebeurd er als de afstand vanaf sensor tussen groter dan of gelijk aan 0 cm en gelijk aan of kleiner dan 50 cm is.

        analogWrite(BLUE, 0);
        analogWrite(GREEN, 0);
        analogWrite(RED, 255);

        tone(piezoPin, 1000, 200); // toon duurt 0,2 seconden
        delay(100); // 0,1 seconden geen geluid
        tone(piezoPin, 1000, 200);
        delay(100);

      }

       else {
        analogWrite(BLUE, 0);
        analogWrite(GREEN, 0);
        analogWrite(RED, 0);

     }

    }

title: Serial monitor doesn't work with piezo buzzer

Answers: 1

body:
Pin D10 of NodeMcu is io 1 which is RX pin of Serial interface of the esp8266. Serial is on NodeMCU connected to USB. The pin is on board labeled RX.

D8 is boot config pin io 15. It must have pulldown on board. The pulldown can disturb the input on this pin. Use D6 (io 12) as echoPin.


body:
My code is getting uploaded to arduino without problem but still my motor is not moving when i connect it to the motor driver shield. I am supplying 6V battery to the shield which is connected to dc motor at M2

What could be the problem?

Code:-

    #include <AFMotor.h> //import your motor shield library

    AF_DCMotor motor2(2,MOTOR12_2KHZ); // set up motors.
    AF_DCMotor motor3(1, MOTOR34_1KHZ);

    void setup() {
      Serial.begin(9600); // begin serial communitication
      Serial.println("Motor test!");
      motor2.setSpeed(105); //set the speed of the motors, between 0-255
      motor3.setSpeed(105);
    }

    void loop() {
       motor2.run(FORWARD);
       motor3.run(FORWARD);
      }

  [![image of circuit][1]][1]

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

title: Motor not working when connected to motor driver shield?

Answers: 1

body:
I cannot tell all of your connections from the photo, but I'm guessing you're supplying power to the Arduino through its power connector and also to the motors, both from the battery. The power connector on the Arduino is specified for 7-12v because the kind of voltage regulator it has needs that 2v difference to operate properly. You're kind of at the edge by supplying 6v, and when the motors come on, their current draw will cause the 6v battery voltage to drop somewhat. It probably drops below the regulator's ability to supply 5v from it, shutting down the Arduino.

Adding one more cell to your battery will give you 7.5v (5x1.5v) and will may be enough to run the Arduino and the motors. Two more cells would work even better. (Don't make the mistake of trying the small 9v batteries with snap-clips on top - their utterly incapable of supply the current your motors need).


body:
I am currently making a project involving a self balancing bot & found this code online:

    #include "PID_v1.h"
    #include "LMotorController.h"
    #include "I2Cdev.h"
    #include "MPU6050_6Axis_MotionApps20.h"

    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        #include "Wire.h"
    #endif

    #define MIN_ABS_SPEED 20

    MPU6050 mpu;

    // MPU control/status vars
    bool dmpReady = false;  // set true if DMP init was successful
    uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
    uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
    uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
    uint16_t fifoCount;     // count of all bytes currently in FIFO
    uint8_t fifoBuffer[64]; // FIFO storage buffer

    // orientation/motion vars
    Quaternion q;           // [w, x, y, z]         quaternion container
    VectorFloat gravity;    // [x, y, z]            gravity vector
    float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector

    //PID
    double originalSetpoint = 178.57;
    double setpoint = 178.57;
    double movingAngleOffset = 0.1;
    double input, output;
    double Kp = 50;
    double Kd = 1.4;
    double Ki = 60;
    PID pid(&input, &output, &setpoint, Kp, Ki, Kd, DIRECT);

    double motorSpeedFactorLeft = 0.6;
    double motorSpeedFactorRight = 0.5;
    //MOTOR CONTROLLER
    int ENA = 5;
    int IN1 = 6;
    int IN2 = 7;
    int IN3 = 8;
    int IN4 = 9;
    int ENB = 10;
    LMotorController motorController(ENA, IN1, IN2, ENB, IN3, IN4, motorSpeedFactorLeft, motorSpeedFactorRight);

    volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
    void dmpDataReady()
    {
        mpuInterrupt = true;
    }

    void setup()
    {
        // join I2C bus (I2Cdev library doesn't do this automatically)
        #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
            Wire.begin();
            TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
        #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
            Fastwire::setup(400, true);
        #endif

        // initialize serial communication
        // (115200 chosen because it is required for Teapot Demo output, but it's
        // really up to you depending on your project)
        Serial.begin(115200);
        while (!Serial); // wait for Leonardo enumeration, others continue immediately

        // initialize device
        Serial.println(F("Initializing I2C devices..."));
        mpu.initialize();

        // verify connection
        Serial.println(F("Testing device connections..."));
        Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));

        // load and configure the DMP
        Serial.println(F("Initializing DMP..."));
        devStatus = mpu.dmpInitialize();

        // supply your own gyro offsets here, scaled for min sensitivity
        mpu.setXGyroOffset(262);
        mpu.setYGyroOffset(-29);
        mpu.setZGyroOffset(-10);
        mpu.setXAccelOffset(-2109);
        mpu.setYAccelOffset(394);
        mpu.setZAccelOffset(1341); // 1688 factory default for my test chip

        // make sure it worked (returns 0 if so)
        if (devStatus == 0)
        {
            // turn on the DMP, now that it's ready
            Serial.println(F("Enabling DMP..."));
            mpu.setDMPEnabled(true);

            // enable Arduino interrupt detection
            Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
            attachInterrupt(0, dmpDataReady, RISING);
            mpuIntStatus = mpu.getIntStatus();

            // set our DMP Ready flag so the main loop() function knows it's okay to use it
            Serial.println(F("DMP ready! Waiting for first interrupt..."));
            dmpReady = true;

            // get expected DMP packet size for later comparison
            packetSize = mpu.dmpGetFIFOPacketSize();

            //setup PID

            pid.SetMode(AUTOMATIC);
            pid.SetSampleTime(10);
            pid.SetOutputLimits(-255, 255);
        }
        else
        {
            // ERROR!
            // 1 = initial memory load failed
            // 2 = DMP configuration updates failed
            // (if it's going to break, usually the code will be 1)
            Serial.print(F("DMP Initialization failed (code "));
            Serial.print(devStatus);
            Serial.println(F(")"));
        }
    }

    void loop()
    {
        // if programming failed, don't try to do anything
        if (!dmpReady) return;

        // wait for MPU interrupt or extra packet(s) available
        while (!mpuInterrupt && fifoCount < packetSize)
        {
            //no mpu data - performing PID calculations and output to motors

            pid.Compute();
            motorController.move(output, MIN_ABS_SPEED);

        }

        // reset interrupt flag and get INT_STATUS byte
        mpuInterrupt = false;
        mpuIntStatus = mpu.getIntStatus();

        // get current FIFO count
        fifoCount = mpu.getFIFOCount();

        // check for overflow (this should never happen unless our code is too inefficient)
        if ((mpuIntStatus & 0x10) || fifoCount == 1024)
        {
            // reset so we can continue cleanly
            mpu.resetFIFO();
            Serial.println(F("FIFO overflow!"));

        // otherwise, check for DMP data ready interrupt (this should happen frequently)
        }
        else if (mpuIntStatus & 0x02)
        {
            // wait for correct available data length, should be a VERY short wait
            while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

            // read a packet from FIFO
            mpu.getFIFOBytes(fifoBuffer, packetSize);

            // track FIFO count here in case there is > 1 packet available
            // (this lets us immediately read more without waiting for an interrupt)
            fifoCount -= packetSize;

            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
            #ifdef LOG_INPUT
                Serial.print("ypr\t");
                Serial.print(ypr[0] * 180/M_PI);
                Serial.print("\t");
                Serial.print(ypr[1] * 180/M_PI);
                Serial.print("\t");
                Serial.println(ypr[2] * 180/M_PI);
            #endif
            input = ypr[1] * 180/M_PI + 180;
            Serial.println(input);
       }
    }

The repo is linked to <https://github.com/kurimawxx00/arduino-self-balancing-robot>

My code is as below:

        /* For documentation purposes
     *
     * #define MPU6050_INTERRUPT_FF_BIT            7
     * #define MPU6050_INTERRUPT_MOT_BIT           6
     * #define MPU6050_INTERRUPT_ZMOT_BIT          5
     * #define MPU6050_INTERRUPT_FIFO_OFLOW_BIT    4
     * #define MPU6050_INTERRUPT_I2C_MST_INT_BIT   3
     * #define MPU6050_INTERRUPT_PLL_RDY_INT_BIT   2
     * #define MPU6050_INTERRUPT_DMP_INT_BIT       1
     * #define MPU6050_INTERRUPT_DATA_RDY_BIT      0
     *
      */

    #include "I2Cdev.h"
    #include "MPU6050_6Axis_MotionApps20.h"
    #include "PID_v1.h"
    #include "LMotorController.h"

    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        #include <Wire.h>
    #endif

    #define MIN_SPEED 20

    #define DEBUG_BUILD

    MPU6050 mpu;

    // Variables for MPU status and control
    bool isDMPReady = false;
    uint8_t dmpStatus; // 0 if initialization succeeds
    uint16_t dmpPacketSize; // default = 42
    uint16_t fifoCount;
    uint8_t fifoBuffer[64];
    uint8_t mpuIntStatus;

    // Variables for calculated data from DMP
    Quaternion q; // // holds QUAT_W, QUAT_X, QUAT_Y, QUAT_Z from FIFO
    int16_t gyro[3]; // Holds rotation
    VectorFloat gravity; // holds gravity vector calculated from DMP
    float ypr[3]; // 0 = yaw, 1 = pitch, 2 = roll

    // PID data
    double setPoint = 178.57;
    double input = setPoint, output;
    double Kp = 50;
    double Kd = 1.4;
    double Ki = 60;
    PID pid(&input, &output, &setPoint, Kp, Ki, Kd, DIRECT);

    // Motor config
    const int inA = 6;
    const int inB = 7;
    const int inC = 8;
    const int inD = 9;
    const int enA = 5;
    const int enB = 10;
    const double motorCorrectionA = 0.6;
    const double motorCorrectionB = 0.5;
    LMotorController motorController(inA, inB, inC, inD, enA, enB, motorCorrectionA, motorCorrectionB);

    // =================================================
    // ===         Interrupt Service Routine         ===
    // =================================================
    volatile bool mpuInterrupt = false;
    void dmpDataReady() {
        mpuInterrupt = true;
    }

    // =================================================
    // ===              Program Setup                ===
    // =================================================
    void setup() {
        // join the I2C bus
        #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
            Wire.begin();
            TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
        #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
            Fastwire::setup(400, true);
        #endif

        Serial.begin(115200);
        while(!Serial);

        // Initialize mpu
        Serial.println(F("Initializing I2C Devices: "));
        mpu.initialize();
        dmpStatus = mpu.dmpInitialize();

        // Gyro and accel offsets
        mpu.setXGyroOffset(262);
        mpu.setYGyroOffset(-29);
        mpu.setZGyroOffset(-10);
        mpu.setXAccelOffset(-2109);
        mpu.setYAccelOffset(394);
        mpu.setZAccelOffset(1341);

        // Verify initialization
        #ifdef DEBUG_BUILD
            Serial.println(F("Testing MPU Status: "));
            Serial.println(mpu.testConnection() ? F("MPU6050 initialization success!") : F("MPU6050 initialization failed!"));
            Serial.println(dmpStatus == 0 ? F("DMP initialization successful!") : F("DMP initialization failed!"));
        #endif

        if(dmpStatus == 0){
            // Enable DMP
            mpu.setDMPEnabled(true);

            attachInterrupt(0, dmpDataReady, RISING);

            // Get interrupt byte
            mpuIntStatus = mpu.getIntStatus();

            // Get DMP packet size ; default = 42B
            dmpPacketSize = mpu.dmpGetFIFOPacketSize();

            // Verify DMP initialization
            #ifdef DEBUG_BUILD
                Serial.println(mpu.getFIFOEnabled() ? F("FIFO Enabled!") : F("FIFO Not Enabled!"));
                Serial.println(mpu.getXGyroFIFOEnabled() ? F("FIFO X Gyro Enabled!") : F("FIFO X Gyro Not Enabled!"));
                Serial.println(mpu.getYGyroFIFOEnabled() ? F("FIFO Y Gyro Enabled!") : F("FIFO Y Gyro Not Enabled!"));
                Serial.println(mpu.getZGyroFIFOEnabled() ? F("FIFO Z Gyro Enabled!") : F("FIFO Z Gyro Not Enabled!"));
                Serial.println(mpu.getAccelFIFOEnabled() ? F("FIFO Accel Enabled!") : F("FIFO Accel Not Enabled!"));
                Serial.print(F("DMP Packet Size: "));
                Serial.println(dmpPacketSize);
            #endif

            isDMPReady = true;

            // Setup PID
            pid.SetMode(AUTOMATIC);
            pid.SetSampleTime(10);
            pid.SetOutputLimits(-160, 160);
        }
        else{
            Serial.println(F("DMP Error!!!"));
        }
    }

    // =================================================
    // ===            Main Program Loop              ===
    // =================================================
    void loop() {
        // Do nothing if DMP initialization failed
        if(!isDMPReady) return;

        while(!mpuInterrupt && fifoCount < dmpPacketSize){
            pid.Compute();
            motorController.move(output, MIN_SPEED);
        }

        mpuInterrupt = false;
        mpuIntStatus = mpu.getIntStatus();

        fifoCount = mpu.getFIFOCount();

        if(mpuIntStatus & 0x10 || fifoCount == 1024){
            mpu.resetFIFO();
            Serial.println("FIFO Overflow");
        }
        else if(mpuIntStatus & 0x02){
            while(fifoCount < dmpPacketSize) fifoCount = mpu.getFIFOCount();

            mpu.getFIFOBytes(fifoBuffer, dmpPacketSize);
            fifoCount -= dmpPacketSize;

            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
            // TODO: implement complementary filter
            input = ypr[1] * 180 / M_PI + 180; // Supposing at upright position, pitch is 180 degrees

            #ifdef DEBUG_BUILD
                Serial.print("Yaw/Pitch/Roll: ");
                Serial.print(ypr[0] * RAD_TO_DEG);
                Serial.print("\t");
                Serial.print(ypr[1] * RAD_TO_DEG);
                Serial.print("\t");
                Serial.println(ypr[2] * RAD_TO_DEG);
            #endif
        }
    }

I am using the exact same libraries and classes as in the repo. Yet my code does not work at all, the motors move erratically. All the physical connections are ok since the code from the repo works flawlessly. I've no idea why this is happening. Help is very much appreciated.

title: Out of two logically similar sketches, one works while the other does not

Answers: 2

body:
Given that both libraries are the same.

The two sketches seem to set up the motorcontroller quite differently. Changing an "input pin" and "enable pin" around, would lead to errratic motor behaviour.

```
LMotorController motorController(ENA, IN1

LMotorController motorController(inA, inB
```

To me, an input pin would be an PWM signal to drive the speed of the motor.
An enable pin, would enable/disable the whole driver (both left/right).

But it's hard to tell, also, if the above sketch is working, why not use the above sketch and adjust that?

body: Another thing I noticed while tinkering, interrupts from the MPU6050 can only be caught by the Uno when serial comm is set to 115200 baud rate or higher. Anything lower causes the MPU interrupts to be never caught. Maybe this is a particular problem of my board (it's a cheap chinese one), but maybe this will help someone out somehow. :)


body:
I am learning UART  and the problem that i have is understanding what happens when i send serial data to my PC via USB which is built in to the Arduino uno board.

For incoming serial data i am using Terminal v1.9b and it basically lets me to set some parameters and listen to incoming data on Software serial port and or write to it.

The process:

 1. Atmega328p's Baud rate is set to 9600
 2. Terminal connects to it (it performs a reset) and i get my data in.

Very simple, it all works and i don't have a problem with it. What my question is: I assume that my PC doesn't talk to atmega328p directly since it has no USB interface. it talks to a bootloader chip which converts the USB to UART and then i receive that message on my atmega328p. How does that chip know which baud rate we agreed to. OR "Terminal" sends the baud rate to that bootloading chip via usb protocol and it sets its UART settings ?

title: Baud rate of Arduinos bootloader

Answers: 1

body:
The bootloader runs in the 328, and just as your application programs do, it sets a UART baud-rate for uploading programs to the Uno.

Current bootloaders use 115200 baud for upload; the most recent previous ones used 57600 baud. Setting that is part of the bootloader code. Whatever your application program last set for a baud-rate doesn't matter; if you reset the Uno, the bootloader sets the UART to the known upload baud-rate, and waits briefly for the PC to begin an upload, and jumps to the currently loaded application program if no upload is begun.

Your PC's Arduino IDE configuration is written to use the known bootloader baudrate (you can see that in the avrdude command). In fact, since I have some boards with soldered-in chips with the older, 57600 baud bootloader burned in them, I have two Uno-board configurations in my IDE; one for those older chips, and one for the current ones.


body:
[![Error reading][1]][1]

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

Hi Guys! i have a problem with the reading with my NODEMCU where i tried this code on an arduino UNO it is working perfectly fine but until i tried to switch it to NODEMCU 1.0 which have a wifi function that i need, the reading turn out to have this type of error, i've tried looking for solution online and tried every single of them but apparently none of it help. The image is the error i have faced and the connection i have made from the nodemcu to hx711 is VCC --> Vin or 3.3v, GND --> GND, DT --> D2, SCK --> D3.
Here's the code that i found online to use:

    #include <HX711.h>

    // Scale Settings
    const int SCALE_DOUT_PIN = D2;
    const int SCALE_SCK_PIN = D3;

    HX711 scale(SCALE_DOUT_PIN, SCALE_SCK_PIN);

    void setup() {
      Serial.begin(115200);
      scale.set_scale(-47740);// <- set here calibration factor!!!
      scale.tare();
    }

    void loop() {
      float weight = scale.get_units(1);
      Serial.println(String(weight, 3));
    }

Thanks in advance!!

title: NODEMCU 1.0 HX711 Load cell reading weird text

Answers: 1

body: Try D1 instead of D3. D3 is io 0, a boot configuration pin with pull-up on board.


body:
this is a program for a blindspot detection system using 4 ultrasonic and 2 ir sensors.
can someone help me in modifyng the code so that this runs faster?

    #include<LiquidCrystal.h>
    #define trigbl 14
    #define echobl 15
    #define trigbr 16
    #define echobr 17
    #define trigfl 18
    #define echofl 19
    #define trigfr 8
    #define echofr 9
    #define bl 10
    #define br 11
    long durationbl;
    long durationbr;
    long durationfl;
    long durationfr;
    int distancebl;
    int distancebr;
    int distancefl;
    int distancefr;
    int irr;
    int irl;
    int a;
    int b;
    LiquidCrystal lcd(7, 6, 5, 4, 3, 2);
    void setup()
    {
      lcd.begin(16, 2);
      pinMode(trigbl, OUTPUT);
      pinMode(echobl, INPUT);
      pinMode(trigbr, OUTPUT);
      pinMode(echobr, INPUT);
      pinMode(trigfl, OUTPUT);
      pinMode(echofl, INPUT);
      pinMode(trigfr, OUTPUT);
      pinMode(echofr, INPUT);
      pinMode(bl, INPUT_PULLUP);
      pinMode(br, INPUT_PULLUP);
    }
    void loop()
    {
      digitalWrite(trigbl, LOW);
      delay(2);
      digitalWrite(trigbl, HIGH);
      delay(10);
      digitalWrite(trigbl, LOW);
      durationbl = pulseIn(echobl, HIGH);
      distancebl = durationbl * 0.034 / 2;
      int a1=distancebl;
      digitalWrite(trigbr, LOW);
      delay(2);
      digitalWrite(trigbr, HIGH);
      delay(10);
      digitalWrite(trigbr, LOW);
       durationbr = pulseIn(echobr, HIGH);
       distancebr = durationbr * 0.034 / 2;
      int a2=distancebr;
      digitalWrite(trigfl, LOW);
      delay(2);
      digitalWrite(trigfl, HIGH);
      delay(10);
      digitalWrite(trigfl, LOW);
      durationfl = pulseIn(echofl, HIGH);
      distancefl = durationfl * 0.034 / 2;
      int a3=distancefl;
      digitalWrite(trigfr, LOW);
      delay(2);
      digitalWrite(trigfr, HIGH);
      delay(10);
      digitalWrite(trigfr, LOW);
      durationfr = pulseIn(echofr, HIGH);
      distancefr = durationfr * 0.034 / 2;
      int a4=distancefr;
      irl =digitalRead(bl);
      irr =digitalRead(br);
      lcd.setCursor(1, 0);
      lcd.print("RL  RR  FL  FR");
      if (a1<30 && irl==0)
      {
      a=0;
      }
      else
      {
        a=1;
      }
       if (a2<30 || irr==0)
      {
      b=0;
      }
      else
      {
        b=1;
      }
       if  (a==1 && b==1 && a3>30 && a4>30)
      {
        lcd.setCursor(1, 1);
        lcd.print("No Obstacle    ");
      }
      else if ( a==0 && b==1 && a3>30 && a4>30)
      {
        lcd.setCursor(1, 1);
        lcd.print("XX            ");
      }
      else if ( a==1 && b==0 && a3>30 && a4>30)
      {
        lcd.setCursor(1, 1);
        lcd.print("    XX        ");
      }
      else if ( a==1 && b==1 && a3<30 && a4>30)
      {
        lcd.setCursor(1, 1);
        lcd.print("        XX    ");
      }
       else if ( a==1 && b==1 && a3>30 && a4<30)
      {
        lcd.setCursor(1, 1);
        lcd.print("            XX");
      }
      else if ( a==0 && b==0 && a3>30 && a4>30)
      {
        lcd.setCursor(1, 1);
        lcd.print("XX  XX        ");
      }
      else if ( a==1 && b==0 && a3<30 && a4>30)
      {
        lcd.setCursor(1, 1);
        lcd.print("    XX  XX    ");
      }

      else if ( a==0 && b==1 && a3<30 && a4>30)
      {
        lcd.setCursor(1, 1);
        lcd.print("XX      XX    ");
      }
      else if ( a==0 && b==1 && a3>30 && a4<30)
      {
        lcd.setCursor(1, 1);
        lcd.print("XX          XX");
       }
      else if ( a==1 && b==0 && a3>30 && a4<30)
      {
        lcd.setCursor(1, 1);
        lcd.print("    XX      XX");
      }
      else if ( a==0 && b==0 && a3<30 && a4>30)
      {
        lcd.setCursor(1, 1);
        lcd.print("XX  XX  XX    ");
      }
      else if ( a==1 && b==1 && a3<30 && a4<30)
      {
        lcd.setCursor(1, 1);
        lcd.print("        XX  XX");
      }
      else if ( a==1 && b==1 && a3>30 && a4<30)
      {
        lcd.setCursor(1, 1);
        lcd.print("XX  XX      XX");
      }
      else if ( a==1 && b==0 && a3<30 && a4<30)
      {
        lcd.setCursor(1, 1);
        lcd.print("XX      XX  XX");
       }
      else if ( a==1 && b==0 && a3<30 && a4<30)
      {
        lcd.setCursor(1, 1);
        lcd.print("    XX  XX  XX");
      }
      else if ( a==0 && b==0 && a3<30 && a4<30)
      {
            lcd.setCursor(1, 1);
            lcd.print("Call Help ......  ");
      }
    }

title: Can anyone please help me to modify the code so that it runs faster?

Answers: 1

body:
You may want to check the datasheet of your sonar sensors to see what is
the recommended trigger pulse duration. On a typical HC-SR04, it is ten
**micro**seconds, not **milli**seconds. So use `delayMicroseconds(10);`.

If your program runs really slowly, the culprit is most probably
`pulseIn()`. This function will wait for an incoming pulse and, if there
is no incoming pulse, it waits one full second before timing out. This
can be simply fixed by providing a third argument to `pulseIn()`, which
is the desired timeout in microseconds. Set it to something reasonable,
maybe around 25,000 µs for a maximum detection range of 4 m.


body:
I have an Uno R3 with a sensor board and a temperature sensor. I'm running a simple temperature check and would like to store that data outside the Ardunio for keeping records, graphs, etc.

I powered it from my PC during development, but obviously I want something more compact when deployed. It's still inside the house, but I want the PC shut down, not running 24/7.

I do have wireless access, and a Raspbery Pi 3 model B. Can any of those help? Or should I buy an ethernet/WiFi shield and try to get acces with those?

title: Deploying an Arduino Uno R3 standalone

Answers: 3

body:
My first reaction is similar to Juraj's - go straight to the PI with the sensor; this is the most straightforward and maybe the simplest answre.  There are caveats - your sensor may not have a straight-forward hookup and, more importantly, the Raspberry PI uses 3.3V inputs - the Arduino can take up to 5V.  Don't fry your PI.
**Next**, you'll have to program your PI to read the sensor.
Another option is to use your Arduino to send the data serially to the PI. Again, verify your voltages.
**Third**, you can, mentioned, use an Ethernet shield, or some wireless daughter-board to talk to another computer like the PI or a server somewhere that stores/analyzes the data.  It tends to get more open-ended and can be as complicated as you like at this point.  Good luck!

body:
So you would rather use your Raspberry Pi than your PC? Easy, as it
turns out that a Raspberry Pi is not that different from a PC running
Debian or a Debian-like OS (e.g. Ubuntu).

Just connect the Uno to the Raspberry Pi through the USB link. Log the
data on your Raspberry exactly like you would do on the PC. You don't
need any Ethernet or WiFi shield. You just need to make sure that
whatever logging program you use on the PC can run on the Raspberry Pi.
This is most often trivial if the PC is itself running a Linux distro.

body:
The simplest is to use an SD card shield and write your data to the card, occasionally exchanging cards. This can be very infrequent if you like; SD cards are pretty dense. Advantage: Simple and direct. Data remains under your direct control. Disadvantage: Finite (but potentially large) capacity; Data remains on your Arduino -- sort-of. Not sure how "outside the Arduino" you need it to be).

Another option, though a little more complex, is to use a networking device to log your data to an online service such as [Thingspeak][1]. I personally favor ESP8266 radios, as they're very cheap and easy to work with, but the choice of an Ethernet shield, WiFi shield, or whatever else, is up to you, and the techniques (from the Arduino's point of view) are similar. Advantage: Your data is saved off your Arduino immediately, somewhere with an "approximately infinite" capacity; provider may (Thingspeak does) offer plotting and analysis tools. Disadvantage: Your data does not remain under your direct control (though you can presumably collect it if you need/want to).

  [1]: https://thingspeak.com/


body:
I am using a ZCD circuit controlling a TRIAC. Now I am using Dimmer library for this purpose. It works fine with ATMega 328 but whenever I try to upload the code in ATMega 128 using Arduino IDE this error pops up:

    Arduino: 1.8.4 (Windows 10), Board: "ATmega128, 2.7v, Disabled (default), 16 MHz external"

    C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp: In member function 'void Dimmer::begin(uint8_t, bool)':

    C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:15:20: error: 'TCCR2A' was not declared in this scope

     #define _TCCRxA(X) TCCR ## X ## A

                        ^

    C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:16:19: note: in expansion of macro '_TCCRxA'

     #define TCCRxA(X) _TCCRxA(X)

                       ^

    C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:157:5: note: in expansion of macro 'TCCRxA'

         TCCRxA(DIMMER_TIMER) = TCCRxA_VALUE;         // Timer config byte A

         ^

    C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:17:20: error: 'TCCR2B' was not declared in this scope

     #define _TCCRxB(X) TCCR ## X ## B

                        ^

    C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:18:19: note: in expansion of macro '_TCCRxB'

     #define TCCRxB(X) _TCCRxB(X)

                       ^

    C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:158:5: note: in expansion of macro 'TCCRxB'

         TCCRxB(DIMMER_TIMER) = TCCRxB_VALUE;         // Timer config byte B

         ^

    C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:19:20: error: 'TIMSK2' was not declared in this scope

     #define _TIMSKx(X) TIMSK ## X

                        ^

    C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:20:19: note: in expansion of macro '_TIMSKx'

     #define TIMSKx(X) _TIMSKx(X)

                       ^

    C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:159:5: note: in expansion of macro 'TIMSKx'

         TIMSKx(DIMMER_TIMER) = 0x02;                 // Timer Compare Match Interrupt Enable

         ^

    C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:21:19: error: 'OCR2A' was not declared in this scope

     #define _OCRxA(X) OCR ## X ## A

                       ^

    C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:22:18: note: in expansion of macro '_OCRxA'

     #define OCRxA(X) _OCRxA(X)

                      ^

    C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:160:5: note: in expansion of macro 'OCRxA'

         OCRxA(DIMMER_TIMER) = 100 * 60 / acFreq - 1; // Compare value (frequency adjusted)

         ^

    exit status 1
    Error compiling for board ATmega128.

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

Any idea what is the issue ?

title: Dimmer.h issues with ATmega 128

Answers: 1

body:
The Dimmer library doesn't support Atmega128/164/16/32. It has

    #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
    #define DIMMER_TIMER 4
    #elif defined(__AVR_ATmega32U4__)
    #define DIMMER_TIMER 3
    #else
    #define DIMMER_TIMER 2
    #endif

For the Atmega128/164/16/32 it will use timer 2. The main errors are:

    'OCR2A' was not declared in this scope
    'TCCR2A' was not declared in this scope
    'TCCR2B' was not declared in this scope
    'TIMSK2' was not declared in this scope

**Possible solution**:

You could try to use timer 3. Only you need to change the timer number in Dimmer.h and in Dimmer.cpp on line 159 change `TIMSKx(DIMMER_TIMER) = 0x02` perhaps to `bitSet(ETIMSK, 3);`. Check the datasheet. I can't test it, I don't have the chip.


body:
im a newcomer for arduino and sorry for any grammar error.
So what im trying to do is replicating a flickering effect found on spacecraft thruster when they about to take off where the fire bursting from dim to bright with flickering,similiar to afterburner on aircraft model which use neopixel led but this time only using common led.
I could mimic the flickering on the led with various  brightness level using the simple analogWrite,the problem is i cant really merge them since i use delay which is affecting how fast the flickering effect is and i need 1 sequence of flickering to stay a while before going next to brighter flickering and so on.
My code is quite too simple

        Int led = 9;
        void setup () {
        pinMode (led, OUTPUT);
        }

        void loop() {
        {analogWrite (led, random (10,15));
        delay (30);}

        }

Im thinking adding a new line with higher random led states (ex. 50,100) should be okay,but then the delay which affect the flickering speed are too short and making both line merging useless since its will go to the brightest in no time.
Is there's any way to hold the first dim line for an amount of time then continue to the next brighter line and so on without affecting the filckering delay?
Any help will be appreciated

Thank you!

title: Help with simple gradually brighter flickering led

Answers: 1

body:
Before using millis() you can try to create the thruster effect with delay().

I think 40Hz update rate for the led should be enough.
The sketch starts with a random value between 5 and 15 and ends with a random value between 80 and 256.
The part in the middle that gradually increases between those values is a mathematical problem.

    // Led mimic spacecraft thruster.
    //
    // Update rate 40Hz for the led.
    // That is a delay of 25ms.

    #define RATE 40  // update rate of led in Hz
    const int ledPin = 9;   // it must be a PWM pin !

    void setup () {
      pinMode(ledPin, OUTPUT);

      Serial.begin(9600);

      randomSeed(analogRead(A0));
    }

    void loop() {
      int n;

      Serial.println("10 seconds low brightness");
      n = 10*RATE;
      for(int i=0; i<n; i++) {
        analogWrite(ledPin, random(5,15));
        delay(1000/RATE);
      }

      Serial.println("5 seconds gradually brighter");
      n = 5*RATE;
      for(int i=0; i<n; i++) {
        //   random start: from 5 to 80     (75 increase)
        //   random end  : from 15 to 256   (241 increase)
        //   The calculation is with long, it might not fit in a 16 bit integer

        int random_start = 5 + int((long(i) * 75) / long(n));
        int random_end   = 15 + int((long(i) * 241) / long(n));
        analogWrite(ledPin, random(random_start,random_end));
        delay(1000/RATE);
      }

      Serial.println("10 second full thrust");
      n = 10*RATE;
      for(int i=0; i<n; i++) {
        analogWrite(ledPin, random(80,256));
        delay(1000/RATE);
      }

      analogWrite(ledPin,0);
      delay(2000);
    }


body:
I have an ESP8266 running an Arduino code to control a dual relay device ( Up, Down, Off ), both from a physical switch and MQTT commands. After mounting the device in place I have no access in case of a need to reset ( just as a precaution ).

My workaround:

1) condition: function that on 4 detection of 4 repeated UP button presses - it should send a reboot signal.

2) the reboot signal is :

    void sendReset() {
      Serial.println("Sending Reset command");
      Serial.println(1/0);
    }

`sendReset` function actually reboots the device and boot occurs as needed, BUT - is doing it this way is a valid solution ? does boot process actually boots all services and freeing/ memory or any other.... AS NEEDED ?

Guy

title: ESP8266 - Sending a software Reset Command

Answers: 1

body:
1/0 is an exception (divide by zero). esp8266 arduino core has soft reset: `ESP.reset()`. Calling this function you get a valid reset.

Note to software reset. esp8266 has a bug. If software reset (or exception) is executed in program started right after the flashing, the board goes back to flashing mode because the flashing flag is still active. Perhaps you noticed that after flashing the bootloader doesn't reset the board, but executes the flashed code.


body:
I have some questions when it comes to draining batteries with low power projects.

I have been making a few low power projects with Arduino Pro Minis running on batteries. Some run on single non-recharchable CR123As while others run on two or three recharchable AAAs. I have removed the regulator and the power led on the Pro Minis, and I have changed the fuses making them run as low as 1.8v (or according to my measurements 1.7v). This way they consume a few µA and should be able to run for years on those batteries.

Now, what started to concern me is that this setup will be able to run the batteries very low. According to the voltage curve of a CR123A, it will be practically drained when reaching 1.7v. The same goes for two or three recharchable NiMH AAAs, that will have an individual voltage of 0.85v or 0.55v. Unless the batteries themselves have a discharge protection built in. In that case there might be no problem at all; I just don't know if batteries such as Eneloops have that.

So my questions are:

1) Do batteries such as CR123As and Eneloops have built in discharge protection so that they stop supplying power when the voltage is too low?

2) If no, will draining a non-rechargable CR123A be dangerous or problematic in any way? And will draining MiMHs down to 0.85v/0.55v hurt the batteries?

3) And, a question that I suppose applies to any battery powered Arduino project: When the supplied voltage drops below the Pro Minis BOD limit, will the Arduino stop using any power, or will it continue draining the batteries until they are completely empty? (In the first case I guess I could stick with the factory set BOD at 2.7v to protect the batteries.)

4) Finally, relating to the first question: Should I try to construct some kind of battery protection in the circuit, or is unnecessary when using CR123A and NiMH batteries?

title: Can batteries be damaged?

Answers: 1

body:
> 1) Do batteries such as CR123As and Eneloops have built in discharge protection so that they stop supplying power when the voltage is too low?

No, they don't.  They just run till there is nothing left.

> 2) If no, will draining a non-rechargable CR123A be dangerous or problematic in any way? And will draining MiMHs down to 0.85v/0.55v hurt the batteries?

A single cell can be run completely flat without problems. NiMH may need some "recovery" to wake them back up again, but shouldn't suffer serious problems (and no safety issues).  However, *batteries* are a different matter: see below.

> 3) And, a question that I suppose applies to any battery powered Arduino project: When the supplied voltage drops below the Pro Minis BOD limit, will the Arduino stop using any power, or will it continue draining the batteries until they are completely empty? (In the first case I guess I could stick with the factory set BOD at 2.7v to protect the batteries.)

It will continue draining power. The BOD is a *reset* circuit - designed to recover the system into a known good state after a dip in the power. A permanent decrease in the input power is beyond the scope of the BOD system.  It will just get stuck in a BOD reset loop and consume all your remaining power.

> 4) Finally, relating to the first question: Should I try to construct some kind of battery protection in the circuit, or is unnecessary when using CR123A and NiMH batteries?

For a single non-rechargeable cell you can just let it run flat. For NiMH you need to protect them.  Here's why (and what I was alluding to above):

----

When you have two or more cells in series (a *battery*) the current flows through all the cells of the battery equally. That is all fine when the cells are all fully charged - however no two cells are precisely the same.

As the battery runs down each cell will approach "empty" at a different time. With a single cell that's not really a problem, since it will just stop providing enough current to run.  However, with multiple cells one cell will run flat before the others. At that point the current provided by the other cells which still have some charge in them will be pushed through the flat cell *backwards*.  It is at that point that the flat cell becomes irrevocably damaged.  Current flowing backwards through the cell will try to *reverse charge* the battery and mess up the internal chemistry beyond recovery.

In the best case scenario, your battery will now have a much lower capacity and need recharging far more often. Worst case scenario: that damaged cell overheats and explodes.

The most prevalent problem that is caused by reverse charging is the depositing of metal crystals on the dielectric (the separator between the two electrodes) in the cell which grow and pierce the dielectric causing short circuits within the cell. There is no way back from that happening.

So you should protect your NiMH batteries from over-discharge by cutting the power to your circuit when the voltage drops below a specific threshold.  You should also recharge all the cells individually, not together in series, or they will end up unbalanced and the same problems of over-discharge can occur.

----

As a side note: I use the terms "cell" and "battery" with their "proper" usage: A *cell* is a single power-producing unit, such as an AA "battery".  A *battery* is a collection of cells.  This is the *proper* usage of the words, not the common usage where *battery* can also be taken to mean *cell*.  I use these terms specifically to differentiate between a single unit and a collection of units because of the major differences in how you need to handle them. It helps prevent confusion if you know that I am talking about just one AA (a cell) or a collection of three AA in series (a battery), for example.


body:
I am trying to interface 4052 demux with arduino, but my program is not working as high is not displayed on serial monitor corresponding to select lines.

    //output coming from demux pins
    int sensorValue0=A0;
    int sensorValue1=A1;
    int sensorValue2=A2;
    int sensorValue3=A3;

    void setup() {
      Serial.begin(9600);
      Serial.println("start");
      //select pins connected A,B connected to 2 and 3
      pinMode(2,OUTPUT);
      pinMode(3,OUTPUT);
    }

    void loop() {
      digitalWrite(2,LOW);
      digitalWrite(3,LOW);
      analogRead(sensorValue0);
      //Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
      int voltage0= sensorValue0 * (5.0 / 1023.0);
      Serial.println("volatge0");
      Serial.println(voltage0);
    }

title: 4052 interfacaing with arduino uno

Answers: 1

body:
You are ignoring the value read by `analogRead()`.  You are then using the value `A0` (14) in your sum to calculate the voltage.

Instead:

    int adcReading = analogRead(sensorValue0);
    int voltage0 = adcReading * (5.0 / 1023.0);

Although I *think* what you really meant to write was, in total:

    int sensorPin = A0;
    int sensorValue0;//output coming from demux pins
    int sensorValue1;
    int sensorValue2;
    int sensorValue3;

    void setup() {
    Serial.begin(9600);
      Serial.println("start");
      pinMode(2,OUTPUT);//selecr pins connected A,B connected to 2 and 3
      pinMode(3,OUTPUT);
    }

    void loop() {
      digitalWrite(2,LOW);
      digitalWrite(3,LOW);
      sensorValue0 = analogRead(sensorPin);
      float voltage0 = sensorValue0 * (5.0 / 1023.0);//Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
      Serial.print("voltage0 = ");
      Serial.println(voltage0);
    }

Note that the value `sensorPin` is where you read the voltage from, and `sensorValue0` is where you store that reading. Also note the use of a `float` type to store the calculated voltage, since an `int` will give you only values of 0, 1, 2, 3, 4 or 5 in this situation (so, pretty meaningless really).


body:
I have a Pro Micro board and I try to make it list my files as in the example of the Arduino IDE.
The pins I use are the following:

    board    micro sd module
       D4  ---> CS
       D15 ---> SCK
       D14 ---> MISO
       D16 ---> MOSI
       GND ---> GND
       VCC ---> VCC

On the serial monitor I get "initiallization failed".

What is wrong with my setup?

This is the code running:

    #include <SPI.h>
    #include <SD.h>

    File root;

    void setup() {
      // Open serial communications and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }

      Serial.print("Initializing SD card...");

      if (!SD.begin(4)) {
        Serial.println("initialization failed!");
        while (1);
      }
      Serial.println("initialization done.");

      root = SD.open("/");

      printDirectory(root, 0);

      Serial.println("done!");
    }

    void loop() {
      // nothing happens after setup finishes.
    }

    void printDirectory(File dir, int numTabs) {
      while (true) {

        File entry =  dir.openNextFile();
        if (! entry) {
          // no more files
          break;
        }
        for (uint8_t i = 0; i < numTabs; i++) {
          Serial.print('\t');
        }
        Serial.print(entry.name());
        if (entry.isDirectory()) {
          Serial.println("/");
          printDirectory(entry, numTabs + 1);
        } else {
          // files have sizes, directories do not
          Serial.print("\t\t");
          Serial.println(entry.size(), DEC);
        }
        entry.close();
      }
    }

And this is my wiring:
[![enter image description here][1]][1]
[![enter image description here][2]][2]
[![enter image description here][3]][3]

  [1]: https://i.stack.imgur.com/laViA.jpg
  [2]: https://i.stack.imgur.com/wxFk1.jpg
  [3]: https://i.stack.imgur.com/yT2KH.jpg

title: SD card failed to initialize

Answers: 2

body:
The SD library works only with FAT and FAT32 format. SD.begin() reads the 'disc volumes' and opens the root folder. If the card is not formatted or formatted with other file system standard, begin() fails.

EDIT: and the pin headers must be soldered

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

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

body:
Here's my setup code for my SD card for a little circuit where I was writing temperature data to the card.

    const int SD_CS = 10;
       const long SLEEP_TIME = 60000;  // write to card every minute
       long multiplier = 0;

       LiquidCrystal_I2C lcd(0x3F, 20, 4);

       void setup() {

         lcd.begin();
         lcd.setCursor(2,0);
         lcd.print("Hello, LCD!");

         if (SD.begin(SD_CS)) { // init SD
           lcd.setCursor(2,2);
           lcd.print("SD card init");
         }

     }

I set the CS pin to D10.
Try switching it to another pin like this and see if you get a different result.  I believe I had a challenge when I used pin 4 but can't quite remember.

**Note**: And of course remember to move your CS wire to pin D10 or whichever one you use.


body:
I'm reading a RFID Card from RC522 and send the data to my computer. My problem is the conversion of `byte[]` to `String` or `std::string`.

    #define SIZE_BUFFER     18
    #define MAX_SIZE_BLOCK  16

    byte buffer[SIZE_BUFFER] = {0};
    byte tam = SIZE_BUFFER;

    // get data
    status = mfrc522.MIFARE_Read(bloco, buffer, &tam);

      Serial.print(F("\nDados bloco ["));
      Serial.print(F("]: "));

    // printing...
     for (uint8_t i = 0; i < MAX_SIZE_BLOCK; i++)
      {
          Serial.write(buffer[i]);
          str += String(buffer[i]);
      }

OUTPUT:

    Dados bloco []: asdas

So, it's ok! But if I try make a string:

      String str = "";

      for (uint8_t i = 0; i < MAX_SIZE_BLOCK; i++)
      {
          str += String(buffer[i]);
      }
      Serial.println(" ");
      Serial.println(str);

The output is:

    97115100971153232323232323232323232

What is the correct way to create a `String` from `byte[]`?

title: Problems on convert byte[] to String

Answers: 2

body:
byte and char are the same. If you set 0 as string terminator after last character in the buffer, you get a zero terminated string. If you really must use String, you can create an instance with a constructor that takes zero terminated string.

    buffer[tam] = 0;
    String str((char*) buffer);

Let in the buffer a place for the zero. `(char*)` is cast that says that the byte array is a char array.

Note: Don't use String class in a MCU, use zero terminated character arrays.

body:
If you change `str += String(buffer[i]);` to `str += (char)buffer[i];`, it will print the ascii characters to the serial monitor.

The following sketch can be used to see the difference in binary compiled size using these two methods of "adding to the string".

    // 4026 to 3758 bytes.
    #define SIZE_BUFFER     18
    #define MAX_SIZE_BLOCK  16

    byte buffer[SIZE_BUFFER] = {
      0x61, 0x73, 0x64, 0x61,
      0x73, 0x20, 0x20, 0x20,
      0x20, 0x20, 0x20, 0x20,
      0x20, 0x20, 0x20, 0x20
    };

    String str = "";

    void setup(){

      Serial.begin(9600);

      for (uint8_t i = 0; i < MAX_SIZE_BLOCK; i++)
      {
          // 4026 bytes. Prints: "97115100971153232323232323232323232"
          //str += String(buffer[i]);

          // 3758 bytes. Prints: "asdas           "
          str += (char)buffer[i];
      }
      Serial.println(" ");
      Serial.println(str);
    }

    void loop(){}

Casting each element in the byte buffer to Char, then adding it to the string drops the binary compiled size from 4026 to 3758 bytes. This is good, but we can really improve the sketch by **not** using the `String` object at all.

This sketch is the same as the first one, except it uses a `Character Array` instead of a `String`.

    // 2074 bytes.
    #define SIZE_BUFFER     18
    #define MAX_SIZE_BLOCK  16

    byte buffer[SIZE_BUFFER] = {
      0x61, 0x73, 0x64, 0x61,
      0x73, 0x20, 0x20, 0x20,
      0x20, 0x20, 0x20, 0x20,
      0x20, 0x20, 0x20, 0x20
    };

    // Use a char array instead of the String object.
    char outputBuffer[SIZE_BUFFER];

    void setup(){

      Serial.begin(9600);

      for (uint8_t i = 0; i < MAX_SIZE_BLOCK; i++)
      {
          // 2074 bytes. Prints: "asdas           "
          outputBuffer[i] = (char)buffer[i];
      }
      Serial.println(" ");
      Serial.println(outputBuffer);
    }

    void loop(){}

The binary compiled size is 2074 bytes. That's 1684 bytes **less** than using the `String` object.

There are many functions available to work with `Character Arrays` on an Arduino, such as http://www.cplusplus.com/reference/cstring/ and http://www.cplusplus.com/reference/cstdlib/.


body:
I have the Arduino Uno and I'm working on a project to build a controller with different inputs and some outputs for readouts. In classic style, I got the Arduino Uno before realising that I might not have enough I/O points to connect everything I want.

I believe there is a way to expand my Uno by using an I/O Expander? Has anyone done something similar? The controller will be for a specific game called Kerbal Space Station. There are quite a few articles helping with the build but not specific to what I am looking at.

Components I'll be using:

INPUTS:

 - 2x 3 Axis Joysticks
 - 11x Microswitches
 - 6x Toggle switches
 - 1x Analogue slider
 - 1x 10 point rotary switch

OUTPUTS:

 - 4x 12 pin LED Bargraphs
 - 1x Serial LCD module display

title: Arduino Uno - Building a Controller

Answers: 2

body:
Yes, all those things have been done before.  Here's some suggestions for components:

* MCP23S17 / MCP23017 - SPI / I2C IO expander (16 IO pins, many can be connected together) ([MCP23S17 library](https://github.com/MajenkoLibraries/MCP23S17))
* MCP3208 - 8 channel 12-bit SPI ADC ([MCP3208 library](https://github.com/MajenkoLibraries/MCP3208))
* TLC59116 - I2C Constant Current LED PWM driver (16 channel) ([TLC59116 library](https://github.com/MajenkoLibraries/TLC59116))

Some other useful tutorials that may help:

* [Keypad](https://playground.arduino.cc/Main/KeypadTutorial) - read lots of buttons / switches with not many pins
* [Multiplex](https://www.instructables.com/id/LED-Multiplexing-101-6-and-16-RGB-LEDs-With-Just-a/) - Control many LEDs with not many IO pins

body:
Sparkfun also sells a SX1509 module for a very good price. It can do a matrix keyboard all on its own (hardware support) with similar (independent hardware-driven) LED heartbeat control. Aside from that, you can use any remaining pins as normal I/O (read/write/pwm).
There are 16 pins total, and it's controlled over I2C.

Adafruit also has a board called the Seesaw, which is a small Atmel SAMD09 with I2C slave firmware. It works similarly, but the pins are much more limited.

Either way, you simply include a library to your code, and use the object to interface with the pins rather than the usual functions on your Arduino. Most seem to use identical syntax (someclass.digitalWrite()...) to the normal Arduin functions.


body: I'd like to know please whether an Arduino can accept an HDMI signal from a satellite receiver, let it flow without any modification to the stream, and output it to TV?

title: Can Arduino accept HDMI input video stream, and output it without any modification to the video?

Answers: 1

body:
No.

HDMI uses multiple serial data streams at gigabit rates. No Arduino is ever going to do that sort of thing.  If you want something programmable to do that kind of thing you need an FPGA.