Motor does not work for a specific case when programming with L293D motor driver shield I tried to make a car that moves using a 4x4 keypad.
Pressing "12" unlocks the car and sets the motors to move forward. After that, if I press 4, the speed of the left motor is reduced to half allowing the motor to turn left, and vice versa for right wheel when key 6 is pressed.
Here is the code:
#include <Key.h>
#include <Keypad.h>

char* startCar = "12";
int position = 0, state = 0;

/*
 * state 0: off
 * state 1: forward
 * state 2: backward
 *
 */

const byte rows = 3;
const byte cols = 3;
char keys[rows][cols] = {
  {'1','2','3'},
  {'4','5','6'},
  {'7','8','9'}
};

byte rowPins[rows] = {2,3,4};
byte colPins[cols] = {PD7, PD6, PD5};
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, rows, cols);

int a=12,b=11,c=10,d=9;
void setup()
{
  pinMode(a,OUTPUT);
  pinMode(b,OUTPUT);
  pinMode(c,OUTPUT);
  pinMode(d,OUTPUT);
  Serial.begin(9600);
  setLocked(true);
}

void loop()
{
  char key = keypad.getKey();
  Serial.print(key);
  if (key == '9')
  {
    position = 0;
    setLocked(true);
  }
  if (key == startCar[position])
  {
    position ++;
  }
  if (position == 2)
  {
    setLocked(false);
  }
  if(state)
  {
    if(key=='2')
     {
      //Move forward
        state = 1;
        runmotors(255,0,0,255);
     }
     if(key=='8')
     {
      //Move backward
        state = 2;
        runmotors(0,255,255,0);
     }
    if(key == '4')
    {
      if(state == 1)
      {
        runmotors(127.5,0,0,255);
      }

      else if(state==2)
        runmotors(0,127.5,255,0);
    }
    if(key == '6')
    {
      if(state == 1)
        runmotors(255,0,0,127.5);
      else if(state==2)
        runmotors(0,255,127.5,0);

    }
  }
  delay(100);
}

void setLocked(int locked)
{
  if (locked)
  {
    state = 0;
    runmotors(0,0,0,0);
  }
  else
  {
    state = 1; // Moves forward
    runmotors(127.5,0,0,255);
  }
}
void runmotors(int s1,int s2,int s3,int s4)
{
  analogWrite(a,s1);
  analogWrite(b,s2);
  analogWrite(c,s3);
  analogWrite(d,s4);
}

Everything works perfectly, except for the fact that when the state is 1, i.e. car is running forward, and I press 4 the left motor completely stops instead of reduced speed. The LED on the motor driver shield which shows whether a motor is running or not also goes off.
It is not a fault of the motor shield or the arduino as it worked when I test it individually with the motors (i.e. without the keypad etc).
Here is a photo of the shield:

Although my problem is not quite visible in this, but here is a video of the car: https://www.youtube.com/watch?v=bq19gNOL8Pg

On an UNO only certain pins are capable of PWM.  Pin 12 is not one of them.  When you try to call analogWrite with pin 12 it will recognize this and will simply call digitalRead for you with HIGH or LOW depending on whether your input is greater than 127.
With most motor controllers you can use one pin as a direction pin and the other as a PWM pin.  So to go one direction you set pin 12 HIGH and do inverted PWM on 11 (if those indeed go to the same motor I didn't look at your shield).  To go the other direction you write LOW on 12 and PWM on 11.
The motor turns when one pin is HIGH and the other is LOW.  When you set pin 12 high then PWM pin 11, whenever 11 is LOW in the PWM cycle it is turning the motor on and when it is HIGH it is turning it off.  So to make it run you might have to PWM 0 for go and 255 for stop.  Sometimes your PWM is on the enable line and then you still use 255 for go and 0 for stop.  It just depends on how things are wired.
When pin 12 is set to LOW then the motor is on when 11 is at the high part of the PWM cycle and off when it's low so you use 255 for go and 0 for stop.  But the whole time pin 12 doesn't have to change.
Now I am not 100% sure that this is the case with your particular motor controller, I'm more of a coder than a hardware guy.  But I've written enough code for motor controllers to know that you usually either need two direction lines and one PWM line or one direction and one PWM.  If that's not the case here then we can let someone else work on why.


How does Arduino IDE 'Get Board Info'? I want my C# application to automatically select the correct COM port by way of a string equality check against a 'GetInfo'-type request to the Arduino board.

I know the Arduino IDE can get info from the board;

Tools > GetBoardInfo

But I don't know how to get it using a sketch or if it is even possible for that matter.

Is this something that can be read from the board, or is it a USB-thing. If it's a USB thing, I'd have to get the info from GetUSBDevices.DeviceID or whatever, then get the serial port used by the USB Device, which would probably work, but I'd rather do it all via a serialPort.

Looking at the source code of the Arduino IDE on github, it looks like they call an executable (listComPorts.exe). So I would guess you can't get that info through serial.

Here's a C# app using WMI that can get port, vid, and pid:

namespace PortTest
{
    class Program
    {
        // Helper function to handle regex search
        static string regex(string pattern, string text)
        {
            Regex re = new Regex(pattern);
            Match m = re.Match(text);
            if (m.Success)
            {
                return m.Value;
            }
            else
            {
                return null;
            }
        }

        static void Main(string[] args)
        {
            // Use WMI to get info
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2",
                "SELECT * FROM Win32_PnPEntity WHERE ClassGuid=\"{4d36e978-e325-11ce-bfc1-08002be10318}\"");

            // Search all serial ports
            foreach (ManagementObject queryObj in searcher.Get())
            {
                // Parse the data
                if (null != queryObj["Name"])
                {
                    Console.WriteLine("Port = " + regex(@"(\(COM\d+\))", queryObj["Name"].ToString()));
                }
                //PNPDeviceID = USB\VID_1A86&PID_7523\5&1A63D808&0&2
                if (null != queryObj["PNPDeviceID"])
                {
                    Console.WriteLine("VID = " + regex("VID_([0-9a-fA-F]+)", queryObj["PNPDeviceID"].ToString()));
                    Console.WriteLine("PID = " + regex("PID_([0-9a-fA-F]+)", queryObj["PNPDeviceID"].ToString()));
                }
            }
            Console.WriteLine("Done");
            int c = Console.Read();
        }
    }
}

From there, it looks like it searches an online database for more info. See: getBoardWithMatchingVidPidFromCloud() function.


ESP8266 malloc/calloc-related crashes ("segfaults") This is sort of the continuation of this problem. After getting hints that the problem I had were related to bad memory, I checked all of my heap-allocating code again and found a malloc that didn't allocate enough memory for an array. After fixing that and fiddling around with calloc, which may be safer for array-related stuff, I think I exposed the actual programming errors themselves. The crash message I get now is:
No poison after block at: 0x3fff0fb8, actual data: 0x84 0xf 0xff 0x3f

User exception (panic/abort/assert)
Panic umm_malloc.cpp:422 umm_malloc_core

which sounds to me like some sort of ESP segfault. The code where this happens according to the stack trace is the following:
Menu* createMenuStructure(ace_time::TimeZone* mainTZ) {
  // create an array of all clock faces, i.e. a pointer to an array of function pointers
  void (**allClockFaces)(T_DISPLAY*, ace_time::ZonedDateTime*);
  // funkiest malloc in the world; undefined behavior? I hope not.
  allClockFaces = (void (**)(T_DISPLAY*, ace_time::ZonedDateTime*)) calloc(DESIGN_MENU_SIZE, sizeof(*allClockFaces));
  // initialize array
  allClockFaces[0] = &basicDigitalCF;
  allClockFaces[1] = &digitalWithSecondsCF;
  allClockFaces[2] = &basicAnalogCF;
  allClockFaces[3] = &binaryCF;
  allClockFaces[4] = &fullDayBinaryCF;
  ClockFaceSelectMenu* cfMenu = (ClockFaceSelectMenu*) malloc(sizeof(ClockFaceSelectMenu));
  cfMenu = new ClockFaceSelectMenu((char**)design_menu, (size_t)DESIGN_MENU_SIZE, allClockFaces);

  // time zone select menu
  TimeZoneSelectMenu* tzMenu = (TimeZoneSelectMenu*) malloc(sizeof(TimeZoneSelectMenu));
  tzMenu = new TimeZoneSelectMenu();

  Menu** allMenus = (Menu**) calloc(3, sizeof(*allMenus));
  // initialize first layer of sub menus
  allMenus[0] = cfMenu;
  allMenus[3] = tzMenu;

  OptionsMenu* mainMenu = (OptionsMenu*) malloc(sizeof(OptionsMenu));
  mainMenu = new OptionsMenu((char**)main_menu, (size_t)MAIN_MENU_SIZE, allMenus);

  // for now, manually set the sub menu's parent to the main menu. When all menus are finished, the main menu will do this automatically
  allMenus[0]->parent = mainMenu;
  allMenus[3]->parent = mainMenu;

  ClockMenu* clk = (ClockMenu*) malloc(sizeof(ClockMenu));
  // timeClient is a global NTPClient variable
  clk = new ClockMenu(&timeClient, mainTZ, (Menu*)mainMenu);

  return clk;
}

All names containing Menu are classes derived from that base class, and the top couple of lines allocate an array of function pointers. And just to be clear: This code was working perfectly fine for the last several days of development until I made some changes to the SD card functionality that caused the constant crashes.
I am not very used to working in manual memory management. Is this way of allocating appropriate, and if so, correct? What am I doing wrong, or does the error lie somewhere else in the (~1500sloc) project?
Edit: Although the issue is already solved, thanks to the approved answer, I wanted to clarify that the constants used in the array allocation are all correct and correspond to the string array's length. E.g. main_menu is a string array of length 5 and MAIN_MENU_SIZE is a constant defined right next to the array definition that is also defined to 5. This is of course necessary as C arrays have no way (that I know of) of finding the length of complex pointer arrays such as these.

You wrote:

// funkiest malloc in the world

Funky, indeed. ;-) I kind of like its twisted beauty, but not everyone
does. Some may urge you to typedef that function type.

allClockFaces[4] = &fullDayBinaryCF;

Are you sure DESIGN_MENU_SIZE is strictly larger than 4? Maybe an
assert() would be good to use here.

ClockFaceSelectMenu* cfMenu = (ClockFaceSelectMenu*) malloc(...);
cfMenu = new ClockFaceSelectMenu(...);

You are assigning a value to cfMenu twice in a row, which means the
value assigned first is lost. This is a memory leak. You do not need
malloc() here, as new takes care of the memory allocation prior to
initializing the object. This error is repeated several times in this
function.

allMenus[3] = tzMenu;

allMenus has length 3: valid indices range from 0 to 2. This is an
out-of-bounds array access, and the likely cause of the errors you see.


Motion sensor large areas I'm looking to build a motion sensor which detects if an object is in the monitored area. Doing some researched I found out that I can use PIR motion sensor for this but it seems the area it monitors is pretty small.

I need something that can monitor about 3 feet x 1 feet area. Is there something else that I can use for this?

My goal is to light up some LED lights when an object is detected in that area.

Thanks in advance.

A standard PIR motion sensor will work fine.  It can monitor motion in a very room.  You just need to make sure the PIR sensor is far enough away.

Here is one article that states it should work up to 10 meters away.

https://www.mobotix.com/eng_US/Support/FAQ/Configuration2/What-is-the-range-of-the-PIR-Passive-Infrared-motion-detector

Note that the device that the PIR sensor is mounted on must be stationary.  It will not work on a robot of anything that is moving.


I can't seem to receive data to the ArduinoStudio serial monitor on ubuntu 14.04 I'm using the Arduino Starter Kit so I have a Uno R3 and going through the examples I'm trying to read temperature data from my controller in Arduino Studio.
In essence my problem can be reduced down to
void setup() {
    Serial.begin(9600);
}

void loop() {
    Serial.print("stuff");
}

Which I'd expect to keep printing "stuff" on the serial monitor.
(In practice I'm running this exact code but all the temperature-reading going on feels irrelevant to my problem, I'm simply mentioning it because I can observe that mye LEDs light up when the temperature rises so I know the code is uploaded and running on the Duo).
I'm not seeing any errors in the studio console, and if I connect using gtkterm or screen I can see data being sent so the problem seems to be isolated to the AndroidStudio serial monitor itself.
I'm running Ubuntu 14.04 and I've connected via USB on /dev/ttyACM3.
I tried running

stty -F /dev/ttyACM3 cs8 9600 ignbrk -brkint -icrnl -imaxbel -opost -onlcr -isig -icanon -iexten -echo -echoe -echok -echoctl -echoke noflsh -ixon -crtscts

as suggested here and I also tried with baud 115200, taking care to also change the value in my setup function.
I also ran

chmod a+rw /dev/ttyACM3

But I'm still not seeing any errors or output. How do I proceed to debug this issue?
Running ls -l /dev/ttyACM* gives

crw-rw---- 1 root dialout 166, 0 feb.  20 14:22 /dev/ttyACM0
crw-rw---- 1 root dialout 166, 1 feb.  20 14:22 /dev/ttyACM1
crw-rw---- 1 root dialout 166, 2 feb.  20 14:22 /dev/ttyACM2
crw-rw-rw- 1 root dialout 166, 3 feb.  20 14:30 /dev/ttyACM3

By default, on a linux system without specific
udev binding rules to rename the device into something non standard, the FTDI driver should map the usb to serial port on /dev/ttyUSB* and not to /dev/ttbACM*. I suspect that you were just looking in the wrong place.
I think it defaults to /dev/ttyUSB* for any usb to serial dongle:

usb-serial.c:   usb_serial_tty_driver->name = "ttyUSB";


Powering Arduino Uno and Ardumoto Motor Driver Shield I need to power an Ardumoto Shield to drive two 12V DC motors. I was planning to connect a 12V battery to the Max 18V input on the Ardumoto and a 9V battery to the barrel jack input of the Arduino Uno.  Can you tell me if this should be ok or if it would cause any damage to the Arduino?

It mentions in the Ardumoto hookup guide:

There's no mention of the Max 18V input on the Ardumoto.. Advice appreciated, thanks.

Do not supply power to both the Arduino barrel jack input and VIN on the shield!

There goes the simple answer. Choose one.

If you power the system through arduino barrel jack input, you will have polarity protection, but the voltage output on VIN pin (which also used by Ardumoto shield) is slightly lower, about 0.6V lower than the input voltage because of the voltage drop on the protection diode.

If you have want to differentiate the supply for Ardumoto and Arduino (as described on your plan), you have to tamper the Ardumoto shield to isolate both supply. Although I never try it myself, it seems possible if you understands how L298 works.


Is it possible to upload a program from a tablet? Is there any easy way to upload a program/sketch from an iPad or Android tablet without adding extra an shield (Bluetooth or Wi-Fi)?

If not, can it be done using shield? Which shield is preferred?

Also what are the IDE options available?

I figured out a way to do this without having to port the compiler to iOS. It only works with the arduino Yún, but the Yún can send code to other arduinos with an spi cable.

Install an SSH app on your device so you can communicate with the arduino
Using that, install Ino on your Yún, a command line arduino compiler
Create a file, put your code in it, then save it
use Ino to upload your code!

kind of confusing, but it could work!


Reset arduino nano after disabling tx/rx I know, i am a bit dummy sometimes and i don't know why i actually did this but here it is. I have an arduino nano and i want it to use an external power via the the Vin port using a 12V external power supply. I thought this would be as simple as replacing the usb power supply by my external 12V power supply on the Vin pin.
But nothing works so i did some digging on the problem and after many tries like soldering the pins 25 and 26 of the FTDI or connect the TX/RX pins to the GND. Concerning that last point, because the TX/RX was still flashing after beeing connected to the GND i have put in my program this two lines to force TX/RX to be disabled and this is my mistake :

digitalWrite(0,LOW);
digitalWrite(1,LOW);

And now what a surprise i can't load a program in my arduino nano anymore even using another arduino to burn the bootloader. And i get this message :

avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x30
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x2e
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x30
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x30
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x2c
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x33
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x38
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x2e
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x33
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x31

I would like to come back to my factory arduino nano and/or enable once again the TX/RX connections ...

After some more tries something actually worked reinitialising the TX/RX pins, but i don't know why really. I wired RX pin to the reset and i loaded an empty code into the arduino, after that i was able to load any program into my arduino again. Problem solved, but why it solved the problem is the question now.


Strange behaviour on splitting char array and converting the chunks to int I have this function:

void changeColor(char control[16])
{
  char _red[3], _green[3], _blue[3], _brightness[3], _white[3];
  int red, green, blue, brightness, white, offset;

  offset = 1;
  for (int i = 0; i < 3; i++) {
    _red[i] = control[i + offset];
  }
  offset = 4;
  for (int i = 0; i < sizeof(green); i++) {
    _green[i] = control[i + offset];
  }
  // strncpy(_green,control+offset,3); // same result
  offset = 7;
  for (int i = 0; i < sizeof(_blue); i++) {
    _blue[i] = control[i + offset];
  }
  offset = 10;
  for (int i = 0; i < sizeof(_white); i++) {
    _white[i] = control[i + offset];
  }
  offset = 13;
  for (int i = 0; i < sizeof(_brightness); i++) {
    _brightness[i] = control[i + offset];
  }

  red = atoi(_red);
  green = atoi(_green);
  //sscanf(_green, "%d", &green); //same result
  blue = atoi(_blue);
  white = atoi(_white);
  brightness = atoi(_brightness);

  Serial.print(" control ");
  Serial.println(control);
  Serial.print(" _red ");
  Serial.println(_red);
  Serial.print(" _green ");
  Serial.println(_green);
  Serial.print(" _blue ");
  Serial.println(_blue);
  Serial.print(" _white ");
  Serial.println(_white);
  Serial.print(" _brightness ");
  Serial.println(_brightness);
  Serial.print(" red ");
  Serial.println(red);
  Serial.print(" green ");
  Serial.println(green);
  Serial.print(" blue ");
  Serial.println(blue);
  Serial.print(" white ");
  Serial.println(white);
  Serial.print(" brightness ");
  Serial.println(brightness);
  //... do something with ints
}

And by calling from the setup:

 char _control[16]={'6','2','5','5','0','0','0','0','0','0','0','0','0','0','5','0'};
 //6255000000000050

 void setup() {
   Serial.begin(9600);
   // ... do something
   while (!Serial) {
     ; // wait for serial port to connect. Needed for native USB
   }
  changeColor(_control);
}

I get from console this output:

   control 6255000000000050
   _red 255ÿ
   _green 000255ÿ
   _blue 000000255ÿ
   _white 000050000000255ÿ
   _brightness 050000000255ÿ
   red 255
   green 255
   blue 255
   white 29951
   brightness 29951

Basically, the char array are filled with more elements than the actual dimension (3), but I don't get error or warnings from the compiler

I also tried with strncpy, strcpy, strncat, and by using the pointer in the for loops

for(int i=0;i<sizeof(_green);i++){
  _green[i]=control+i*sizeof(char)+offset*sizeof(char);
} // also without the sizeof()

And I got the same result in the console (with nl&cr), any hints?

EDIT:

Added NULL char

  ...
  char _red[4], _green[4], _blue[4], _brightness[4], _white[4];
  int red, green, blue, brightness, white, offset;
  _red[4]='\0';
  _green[4]='\0';
  _blue[4]='\0';
  _white[4]='\0';
  _brightness[4]='\0';
  offset=1;
  for(int i=0;i<3;i++){
    _red[i]=control[i+ offset];
  }
  // same as above

Output:

control 6255000000000050
_red 255
_green 100255
_blue 000100255
_white 0000050
_brightness 050
red 255
green 100
blue 0
white 50
brightness 50

In this piece of code you have a strange mix of upper bounds:

  for(int i=0;i<3;i++){
    _red[i]=control[i+offset];
  }
  offset=4;
  for(int i=0;i<sizeof(green);i++){
    _green[i]=control[i+offset];
  }
 // strncpy(_green,control+offset,3); // same result
 offset=7;
 for(int i=0;i<sizeof(_blue);i++){
   _blue[i]=control[i+offset];
 }
 offset=10;
 for(int i=0;i<sizeof(_white);i++){
   _white[i]=control[i+offset];
 }
 offset=13;
 for(int i=0;i<sizeof(_brightness);i++){
   _brightness[i]=control[i+offset];
 }

The first looks correct at 3.  The second loop has an upper bound of sizeof(int) which is 2.  The third loop seems to be sizeof(char) which is 1.

Unfortunately non of those values match up with the results you are getting.  What I would try is refactoring whats inside you function to this.

int Convert (char* buffer, char const* control, const int& offset, char const* name)
{
    int value = 0;
    for (index = offset; index < offset; ++index)
    {
        buffer[index-offset] = control[index];
    }
    buffer[4] = '\0';
    atoi(buffer);
    Serial.print(name);
    Serial.print(" = ");
    Serial.print(buffer);
    Serial.print("  Value = ");
    Serial.println(value);
    return value;
}

And then call it to populate your values:

void changeColor(char control[16])
{
    char buffer[4]; // You can reuse this buffer, unless you wanted to have separate ones.
    const int red    = Convert (buffer, control, 1, "red");
    const int green  = Convert (buffer, control, 4, "green");
    const int blue   = Convert (buffer, control, 7, "blue");
    const int white  = Convert (buffer, control, 4, "white");
    const int bright = Convert (buffer, control, 4, "bright");
}


ATMega I/O maximum current According to the ATmega328P datasheet, the total current from all I/O pins must not exceed 200mA.

Let's say that an Output pin sources 30mA and an Input pin sinks 10mA. The total current should be 30+10=40mA or 30-10=20mA?

Neither. First, inputs don't draw current. Whether you're sourcing current or draining it, it will always be an output pin.

The 200 mA rule is probably determined by the bonding wires for the Vcc and ground pins on the die. That means that all outputs which are sourcing current shouldn't source more than 200 mA combined, as this current will have to enter the device through the Vcc pin.
Likewise all outputs sinking current shouldn't sink more than 200 mA combined, as this current will drain through the ground pin.


Does enabling the Timer1 CompareA interrupt instantly triggers an interrupt? I am learning Arduino interruptions and I am unable to explain the behavior of a minimalistic interrupt driven project. The project is the following: an Arduino UNO is connected to two LEDs, on ports 9 and 10, and a button on port 2. The button is listened to for RISING interruptions, which are expected to trigger the following 3 seconds sequence: LED1 HIGH (one second); both LEDs HIGH (one second); LED2 HIGH (one second); during which pressing the button should have no effect.

#define led1Pin 10
#define led2Pin 9
#define buttonPin 2

void setup() {

  cli();//stop interrupts

  pinMode(led1Pin, OUTPUT);
  pinMode(led2Pin, OUTPUT);
  pinMode(buttonPin, INPUT);
  digitalWrite(led1Pin, LOW);
  digitalWrite(led2Pin, LOW);
  attachInterrupt(digitalPinToInterrupt(buttonPin), f, RISING);

  TCCR0A = 0;// set TCCR2A register to 0
  TCCR0B = 0;// set TCCR2B register to 0 (sets timer0 prescaler values to "disable timer")
  TCCR2A = 0;// set TCCR2A register to 0
  TCCR2B = 0;// set TCCR2B register to 0 (sets timer2 prescaler values to "disable timer")

  //set timer1 interrupt at 1Hz
  TCCR1A = 0;// set TCCR1A register to 0
  TCCR1B = 0;// set TCCR1B register to 0

  // set compare match register for 1hz increments
  OCR1A = 15624;// = (16*10^6) / (1*1024) - 1
  TCCR1B |= (1 << WGM12);   // turn on CTC mode 1 (compare to OCR1A)
  TCCR1B |= (1 << CS12) | (1 << CS10);// CS12|CS10 => Prescaler 1024
  TIMSK1 = 0;// disable timer compare interrupt

  sei();
}

volatile int index=0;

volatile byte previousState=LOW;
volatile byte state = LOW;

void loop() {
  if (state && !previousState) {
    digitalWrite(led1Pin, HIGH); index=1;
    TCNT1H = 0;
    TCNT1L = 0; //initialize counter value to 0
    TIMSK1 |= (1 << OCIE1A); // enable timer compare interrupt
    previousState = HIGH;
  }
}

void f() {
  state = HIGH;
}

ISR(TIMER1_COMPA_vect){ //timer1 interrupt 1Hz
  switch(index) {
  case 1:
    digitalWrite(led2Pin, HIGH); index=2;
    break;
  case 2:
    digitalWrite(led1Pin, LOW); index=3;
    break;
  case 3:
    digitalWrite(led2Pin, LOW); index=0;
    state=LOW; previousState=LOW;
    TIMSK1 = 0;// disable timer compare interrupt
    break;
  default:
    break;
  }

}

Code adapted from https://www.instructables.com/id/Arduino-Timer-Interrupts/

Upon pressing the button, state is set to HIGH, which assuming previousState and state were LOW, should get the loop to perform a set of action once as it will set previousState HIGH.

These actions are the following: set led1Pin to HIGH, set TCNT1H and TCNT1L to 0, which should put the Timer1 counter to 0, and then set TIMSK1 to 0b00000010, that is, 1 << OCIE1A, to accept the interrupt when it will be triggered, supposedly one second from the instruction that set the counter to 0, as the timer fires interrupts at 1Hz.

But while the expected behaviour is LED 1 on for one second, both LEDs on for one second, then LED 2 on for one second, the observed behaviour is the following, from my tests:

First time pressing the button since Arduino reset : LED 1 and LED 2 on for one second, LED 2 on for one second.
Button presses properly ignored until LED 2 turns off.
Subsequent button presses : either proper behaviour (LED1 on, both LEDs on, LED2 on); or "first press" behaviour (both LEDs on, LED2 on). In both cases, the cycle sometimes instantly restart ([optional : LED1 on;] both LEDs on; LED2 on; LED1 on; both LEDs on; LED2 on), with each state taking one second.

The non-deterministic nature of the problem lets me think I'm mishandling interruptions. The project behaves as if enabling timer compare interrupts instantly triggered one, despite setting the relevant registers to 0 before that. I was unsuccessful in finding information regarding this that would explain the problem.

Is there asynchronous behaviour when setting the TCNT1H and TCNT1L registers to 0 ? Can a compare match interruption somehow be buffered ? And how comes the cycle sometimes execute twice ?

The project behaves as if enabling timer compare interrupts instantly
  triggered one

This can indeed happen, and it's likely what you are experiencing.

Explanation: an interrupt fires when three bits are simultaneously set:

the “interrupt flag” that signals the detection of some specific event
the “interrupt enable” bit associated with that particular interrupt
the “global interrupt enable” bit that is set by the sei()
instruction

In your case, the relevant interrupt flag is OCF1A (Timer/Counter1,
Output Compare A Match Flag), in register TIFR1 (Timer/Counter1
Interrupt Flag Register). This flag is raised by a “timer compare”
event, i.e. when the timer value hits the value stored in OCR1A. If
the interrupt fires, the flag is automatically cleared when the CPU
starts executing the corresponding ISR. Alternatively, the flag can be
cleared manually by overwriting it with a logic 1 (yes, that's kind of
backwards). It is worth noting that the flag records the compare events
whether or not the interrupt is enabled.

You normally expect the interrupt flag to be the last of these three
bits to be set, so that the interrupt is triggered by the compare event.
But this need not be the case. In your program, it is likely that the
interrupt flag is raised one second after startup. The global interrupt
enable is set by your sei() at the end of setup(). Thus, at this
point, as soon as you set the interrupt enable bit the interrupt fires
immediately.

The standard solution to this problem is to clear the interrupt flag
right before setting the interrupt enable bit:

TIFR1  |= _BV(OCF1A);   // clear timer compare flag
TIMSK1 |= _BV(OCIE1A);  // enable timer compare interrupt


Teensy 2.0 with MCP23017-E I've recently bought two more MCP23017-E's for a project, but after hooking them up to my Teensy 2.0 I couldn't get them to react to anything. Suspecting faulty hardware, I hooked them up to an old LCP1114, and got them running just fine. I've tried porting the code I used, which still gave no result.

I'm using the following code:

#include "Wire.h"
const byte device=0b01000000; //default addrress of IO chip

const byte IODIRA=0x00;
const byte IODIRB=0x01;

const byte GPIOA=0x12; //IO pins, port A
const byte GPIOB=0x13; //IO pins, port B
const byte OLATA=0x14;//O pins A
const byte OLATB=0x15;//O pins B

const byte GPPUA=0x0C; //pull up resistors ,port A
const byte GPPUB=0x0D; //pull up resistors ,port B

char iCounter = 0;

void setup() {
  Wire.begin();
  seti2cbyte(device,IODIRA,0x00);
  seti2cbyte(device,IODIRB,0xFF);
  seti2cbyte(device,GPPUB,0xFF);  //enable pull-up resistors on port B
}

byte geti2cbyte(byte address, byte ptr) {
  Wire.beginTransmission(address);
  Wire.write(ptr);
  Wire.endTransmission();
  Wire.requestFrom(address, 1); // request one byte of data from MCP20317
  byte inputs=Wire.read();
  return inputs;
}

void seti2cbyte(byte address, byte ptr, byte value) {
  Wire.beginTransmission(address);
  Wire.write(ptr); // set MCP23017 memory pointer to GPPUA address
  Wire.write(value); // enable pull up resistors
  Wire.endTransmission();
}

void loop() {
  seti2cbyte(device,OLATA,iCounter);
  byte port_b = geti2cbyte(device,GPIOB); //get status of pins 21-28
  Serial.print(iCounter++);Serial.println(port_b);
  delay(500);
}

I don't see a blinking LED, and port_b stays at 255 (or -1 I figured after reading the Wire.cpp)

I've tried different methods, even running SPI myself (setting pins high and low manually). The only difference I see is that the Teensy 2.0 is 5V, and the LCP1114 runs at 3.3V. The data sheet for the MCP23017-E states that it is also rated for 5V though.

Why does it seem like my MCP23017-E's won't work at 5V, while the data sheet states they should?

MCP23017-E datasheet

  • Operating Voltage:
  - 1.8V to 5.5V @ -40°C to +85°C
  - 2.7V to 5.5V @ -40°C to +85°C
  - 4.5V to 5.5V @ -40°C to +125°C

You have the wrong device address. You've included the R/W bit in the address, which you shouldn't.  An I2C address is only 7 bits, not 8.  Drop one bit:

const byte device=0b0100000; //default addrress of IO chip


Uploading Error: no programmer has been specified Whenever I upload a code I get this error:

avrdude: no programmer has been specified on the command line or the config file
         Specify a programmer using the -c option and try again

I am able to upload from other PCs, but ever since I got the newest IDE, it stopped working. I even tried downgrading to 1.6.8, and still i get this error... Any help? Thanks,

Sean

This issue occurs when using Arduino IDE 1.6.8 or older with Arduino AVR Boards 1.6.12 or 1.6.14. There are two solutions:

Upgrade your Arduino IDE to 1.6.9 or newer by downloading and
installing the appropriate file from
https://www.arduino.cc/en/Main/Software.
Downgrade your Arduino AVR Boards version to 1.6.11 or older(or 1.6.13) via
Tools > Board > Boards Manager...

I submitted a pull request to fix this backwards compatibility issue and it was merged by the Arduino developers so this issue will no longer occur with Arduino AVR Boards 1.6.15 and up. It explains the cause of the issue:
https://github.com/arduino/Arduino/pull/5427


DHT sensors with RGB LED I have a DHT11 that outputs temperature and humidity values to my serial monitor. I'm trying to serial the COLOUR of the light based on the temperature conditions. So far I only get 1's and 0's. How can I change these integer values to output string say RED, GREEN or BLUE?

Code

#include <dht.h>

dht DHT;
#define DHT11_PIN A5
int redPin = 10; // Red LED,  connected to digital pin 10
int grnPin = 9; // Green LED, connected to digital pin 9
int bluPin = 8;  // Blue LED, connected to digital pin 8

void setup() {
  Serial.begin(9600);
  // Sets the pins as output for RGB LED
  pinMode(redPin, OUTPUT);
  pinMode(grnPin, OUTPUT);
  pinMode(bluPin, OUTPUT);
}

void loop() {
  int chk = DHT.read11(DHT11_PIN);
  int t = DHT.temperature;
  int h = DHT.humidity;
  Serial.print("Temperature = ");
  Serial.print(t);
  Serial.print( "," );
  Serial.print("Humidity = ");
  Serial.print(h);
  Serial.print("\n");
  delay(60000);
  if((DHT.temperature < 26) && (DHT.temperature >= 23.2)) {
    // Writing the LED colour pins HIGH or LOW to set colours
    digitalWrite(redPin, HIGH); // yellow
    digitalWrite(grnPin, HIGH);
    delay(100);
    digitalWrite(bluPin, LOW);
  }
  if((DHT.temperature < 23) && (DHT.temperature > 20.2)) {
    digitalWrite(grnPin, HIGH); // green
    delay(100);
    digitalWrite(redPin, LOW);
    digitalWrite(bluPin, LOW);
  }
  if((DHT.temperature < 20) && (DHT.temperature > 17.2)) {
    digitalWrite(grnPin, HIGH); // aqua
    digitalWrite(bluPin, HIGH);
    delay(100);
    digitalWrite(redPin, LOW);
  }
  if(DHT.temperature <= 17) {
    digitalWrite(bluPin, HIGH); // blue
    delay(100);
    digitalWrite(grnPin, LOW);
    digitalWrite(redPin, LOW);
  }
  delay(1000);
  // Sensor shouldn't be read too frequently so delay of 1s
}

I will be grateful if I can get some help. Thanks!

So far I only get 1's and 0's

Before moving into the LED parts, you have to make sure that your system can correctly read the DHT sensor. There are debugging example from arduino-info.wikispaces.com

  How can I change these integer values to output string say RED, GREEN or BLUE?

You can do it by simple if-else statement. This would be better than your original code, because there are multiple if's without any else which is (although not so significant) less optimal.

So, if put together, you can try:

void loop()
{
  int t,h,chk = DHT.read11(DHT11_PIN);

  switch (chk)
  {
    case DHTLIB_OK:
                Serial.print("OK,\t");
                break;
    case DHTLIB_ERROR_CHECKSUM:
                Serial.print("Checksum error,\t");
                break;
    case DHTLIB_ERROR_TIMEOUT:
                Serial.print("Time out error,\t");
                break;
    case DHTLIB_ERROR_CONNECT:
        Serial.print("Connect error,\t");
        break;
    case DHTLIB_ERROR_ACK_L:
        Serial.print("Ack Low error,\t");
        break;
    case DHTLIB_ERROR_ACK_H:
        Serial.print("Ack High error,\t");
        break;
    default:
                Serial.print("Unknown error,\t");
                break;
  }
  //moving on into next parts only if you get "OK" from serial reply, which means you successfully read the DHT11
  t = DHT.temperature;
  h = DHT.humidity;
  Serial.print(DHT.humidity, 1);
  Serial.print(",\t");
  Serial.println(DHT.temperature, 1);

  //----end of sensor reading and debugging

  if (t<=17)
  { //blue
   digitalWrite(bluPin, HIGH);
   digitalWrite(grnPin, LOW);
   digitalWrite(redPin, LOW);
   delay(100);
  } else
      if (t<20)
      {
       digitalWrite(grnPin, HIGH);  // aqua
       digitalWrite(bluPin, HIGH);
       digitalWrite(redPin, LOW);
       delay(100);
      } else
      if (t<23)
      {
        //....
      }
      //....
      //and goes on

 delay(1000);
}

And yes, as @Matt suggest, it would be better if you use PWM to control the RGB led which will give you (mathematically) 255*255*255 colour possibilities instead of 8 combinations from digitalWrite(). For example:

//....
//....
  if (t<20)
  { //aqua
   new_t = map(t,DHT11_min_temperature_reading,DHT11_max_temperature_reading,0,255);
   //you can do self research about DHT11 maximum and minimum temperature reading
   //parameters 0 and 255 is the minimum value of PWM(0) and the maximum value(255)
   AnalogWrite(bluPWMPin, new_t);
   AnalogWrite(grnPWMPin, 255-new_t);
   AnalogWrite(redPWMPin, 0);
   delay(100);
  }
//....
//....

Hope it helps :D


Normally-Open opto-coupler board I'm looking for a Normally-Open optocoupler board for arduino. I need to control power of a device (DC 12v, 500mA).
I tried to use TLP281 board, which works, except that it inverts the output: device is powered when there is no control signal (i.e., it is Normally-Closed).

For this reason, the TLP281 board is not useful in my project.

This is picture and schematics for TLP281 board:

I need an optoisolator board which works analogous to normally open mechanical relay: when there is no signal, device must not be powered; and when there is signal, device must be powered.

NOTE: workaround by inverting the control signal in microcontroller firmware is not permitted, as the device must not be powered when microcontroller is off

I don't think there is a need for a specific "normally-open" opto-coupler. Same result can be easily achieved by using "normally-closed" opto-coupler and making a slightly modified "NOT" logic gate using three resistors and NPN transistor.

1. When INPUT is LOW:

Base of Q1 is shorted to ground through R1 so Q1 not letting the magic pixies go through. This makes OUTPUT show 5V and be in HIGH logic state.

2. When INPUT is HIGH:

Base of Q1 is powered by voltage divider R/R1. R needs to be much lower than R1 to keep Q1 saturated. This makes Q1 to be passing current and setting OUTPUT to LOW state by creating a voltage divider R2/Q1(collector-emitter resistance) This means that value of R2 should be much higher then c-e resistance of Q1.

3. When INPUT is floating (microcontroller is turned off):

Any voltage on INPUT caused by imperfections of the hardware, E-M noise induction, static electricity, etc. should be discharged to ground by resistors R+R1 keeping INPUT in LOW state. (This means that R+R1 cannot have to high value or the discharge speed might be to slow)


Lcd display shield, no characters So, I've been trying to make an Lcd display shield I got from ebay to work with arduino. Using this very simple code:

#include <LiquidCrystal.h>

#define RSPin 8
#define EnablePin 9
#define DS4 4
#define DS5 5
#define DS6 6
#define DS7 7

#define LCDColumns 16
#define LCDRows 2

LiquidCrystal lcd(RSPin, EnablePin,DS4,DS5,DS6,DS7);

void setup()
{
  lcd.begin(LCDColumns, LCDRows); //Configure the LCD
  lcd.setCursor(0,0);
  lcd.print("Hello, World!");
}

void loop()
{

}

Actually I've tried several simple examples, checked pins physically to make sure I'm using the right order, But no luck. backlight is on, no characters at all. Am I missing something? Or should just contact the seller to send another shield.

So, after some close inspection I noticed that the blue potentiometer wasnt soldered in correctly. Also, its needs to be turned quiet a lot to have some effect. Might replace it completely. But now it works!


Modbus Protocol Compile Error I have Code for Mod bus Library as below. I have Gone through lots of forum. How to assign device ID, slave address, length using below library function:

#include <SimpleModbusSlave.h>
#define  LED 9
enum
{

  ADC_VAL,
  PWM_VAL,
  HOLDING_REGS_SIZE // leave this one
};

unsigned int holdingRegs[HOLDING_REGS_SIZE];
void setup()
{
  modbus_configure(&Serial, 9600, SERIAL_8N2, 1, 2, HOLDING_REGS_SIZE, holdingRegs);
  pinMode(LED, OUTPUT);
}

void loop()
{
  modbus_update();
  holdingRegs[ADC_VAL] = analogRead(A0); // update data to be read by the master to adjust the PWM
  analogWrite(LED, holdingRegs[PWM_VAL]>>2); // constrain adc value from the arduino master to 255
}

I am getting Error has.

SimpleModbusSlaveArduino.cpp: In function 'void setup()':
SimpleModbusSlaveArduino:79: error: 'SERIAL_8N2' was not declared in this scope

I have  made changes in the lib as in forum. but I found no value read by my software.

Master sending below request on read mode. But not receiving anything.

12:31:02.953: Com8, Baud Rate: 9600, Data Bits: 8 Bits, Parity: None, Stop Bits: 1 Stop Bit
12:31:02.953: Echoback: On, RTS Control: On, Transmit Delay: 5 ms, Response Delay: 1000 ms
12:31:02.953: Read Holding Register(s), Repeat Loop
12:31:02.953: Device Address: 01h, Register: 0000h
12:31:02.953: |-> Read Register: 0000h
12:31:02.968: -> [01h] [0Dh] [00h] [00h] [00h] [01h] [CBh] [EDh]

CHANGES MADE IN AS IN FORUM MENTIONED

Not sure where you got the library from, but if it's from this github repo, you're using it wrong.

The function prototype for modbus_configure is:

void modbus_configure(long baud, byte _slaveID, byte _TxEnablePin, unsigned int _holdingRegsSize, unsigned char _lowLatency);

The example file shows how to use it correctly

modbus_configure(115200, 1, 2, TOTAL_REGS_SIZE);


Can the TimedAction library be used to call functions of an object Currently to use TimedAction for a function a program would look like so:

#include <TimedAction.h>
void functionX();
TimedAction funtionTimed = TimedAction(1000, functionX);

void setup()
{

}

void loop()
{
functionTimed.check();
}

void functionX()
{
 //run function
}

My question is say I have an object class with some functions I would like to use with this TimedAction library. How would this be written?

You can't. The TimedAction class doesn't support the function prototype required for your undefined class (it has to match your class, so can't be written).

You have to call a normal function which then calls the class function, or you have to have your class function as static so it doesn't include the class in the function prototype.

class foo {
    public:
        static void runMe() {
            // blah blah
        }
};

TimedAction funtionTimed = TimedAction(1000, foo::runMe);

However, TimedAction is pretty simplistic and you don't really need it.  You can just write a function to only run every so often:

class foo {
    private:
        uint32_t _runMeTimestamp;
    public:
        void runMe() {
            if (millis() - _runMeTimestamp < 1000) return;
            _runMeTimestamp = millis();
            // blah blah
        }
};

foo myFoo;

void loop() {
    myFoo.runMe();
}

Those two lines of code, plus a variable to store the timestamp in, are all you need to make a function run at periodic intervals.


How can I control neopixels attached to a Digispark? I want to use a string of Neopixels attached to a Digispark hanging off of a RasPi3 as indicators for various situations.  For example: a motor (connected to a driver hat on the I2C bus of the RasPi) turns on or reverses direction.  Can I use Firmata, or is there something like it for the Digispark that I can use with Python?

You need a dedicated microcontroller since you need very precise timing for controlling the neopixels. It works well on an ATTiny85, we are using Adafruit Trinket boards to control Neopixels and work well. So far up to 12 pixels :)

You can download a Trinket Neopixel library, which is modded for an internal osc ATTiny85 from Adafruit.

Then your Raspi can talk to the microcontroller. It is a little problematic, though, since the software serial port handling consumes too much memory on ATTiny, and the ATTiny will ignore all serial input while refreshing the neopixels. Therefore you may get it easier by using an Arduino UNO, or Leonardo or Micro which is powerful enough for many pixels, and have a built-in hardware serial port.

As a matter of fact, you can talk to these Arduino boards as if it would be a serial port, so just plug in a Leonardo over USB and you'll get a new serial port in Rpi to talk to.


A question about the possible limits of an Arduino Uno I've searched the web but could not find a straightforward answer to my query.

I am building a control board for one of my models and this time have decided to also include a computer interface, so I have incorporated an Arduino Uno into my project instead of just analog circuits. I'm not an electronics expert of any sort but I manage by applying basic logic and a lot of trial and error.

Anyway, I have a single Arduino. It is operating the following:

An LCD display,
a 4 button operation panel I made using an LS148 ic,
an L293 operating 2 small motors,
a servo,
a dark sensor,
a temperature sensor,
and it also does serial communication.

Everything is working great, but slow (or so it appears to me).

If i push a button it takes the board about a second to pick up on the signal while an external LED indicator shows the circuit using the LS148 is working as it should. (I basically chained the 1-4 inputs and checking the truth table on the board to determine which button was pressed). Or pick up on a signal sent from the dark sensor for example. It appears as if the whole code in the Arduino runs at a cycle of once per second. Also sending instructions from the computer.

When I disable the LCD code everything works fast(er) and so goes when I remove other parts. So my question is, have I overloaded it?

I am on the verge of ordering another board (which I am going to do anyway), but in this case it is purely due to my belief that if I connect the LCD with the whole display code onto one board and the rest of the sensors and chips to another it will solve my problem.

I haven't figured out yet if it's possible to link the two boards or how to do that, but once I'll get to that bridge I'll cross it as well.

Thanks for your advice.

A lot of Arduino code is written either generally inefficiently, or written in completely the wrong way.

For instance, take the LCD code.  Commands have to be sent at the right speed with the proper delays in there for things to happen.  LCDs are actually quite slow devices to communicate with, and as a result the LCD code has a large number of delays in it.

Nothing else can happen while there's a delay() running.

Many other things will introduce their own delays.  Put them all together and you have a slow system.

No, you're not overloading it, you're slowing it down on purpose, and all those small slow-downs add up to one big grind.

There are other ways of doing these things, of course, which are far more friendly to the chip - things that don't require delays of any form.

For a start there is the millis() function which tells you the time.  Using that to know when to do things, instead of sitting waiting for them to happen, allows you to do so much more at once.

It's like boiling an egg.  Do you put the egg in boiling water and sit there staring at it for 3 minutes (or however long you like your egg cooking), or do you set the timer on your oven to alert you in 3 minutes time so you can go and do the ironing while the egg is boiling?

It's the same with Arduino programming.  Note the time, then check that time against the current time to see if the required time has passed.

Of course, with things like the LCD library, changing it to work that way would be quite a lot of effort.

There are also hardware timers.  These allow you to run small snippets of code at regular periods.  Great for managing things like servos or other motors where you only want to be changing the state or speed of them say 10 times per second. Instead of updating them all the time, just set a desired speed / position variable and let the timer interrupt update the actual motor at a lower rate.

There are two key phrases to take away here:

Non-blocking.  That is basically writing routines that never wait for something to complete, but can check to see if it's time for something to happen.
Asynchronous programming.  This is using things like timers to make things happen "outside" your main loop.


What is the best way to measure PWM signals ( pulseIn ) with the Arduino via a Raspberry Pi? I connected my Arduino Uno to my raspberry via USB serial. I'm able to read out both digital and analog pins of my Arduino using the Python nanpy library (v.0.8).
However, I can't find support for the pulseIn() function. It seems nanpy doesn't support pulseIn() at all.

What is the best way to measure PWM signals with the Arduino and forward the results to the Raspberry Pi?

I am able to measure PWM using the Arduino GUI, however I would to take PWM samples at fixed time intervals over a long period of time and combine this data with other measurements that my Raspberry is making.I also tried pyFirmata, but it doesn't support pulseIn() measurements either.

Nanpy seems to have a CounterClass that does frequency measurements.

Or do you want to measure the PWM duty-cycle?


Can I turn off a device using the 5V and analog pins? Could I connect a device that requires minimum 5V 1A from the 5V Pin to the Ground and somehow turn it off inside  a sketch?

edit: I'm using a Due based boad, the digix http://digistump.com/wiki/digix/tutorials/basics

You would use a transistor. Something like this would work.

In this case the Arduino controls a transistor to drive a brushless motor.

Source: Arduino Cookbook: (https://www.inkling.com/read/arduino-cookbook-michael-margolis-2nd/chapter-8/figure-8-9)

Update:
For the sake of clarity I should point out that the TIP102 is the device to use for the 1A required (not the 2N2222). And as pointed out by others the 5V supply of most Arduino boards would not be sufficient to supply 1A, so an external supply would be advised.


Is there a way to make the RESET pin work in the inverse? Is there a way for me to have this work the opposite way?
I have one cable with an alligator clip hooked up to the reset pin and another hooked up to ground.
When I clip them both together, the board resets.
However, I would like for this to work in the opposite way such that they’re already clipped together and when you detach the cables, the board resets.

My personal preference would be to attach a NOT gate to the RESET pin.  This can be constructed very simply from a single NPN transistor (or N-channel MOSFET) and a resistor.

simulate this circuit – Schematic created using CircuitLab
With the wire disconnected R1 turns on Q1 which pulls the RESET pin LOW.  With the wire connected Q1 is turned off, allowing RESET to be pulled back up by the pullup resistor that's built into the Arduino.
This method also won't interfere with the programming reset action of the Arduino.


Use AS3935 with I2C? Has someone experience with interfacing the AS3935 lightning sensor using I2C? I found a library but it only works with SPI as far as I can tell. I really don't want to give up 4 pins for SPI as I need those for other things. I2C would be great as I use a couple more sensors with I2C so no extra pins only for AS3935.

Just use these functions to read/write AS3935 registers, replacing the SPI ones (_devAddr is the device address, usually 0x03) :

// read/write functions for I2C mode
uint8_t AS3935::_i2cRead(uint8_t addr)
{
    // send register number
    Wire.beginTransmission(_devAddr);
    Wire.write(addr);
    Wire.endTransmission(false); // <<<--- THE 'false' here is mandatory!

    // request register data
    Wire.requestFrom(_devAddr, (uint8_t)1);

    // read data
    return Wire.read();
}

void AS3935::_i2cWrite(uint8_t addr, uint8_t data)
{
    Wire.beginTransmission(_devAddr);
    Wire.write(addr);
    Wire.write(data);
    Wire.endTransmission();
}

The "trick" is to use Wire.endTransmission(false) inside the read routine; this avoid to send the stop bit, which is mandatory for AS3935 read operation.


Substitute for FTDI board? I am thinking forward to buy a set of Arduino pro mini. I have a very low budget and I can't think of buying a FTDI board. Is there any substitute for the FTDI board that is compatible with these arduino pro mini.

All prices in USD w/ free shipping.

FT232RL breakout board:

Aliexpress: $1.55
eBay: $1.81

They are probably counterfeit. A Windows driver update (AKA "FTDIgate") at one point "bricked" them but I'm not sure that's an issue anymore. Even if it is it's Windows only and easy enough to work around. I've used these for years on Windows and they work fine for me.

If that's still beyond your budget there are a few other common options. I haven't used these breakout boards but I do have quite a few boards that use the CH340G and they work perfectly once you install the driver. There's a decent chance some of these will also be counterfeit. Some didn't break out the DTR/CTS pin for auto reset but if you're on such a low budget maybe it's worth it to you to press the reset button on every upload to save a few cents. They may not have the standard FTDI header pinout and if so would require you to use jumpers to connect them to the Pro Mini rather than plugging directly into the header.

PL2303 breakout board:

Aliexpress: $0.50
eBay: $0.74

These don't appear to break out the DTR or CTS pins so they won't do auto-reset.

CH340G breakout board:

Aliexpress: $0.72
eBay: $0.93

These don't appear to break out the DTR or CTS pins so they won't do auto-reset.

CP2102 breakout board:

Aliexpress $1.00
eBay: $1.31


How to get the MAC address of an Ethernet shield, if it is not printed on it? Help me to find out how to connect an Ethernet shield over the internet using a LAN cable. I have tried many times but I'm not getting a MAC and IP address.

If you do not have a MAC address then you have to make one up.  There are a couple of rules and regulations about what a MAC address can be, but most of the time you can just make one up:

It must be unique on your network
There are a set of prefixes that are reserved for special purposes:

The lowest bit of the first byte must be 0
The second bit of the first byte must be 1

You can read more about it here: https://en.wikipedia.org/wiki/MAC_address

Once you have provided a MAC address and physically connected it to the network then you need an IP address and netmask.  There are two ways you can get the IP address and netmask:

Through DHCP - For example your home internet router would provide the IP address for you.
By allocating your own. This must be within the range of your network's IP addresses, typically something like 192.168.0.x where x is between 1 and 255.  The IP address must be unique on your network.

The netmask, again, can be given by DHCP, otherwise you will have to enter the netmask of your network, typically 255.255.255.0

Then to access the internet itself you need to provide (or be provided with through DHCP) the address of the internet gateway and possibly a DNS server address. On a home network they are typically the address of the router, which may well be 192.168.0.1 or something similar.


ATMega328P U Query - does it work straight away on Uno R3 Quick query (I hope).
I have an Arduio R3 board with ATMega328P U on board. It works fine. I bought some new MCUs, ordered with bootloader. Same IC designation. Before I dive into my new project I want to confirm they are okay.
So ...............I take the original MCU out of the Arduino R3 and replace it with a new ATMega328P U. Should it work fine straight away? i.e. can I upload simple sketches like Blink?
My problem is that I've done this and none of them work. I get two flashes on the Rx LED on the board, then ArvDude gives me a string of "not in sync" error messages. If I put the original MCU back in then everything works okay again. I don't want to go through the hassle of burning bootloader on chips that supposedly have it, I'd rather send them back.
Are my new MCUs duff? Or is there any other easy way to check them?
Many thanks

The MCU on the Uno R3 comes with a specific bootloader (Optiboot) and
fuse configuration (external clock, clock prescaler disabled, bootloader
enabled...). You may find some ATmega328Ps on the market that have been
specifically configured as drop-in replacements for the one on an Uno.
Those should “just work”. If the ones you bought come with a different
bootloader or fuse configuration, you may have to re-flash or
reconfigure them.


How come my switch is triggering with out pushing the button? New here, sorry If my formatting is bad.

int button = 2;
int relay = 3;
int speaker = 4;

void setup()
{

  pinMode(button, INPUT_PULLUP);
  pinMode(relay, OUTPUT);
  pinMode(speaker, OUTPUT);

}

void loop()
{
  if(digitalRead(button) == 0)
  {
    digitalWrite(relay, HIGH);
    tone (speaker, 100, 300);
    delay (3000);
  }
  else
  {
    digitalWrite(relay, LOW);
  }
}

I want the relay to trigger and stay open only while the button is pressed.   However for some reason touching pin 2 triggers the relay and sound, even if I'm not connecting it to the ground.

If i remove the tone (speaker, 100, 300); it only triggers when the button connecting pin 2 to ground is pressed, but obviously doesn't play the tone.

I want the relay to trigger and stay open only while the button is
  pressed. However for some reason touching pin 2 triggers the relay and
  sound, even if I'm not connecting it to the ground.

Touching a pin is like connecting it to ground with a resistor (human body is conductive). It may or may not be stronger then the pull-up resistor.

  If i remove the tone (speaker, 100, 300); it only triggers when the
  button connecting pin 2 to ground is pressed, but obviously doesn't
  play the tone.

Activation of the neighbor pin influences the pull-up on pin 2. Try external pull-up on pin 2.


Operating two functions simultaneously I have connected a bluetooth module(HC-06) and a voice recognition shield(EasyVR) on an arduino UNO.
By using an another HC-06 on the another arduino(so, 2 arduinos and 2 HC-06 totally), I am going to let two arduionos communicate with each other.
Also, simultaneously, one arduino with HC-06 will recogize the voice by using the voice recognition module.
I have successed each operations, but after combining two codes the bluetooth doesn't work...
(Voice recognition have successed.)

Is it unable to operate two operations simultaneously?

Can we use these two sentences in one code?
SoftwareSerial BT(2,3);     --> for bluetooth module
SoftwareSerial Port(12,13);   --> for voice recognition module

Is it unable to operate two operations simultaneously?

The only way you can do two operations simultaneously is to have two Arduinos. An Arduino can only do one thing at a time. In order to make it seem like it's doing things at once you have to create your sketch accordingly. The use of delay() is right out. As are long loops using things like while(). In short: anything that blocks is bad.

  Can we use these two sentences in one code?

Not reliably, no.  They are both resource hungry and, to a large extent, blocking. A general rule is, if you need at least two more UARTs than the board provides then you need a different board. You can only reliably work with one software UART at a time.

I would suggest upgrading to a more capable board with more hardware UARTs. Either that or use a bluetooth system that doesn't use UART, such as an SPI based BLE module.


When and where do I have to worry about accounting for sensor "noise"? I just watched this excellent video tutorial that shows a simple Arduino program that toggles an LED via a pushbutton. Very cool!

Being brand new to electronics/robotics, I was shocked that something as simple as a pushbutton required his debounce behavior. That's something I would have never thought about in a million years. What is the 'rule of thumb' for when this type of debounce behavior (regardless of what sensor we're talking about, pushbutton or otherwise) must be accounted for? Is it simply that any type of analog sensor can generate this kind of unexpected 'noise'?

Can someone provide other examples for when special code must be put in place to accommodate unexpected sensor noise?

Switch bounce is a physical issue that can be cleaned up with filtering. Since the sense states are very simple, only very crude (time-based) filtering is required to clean up its signal.

Other mechanical sensors that can exhibit similar characteristics are bump sensors, tilt sensors, and accelerometers. Bump and tilt sensors are also very simple, and similar filtering will clean up their signals.

Accelerometers on the other hand react to very minute perturbations, so they may require more advanced filtering based on the application they will be used in; orientation sensing can use time-based filtering, whereas things such as motion tracking including dead reckoning will require one or more layers of calculus in order to clean up the signal.


Arduino loses its program under unusual conditions I have a pretty complicated setup: an ATMEGA328p chip (found in the Uno, Duemilanove, etc.) on a Diavolino board (from EvilMadScientist) running at 8 MHz (instead of the normal 16 MHz).  This should be basically the same thing as the 3.3V arduino pro from the code's point of view.  On top of this is a custom shield including a bunch of digital and analog devices with SPI, I2C, and serial interfaces.

This is supposed to run for days or weeks at a time.  In normal conditions--on the ground outside--it does fine.  However, in two recent tests, it lost its program and stopped working.  One of these was in a cold low-pressure chamber (-40 C/F).  The other was outside mounted on a flying quadcopter.  Reprogramming it fixed the problem; before reprogramming, neither a reset nor power-cycling would get any response from it.

Has anyone ever heard of an arduino bricking itself like that?  My best idea for how this could happen is that somehow the chip was put into a state where it treated incoming serial data as a new program to run.  Also, I'm speculating that connections between the two boards could have been disrupted by thermal contraction or vibration in those tests.

Thanks for any help!

I would suggest that you reproduce the issue and then use a device capable of reading the flash, to confirm that it's still identical to the .hex file that was used to program the board.

I know that the AVRDragon can do it and maybe also cheaper USB ISP programmers can do it too.

But it seems that you are not alone.

Flash memories like those used in uC work by trapping electrons in wells of charge, so that they pseudo-permanently affect the silicon.

Very low temperatures can change the properties of the insulation, letting many more electrons than usual to escape.

Try to wrap the board in a thermal airtight insulator, possibly providing local heating. That should solve your problems.


A class within a class - via an Initialiser Lists: NOT able to update a variable My test are based on the blog of http://arduinoetcetera.blogspot.be/2011/01/classes-within-classes-initialiser.html.

Because I would like to use this idea, I tried with a simple idea, after the instance is created just update a value.

But for some reason, the code compiles perfectly and there seems to be no error with the update method, but it DOES NOT UPDATE the variable.

But my output on the serial monitor show that the number (volatile int) doesn't update.

Object of class First has value - Number: 6
Object of class Second has value - Number: 13
Object of class Second has value - Double: 26
Object of class Second has value - Update: [0] - 20  // <--
- -
Object of class First has value - Number: 6
Object of class Second has value - Number: 13        // <--
Object of class Second has value - Double: 26
Object of class Second has value - Update: [1] - 70
- -
Object of class First has value - Number: 6
Object of class Second has value - Number: 13

code - MAIN :  First thing(6, 13);
[edited on request of @Mark Smith]

#include "First.h"
First thing(6, 13);
...
int newValue;
...
int ledPins[] = {
  20, 70, 45, 68, 543, 321
}; // an array of pin numbers to which LEDs are attached
int pinCount = 6; // the number of pins (i.e. the length of the array)
bool plus=true;
int index=-1;
void loop() {
  Serial.print("Object of class First has value - Number: ");
  Serial.println(thing.Number());
  Serial.println();
  Serial.print("Object of class Second has value - Number: ");
  Serial.println(thing.getSecond().Number());
  Serial.print("Object of class Second has value - Double: ");
  Serial.println(thing.getSecond().Double());
  ...
  Serial.print("Object of class Second has value - Update: [");
  if ( plus && index == (pinCount-1) ) {
    plus=!plus;
  }
  if ( !plus && index == 0 ) {
    plus=!plus;
  }
  // change + <--> -
  (plus) ? index++ : index--;
  newValue=ledPins[index];
  Serial.print(index,DEC);
  Serial.print("] - ");
  Serial.println(newValue, DEC);
  thing.getSecond().Update(newValue);
  Serial.println("- - ");

code - FIRST

#include "First.h"
...
First::First(int firstNumber, int secondNumber) : widget(secondNumber) {
  itsNumber = firstNumber;
}
int First::Number() {
  return itsNumber;
}
Second First::getSecond() {
  return widget;
}

code - SECOND : void Second::Update(int newNumber)

#include "Second.h"
...
volatile int itsNumber;
Second::Second(int newNumber) {
  itsNumber = newNumber;
}
void Second::Update(int newNumber) {
  itsNumber = newNumber;
}
int Second::Number() {
  return itsNumber;
}
int Second::Double() {
  return itsNumber*2;
}

For the complete code
https://github.com/droopy4u/ARDUINO
 - https://github.com/droopy4u/ARDUINO/tree/master/ClassWithClasses -

Even without the real code, I think the problem is with the function First::Second().

You need to understand what happens in C++ when values are passed as parameters.  The are passed by value by default, this means a COPY of the value is passed into the function, you can modify the parameter all you like but when you return those changes are lost.

There are two exceptions to this, the first is pointers.  When you pass in a pointer you can modify what is pointed to but you still can't modify the pointer, because that is a copy.  If you want to modify the pointer then you need a pointer to a pointer int** ptr_to_ptr.

The other exception is a reference.  In this case the function can modify the parent function's variable.  This is more efficient in terms of memory.

So you have:

int AddOne(int value) {++value; return value};   // 5 == AddOne(5);
int AddOne (int value) {return value+1};         // 6 == AddOne(5); - doesn't modify the parameter.
int AddOne(int* pValue) {(*value)+1; return *value;}//6 == AddOne(5); - Pointer
int AddOne(int& value){++value; return value;}   // 6 == AddOne(5); - Referance
int AddOne(const int& value){++value; return value;} // Compiler error, modifying const value.

So why it is First::Second() causing the problem?  Well the same rules apply to return values as to parameters and you are returning a copy of the value widget so you then modify that copy and then dispose of it.  So this is what you need to fix the problem.

Second& First::getSecond()
{
    return widget;
}

EDIT : Its not clear in the preceding text but you don't need getSecond() to return a reference if you are not altering the value of widget so getDouble() will return the expected value because it is working form a copy of the original and not storing any changes.  However update() will not work as expected because the result of getSecond() goes out of scope (gets disposed of) once the call is complete.  The changes its made are not save to the original because it is working on a copy.


Which type of sensor should i use to get RPM of an engine? Using Arduino (i got leonardo and uno),
I'm looking for a way to get the RPM of my car's engine.
I know this can be done using an OBD2 connection however i'm looking for a different way.
Sensing?
I need a reference for a sensor / a creative way to get this data.
Having said that, these approaches came up:

guessing the RPM by reading the amps in the car's 12V connection
recording the sound of the engine using a microphone and setting thresholds for certain RPM values

I would think something like this would benefit you greatly. If your vehicle was produced after 1996 it will have an OBD port near the steering wheel that allows you to read diagnostic information from the car. This diagnostic information always includes error codes (think: Check engine light), and often includes operating information like speed and engine rpm.


Adafruit esp32 Feather Failing to compile So yesterday, I was able to upload/compile given example code to the Esp32 Huzzah board. Today I couldn't even compile. Even carefully using the tutorial adafruit provides.

I was getting errors as given below. How do I fix this?

C:\Users\YbSeconds\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1/tools/sdk/lib\libesp32.a(cpu_start.o):(.literal.main_task+0x14): undefined reference to `app_main'

C:\Users\YbSeconds\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1/tools/sdk/lib\libesp32.a(cpu_start.o): In function `main_task':

/Users/ficeto/Desktop/ESP32/ESP32/esp-idf-public/components/esp32/cpu_start.c:503: undefined reference to `app_main'

C:\Users\YBSECO~1\AppData\Local\Temp\arduino_cache_436740\core\core_b15e1ec95534e29a355269b84b798354.a(HardwareSerial.cpp.o):(.literal._ZN14HardwareSerial9availableEv+0x0): undefined reference to `uartAvailable'

C:\Users\YBSECO~1\AppData\Local\Temp\arduino_cache_436740\core\core_b15e1ec95534e29a355269b84b798354.a(HardwareSerial.cpp.o):(.literal._ZN14HardwareSerial4peekEv+0x0): undefined reference to `uartPeek'

C:\Users\YBSECO~1\AppData\Local\Temp\arduino_cache_436740\core\core_b15e1ec95534e29a355269b84b798354.a(HardwareSerial.cpp.o):(.literal._ZN14HardwareSerial4readEv+0x0): undefined reference to `uartRead'

C:\Users\YBSECO~1\AppData\Local\Temp\arduino_cache_436740\core\core_b15e1ec95534e29a355269b84b798354.a(HardwareSerial.cpp.o):(.literal._ZN14HardwareSerial5flushEv+0x0): undefined reference to `uartFlush'

C:\Users\YBSECO~1\AppData\Local\Temp\arduino_cache_436740\core\core_b15e1ec95534e29a355269b84b798354.a(HardwareSerial.cpp.o):(.literal._ZN14HardwareSerial5writeEh+0x0): undefined reference to `uartWrite'

C:\Users\YBSECO~1\AppData\Local\Temp\arduino_cache_436740\core\core_b15e1ec95534e29a355269b84b798354.a(HardwareSerial.cpp.o):(.literal._ZN14HardwareSerial5writeEPKhj+0x0): undefined reference to `uartWriteBuf'

C:\Users\YBSECO~1\AppData\Local\Temp\arduino_cache_436740\core\core_b15e1ec95534e29a355269b84b798354.a(HardwareSerial.cpp.o): In function `HardwareSerial::available()':

C:\Users\YbSeconds\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1\cores\esp32/HardwareSerial.cpp:157: undefined reference to `uartAvailable'

C:\Users\YBSECO~1\AppData\Local\Temp\arduino_cache_436740\core\core_b15e1ec95534e29a355269b84b798354.a(HardwareSerial.cpp.o): In function `HardwareSerial::peek()':

C:\Users\YbSeconds\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1\cores\esp32/HardwareSerial.cpp:157: undefined reference to `uartPeek'

C:\Users\YBSECO~1\AppData\Local\Temp\arduino_cache_436740\core\core_b15e1ec95534e29a355269b84b798354.a(HardwareSerial.cpp.o): In function `HardwareSerial::read()':

C:\Users\YbSeconds\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1\cores\esp32/HardwareSerial.cpp:157: undefined reference to `uartRead'

C:\Users\YBSECO~1\AppData\Local\Temp\arduino_cache_436740\core\core_b15e1ec95534e29a355269b84b798354.a(HardwareSerial.cpp.o): In function `HardwareSerial::flush()':

C:\Users\YbSeconds\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1\cores\esp32/HardwareSerial.cpp:157: undefined reference to `uartFlush'

C:\Users\YBSECO~1\AppData\Local\Temp\arduino_cache_436740\core\core_b15e1ec95534e29a355269b84b798354.a(HardwareSerial.cpp.o): In function `HardwareSerial::write(unsigned char)':

C:\Users\YbSeconds\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1\cores\esp32/HardwareSerial.cpp:157: undefined reference to `uartWrite'

C:\Users\YBSECO~1\AppData\Local\Temp\arduino_cache_436740\core\core_b15e1ec95534e29a355269b84b798354.a(HardwareSerial.cpp.o): In function `HardwareSerial::write(unsigned char const*, unsigned int)':

C:\Users\YbSeconds\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1\cores\esp32/HardwareSerial.cpp:157: undefined reference to `uartWriteBuf'

collect2.exe: error: ld returned 1 exit status

exit status 1
Error compiling for board Adafruit ESP32 Feather.

So it turns out the problem is that you're using the esp32 1.0.1 library provided by espressif. I'm assuming you're using the Arduino IDE board manager URL: https://dl.espressif.com/dl/package_esp32_index.json

To fix this, don't use 1.0.1. Use 1.0.0! Remove 1.0.1 and install 1.0.0. That should get it to compile properly without the uart, app_main errors.


Which Barcode Scanner to be used with arduino in India I know this question is not so releavant as it does not include any research, but I am in search of a barcode scanner that i can easily interface with arduino and get output from it but unfortunately the Scanner models which are listed from the people doing the same stuff are not easily available in India. So if anyone knows which barcode scanner would best suit the requirement please suggest.
Availabilty in Indian market would be much appreciated :)

Most barcode scanners behave just like a regular keyboard.

Try getting one with a PS2 port. You can pretty easily interface a PS2 keyboard to an Arduino. There are already libraries for it.


Deriving the exact relationship between PWM and steering I am using a L298n driver to make a basic RC car. I realise that PWM is used to control the speed of the motors and that the car would turn when the wheels on one side of the car have a rpm different from the other side. I am taking user input from the x-axis of a joystick.
However, I am not sure how to arrive at an exact relationship between rpm and the angle by which the car turns.
My approach so far :

If the car is turning left, the wheels on the left side are turning in a smaller arc and hence the inner wheels have a lower rpm. The sharper the turn the slower the inner wheels turn.

PWM is used to control the speed of the motors.

Each angle of turning corresponds to circles of different radii. Hence a sharper turn would correspond to a circle with a very small radius.

So I need to map the x-axis values of the analog stick to angles by which I want the car to turn. Once I know the relation between rpm and the angle by which the car turns, I can map the joystick values to PWM values.

This question has already been asked here and the consensus seems to be that some sort of feedback mechanism is required for an exact calibration.
I have two questions :

Where do I learn more about this feedback mechanism?
Purely from a physics perspective, considering an ideal environment, how do I derive a relation between rpm and the steering angle?

Where do I learn more about this feedback mechanism?

It depends on the kind of feedback. You can have absolute or relative feedback. Relative would be, for example, to use an encoder on each wheel to find out how much it has turned. Absolute would be using a compass to know exactly what direction the vehicle is facing at any time.

Purely from a physics perspective, considering an ideal environment, how do I derive a relation between rpm and the steering angle?

If you know how much each wheel has turned then it is really just simple trigonometry. You have two arcs that are the same proportion around the circumference of two circles. The circles must have the same centre point. Well, I say "simple" - that's a relative term. And of course it depends if you are moving like a car (i.e., turning while moving forwards) or like a tank (turning on the spot) as to whether such calculations are particularly meaningful.
But then of course that's only if you actually know the RPM. Which requires feedback.
There is no easy relationship between PWM and the angle turned. This is because PWM does not define the RPM:

PWM defines the current
The current defines the torque
The torque defines the acceleration (and ultimately maximum speed) under different loads and conditions.

Those loads and conditions change depending on lots of factors. With no way to change the angles of the wheels they will need to slip on the surface as you turn. That adds friction and varies depending on both the speed at which you turn, the angle you turn through, and the surface you are driving on at the time. A high friction surface will both increase the power transfer and at the same time require more power to turn. A sharper turn angle will slip more and require more power to overcome the friction.
It's a very complex relationship with far too many variables. Which is why cars have steering mechanism to change the angle of the wheels, and some vehicles have rear-wheel steering as well to change the angle of the rear wheels to reduce slip and friction (such as the Porsche 911 and many large heavy vehicles), and why London cabs use "Ackermann" steering which gives each wheel a different angle while turning to increase the angle the vehicle can turn through so it can turn in the road easier.
So all in all if you want to know what direction you are pointing at any time, although it's harder to interface with and use, and may be a little more expensive, a compass or other absolute rotation sensor is the way to go.
If you want to turn to a specific angle, (or turn through a specific angle, which is just a relative change between two specific angles) then it's a case of "move a bit" then "see what angle I'm at" then "move a bit more" and "see what angle I'm at".
You could either use a simplistic approach where you always move in discrete steps, or use a PID to calculate what would be a good amount to turn to get you closer and closer to the desired angle depending on how far you turned last time.


What is the best way to connect multiple Arduinos? In my situation, I have a map divided into multiple parts, each part could have about 20 to 100 Arduinos that they should send information from time to time to the master. How could I do this?

Second problem. How could I use the other Arduinos to send the info from Arduino that are so far from the Master?

Example in part 1: Arduino X is 500 meters far away from the master. How could use the other to send the information?

Can I do this with NodeMcu or such equipment with built-in WiFi?

I think you should start with using Wifi modules and you use an esp-01 too instead of NodeMCU. Once you are familiar with esp-01's, you will find them as good as NodeMCU. Esp-01's only lack multiple pins when compared to NodeMCU.

And for communication between arduino and esp-01, use serial ports- 0 and 1.

Here is example code-
For Master Arduino

int temp;
int hum;

void setup(){
 Serial.begin(115200);
 delay(2000);
}
void loop() {

 temp = random(0,100);
 hum = random(100,200);
 Serial.print(temp);
 Serial.println('t');
 delay(2000);
 Serial.print(hum);
 Serial.println('h');
 delay(2000);
 Serial.flush();
}

For Slave Esp or any other slave arduino -

String inString = "";    // string to hold input

float temp = 0,hum = 0;

boolean newtemp=false, newhum=false;

void setup() {
  Serial.begin(115200);
  Serial.println("ESP 8266 - 01 Module is ready to receive codes from Master Arduino");
 }

void loop() {
  // Read serial input:
  while (Serial.available() > 0) {
    int inChar = Serial.read();

    if (inChar != '\n') {

      if (inChar == 't')
      newtemp = true;

      if (inChar == 'h')
      newhum = true;

      inString += (char)inChar;
    }
    else {
      Serial.print("Input string: ");
      Serial.println(inString);
      if ( newtemp == true ) {
      temp = inString.toFloat();
      Serial.print("Received Temperature:");
      Serial.println(temp);
      newtemp = false;
      }
      if ( newhum == true ) {
      hum = inString.toFloat();
      Serial.print("Received Humidity:");
      Serial.println(hum);
      newhum = false;
      }
      inString = "";
    }
  }
}

Pin connections -

Master Arduino TX -- Slave board RX


Sensing horizontal tilt I'm building a digital gear shift knob, which would display current gear (1-5, R) and based on readings from OBD-II change color when gear shifting is required, to save on fuel consumption.

I need a way to detect the current gear - PID 0D (current gear) is not availiable in this car. I was thinking about doing it based on the horizontal tilt of the gear stick, since there are 6 positions plus a neutral gear:

    1   3   5
     \  |  /
      --0--
    /   |  \
   2    4   R

Is there a sensor I could use? Or perhaps it'd be possible to build one, e.g. using 6 of these ball switches: https://www.adafruit.com/products/173
There is however a space constraint since everything needs to fit inside a gear knob, therefore I'd prefer a nice single package.

You could also sense the position of the stick where it enters the floor with hall sensors... 1-5 and reverse would have sensors, neutral would be when none of the other gears are detected.


Digital Band pass filter on Arduino I am working with sensors on Arduino and would like to filter the sensor's output to a certain band of frequencies.

I found many examples online on how to implement simple digital low-pass filters in Arduino code, but not for band pass filters.

Is it even possible to achieve this in the scope of an Arduino program?
If anyone can share some tutorial for this, that would be much appreciated.

A band pass filter simply means that it a filter between a certain interval of frequencies thus it can be made from a high pass filter and a low pass filter

e.g. this fact is mentioned here http://www.electronics-tutorials.ws/filter/filter_4.html

as well as lots of other web pages which a search by you can find.
So yes a band pass filter can be implemented on arduino if you can implement the corresponding high pass and low pass filter too.


Thermometer project shows fluctuation due to varying sensor value and voltage I built this thermometer that reads the sensor value from the temperature sensor and displays it on the LCD display. It basically works fine, but the displayed temperature shows a fluctuation between +/-2 degrees due to varying sensor value and voltage every second.
(This is my very first Arduino project and I am pretty new to electronics.)
The Arduino gets the power via my Mac through USB.

When I check the sensor value and voltage, it slightly differs each second (or whatever delay interval I use in my code). Sensor value is between 123-125 and voltage usually 0.7, but also changes slightly, which causes the temperature calculation to vary around 2 degrees, which for a "thermometer" is quite a lot.

Is there any way to stabilize it? Should I use a capacitor or another resistor?

Code:

#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

const float powerSupply = 5.0;
const int sensorPin = A0;
const float baselineTemp = 23;

void setup() {
  Serial.begin(9600);
  lcd.begin(16, 2);
  lcd.print("Temperature:");
}

void loop() {
  int sensorVal = analogRead(sensorPin);
  Serial.print("Sensor Value: ");
  Serial.print(sensorVal);

  float voltage = (sensorVal/1024.0)*powerSupply;
  Serial.print(", Volts: ");
  Serial.print(voltage);

  Serial.print(", degrees C: ");
  float temperature = (voltage - .5)*100;
  Serial.println(temperature);

  // set the cursor to column 0, line 1
  // (note: line 1 is the second row, since counting begins with 0):
  lcd.setCursor(0, 1);
  // print the number of seconds since reset:
  lcd.print(temperature);
  // lcd.print(String(sensorVal) + ", " + String(voltage) + ", " + String(temperature));
  delay(1000);
}

What you need to do is take an averaged reading, this is because the sensor is always fluctuating, noise on the 5V line or the signal line. There are possible hardware solutions.

Adding a capacitor between Vcc and Gnd near the sensor, 0.1µf
Adding a low-pass filter on the signal line of the LM35 to Arduino
heatsink on the LM35(they are very sensitive to movement, giving odd readings)

The capacitor on the Vcc and Gnd will lessen the effects of voltage spikes from the rest of the Arduino's circuitry.

The low-pass filter will help give a more filtered output from the sensor with a better response over time.

                2.2k
LM35>---------/\/\/\-0------<Arduino
                     |
                     |
                     |
                    === 1µF
                     |
                     |
                    GND

The heatsink will allow the LM35 to get a better reading of the general temperature and not the temperature of the breeze from a window.

All three of the above solutions will probably give the best results.

What you could do in software too is to have an averaging algorithm/function in your code and actually take the averaged reading across the whole second that you delay the MCU.

An example of this would be:

#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

const float powerSupply = 5.0;
const int sensorPin = A0;
const float baselineTemp = 23;
int sensorVal = 0;

//these are NEW
unsigned long lastTime = 0;     // last time reading taken
unsigned long currTime = 0;     //current time variable intialised
float AverageReading = 0;

float _readingAv = 0;   // static variable for keeping the averaged reading
int _readingsCount = 0;
int _readings = 100;     //the number of readings to take

void setup() {
  Serial.begin(9600);
  //  lcd.begin(16, 2);
  //  lcd.print("Temperature:");
}

void loop() {
  currTime = millis();

  if ((currTime - lastTime) < 1000) {  //checks to see if a second has passed
    sensorVal = analogRead(sensorPin);

    if (_readingsCount < _readings) {
      _readingAv += sensorVal; //add the current value to the last
      _readingsCount++;
    }
    else {
      AverageReading = _readingAv / _readings; //get the average
    }
  }
  else {
    Serial.print("Sensor Value: ");
    Serial.print(sensorVal);

    float voltage = (AverageReading / 1024.0) * powerSupply;
    Serial.print(", Volts: ");
    Serial.print(voltage);

    Serial.print(", degrees C: ");
    float temperature = (voltage - .5) * 100;
    Serial.println(temperature);

    //~ reset the values used by the previous function
    _readingsCount = 0;
    lastTime = currTime;
    _readingAv = 0; //Important to set this back to 0 so not to get odd values

    // set the cursor to column 0, line 1
    // (note: line 1 is the second row, since counting begins with 0):
    lcd.setCursor(0, 1);
   // print the number of seconds since reset:
    lcd.print(temperature);
    // lcd.print(String(sensorVal) + ", " + String(voltage) + ", " + String(temperature));
  }

}

Probably a better version of making filtering code of the LM35.


Readings changing in hall effect sensor I am using a A1324 hall effect sensor for a distance measuring.

The voltage output keeps changing even if the distance between the magnet and sensor does not change. The output changes +-0.200V and I am trying to measure the distances at steps of 0.01V.

From https://www.arduino.cc/reference/en/language/functions/analog-io/analogread/

  analogRead()

  Reads the value from the specified analog pin. The Arduino board
  contains a 6 channel (8 channels on the Mini and Nano, 16 on the
  Mega), 10-bit analog to digital converter. This means that it will map
  input voltages between 0 and 5 volts into integer values between 0 and
  1023. This yields a resolution between readings of: 5 volts / 1024 units or, .0049 volts (4.9 mV) per unit.

It is likely what you are seeing is noise and is to be expected. The source of the noise is likely multiple and could be environmental physical metallic or magnetic objects some distance away that are moving, electrical wiring (mains) nearby, and noise introduced by the power supply to the Arduino.

If you want to get a stable precise reading that close to the minimum step size, you will want to take several readings and average them. The more you read and average, the more you can eliminate the random effect of the noise, but the tradeoff is that it is slower because you are taking tens or hundreds of readings just for one result.


How to change Void with button press I have 2 buttons and 2 voids (blink_slow) (blink_fast).
i need to be able to press button 1 and blink-slow void will run, then press button 2  and blink fast will run. none of my code works, any idea how i can do this?

const int btn1 1;
const int btn2 2;
const int led  13;

void setup(){
pinMode(btn1,INPUT_PULLUP);
pinMode(btn2,INPUT_PULLUP);
pinMode(led,OUTPUT);
digitalWrite(led,HIGH);
}
void loop(){
if(digitalRead(btn2 =LOW)){
blink_slow();
}
if(digitalRead(btn3 =LOW)){
blink_fast();
}

void blink_slow(){
digitalWrite(led,LOW);
delay(1000)
digitalWrite(led,HIGH);
delay(1000)
}

void blink_fast(){
digitalWrite(led,LOW);
delay(500)
digitalWrite(led,HIGH);
delay(500)
}

Start by correcting the obvious:

const int btn1 = 2;
const int btn2 = 3;
const int led = 13;

void setup()
{
  pinMode(btn1, INPUT_PULLUP);
  pinMode(btn2, INPUT_PULLUP);
  pinMode(led, OUTPUT);
  digitalWrite(led, HIGH);
}

void loop()
{
  if (digitalRead(btn2) == LOW) {
    blink_slow();
  }
  else if (digitalRead(btn3) == LOW) {
    blink_fast();
  }

void blink_slow()
{
  digitalWrite(led, LOW);
  delay(1000)
  digitalWrite(led, HIGH);
  delay(1000)
}

void blink_fast()
{
  digitalWrite(led, LOW);
  delay(500)
  digitalWrite(led, HIGH);
  delay(500)
}

The mistakes where 1) const variable assignment, 2) using pin 1 (TX) is a potential risk if you later what to use Serial for debugging, etc, 3) condition expression, and a lot of formatting. Open your C/C++ book and check the syntax.

Now your turn to improve this!


What should be the delay to be given for reading accelerometer I have five accelrometer sensors (MMA 7361) connected to the analog channels of Arduino Duemilanove. I am using the following code to read the data. (I am reading from only one axis from each sensor.)

#include <avr/io.h>
#include <avr/wdt.h>

int sensorValue = 0; // value read from the pot

void setup()
{
    Serial.begin(9600); // initialize serial communications at 9600 bps:
}

void loop()
{
    // read the analog values:

    int i=1;

    Serial.print("ACS#");

    for(i=0;i<5;i++)
    {

        sensorValue = analogRead(i);
        Serial.print(sensorValue);
        Serial.print("#");

        delay(10);
    }

    Serial.println("");

}

I am using a delay of 10 after reading each sensor. What should the value of the delay I should be using after reading one sensor to get the correct values from the sensors?

A delay is not needed.

What can be more beneficial, though, is making a dummy reading between each real reading.  This gives the ADC more of a chance to settle on the right reading without the Sample and Hold capacitor being influenced by the previous reading.

The simplest way is just to duplicate your analogRead line so it's done twice.


ATtiny44 millis() not working with 16 MHz external clock I'm using ATtiny44 with Arduino IDE according to this tutorial: http://highlowtech.org/?p=1695

I have a problem with millis(). When I use an internal 1 MHz clock it works correctly but when I use external 16 MHz clock it takes millis() much more time than one second to be divisible by 1000.

I tested it with LCD and Hello World sketch, modified to correspond ATtiny's pins. Do millis() actually work with Tiny's?

Why does it work properly with 1MHz and not with 16 MHz which is the same as used in Arduino platform.

Let me guess: "much more time" is about, ohhh, 16 times?

When millis() was written, it had to assume what the input clock was. There is no way to detect the speed of the input clock: to do so would require another clock! So the writers of the function defined a starting constant, set it to 1000000, and required anyone that changed the clock would have to change that constant.

Find the constant, and set it to 16000000. Voilà!

Here's an article on the source code of the function:

https://ucexperiment.wordpress.com/2012/03/16/examination-of-the-arduino-millis-function/


Setting data pin with NanodeUNIO I'm using a sketch that helps to reset Da Vinci XYZPrinter cartridge EEPROMs, and it's based on the NanodeUNIO library. It uses digital pin 7 for data. I want to use my TFT Touch Shield to set the extruder temperature, but the shield also makes use for digital pin 7. Being that the sheild is wired to use pin 7, it can't be changed. But any pin that can be used as a digital pin should be useable with NanodeUNIO (at least, that is my assumption), but I can't find where in NanodeUNIO it sets the data pin. Where is that pin set, and how can it be changed?

xyz_dv_eprom.ino uses low-level access rather than Arduino calls to manipulate PD7, most likely for speed reasons. Lines 96 through 104 (specifically 96, 97, 100, and 104) need to be modified in order to change both the port and the bit used.

ATmegaXX8 pin mapping
ATmegaXXX0 pin mapping
ATmegaXXU4 pin mapping


Two nRF24L01 radios per Arduino Due to the results of my previous post (Slower nRF24L01 round trip delay than expected) I found out that it will be quite difficult to reach my latency requirements.

I am thinking about using my own protocol (instead of the 6-1 Multiceiver protocol), but that would involve getting some kind of 'clocked' receive and send times for devices, which will not make it simple probably. The time to change from reading to writing is less than expected (startListening takes max 350 us and stopListening 450 us). However, if I need to do this ever 5 ms and making sure no devices are reading/sending to others, that's quite a bit of downtime.

So I was thinking, would it be a good (or stupid) idea to use TWO nRF24L01's per Arduino, one by default in reading mode, the other on writing mode (thus having bidirectional communication) and using two different channels. This means I never have to switch between reading and writing and can read/write simultaneously without message colliding.

(note: later I want to use multiple Arduinos and one STM32 device).

Does anyone see problems in this idea?

Requirement goals:

Latency: less than 10 ms to send it from device A to B, process it (excluded, takes a few ms) and send back from B to A (or in some cases B to C). Less than 10 ms is better.
Amount of messages: can be theoretically hundreds per second, in practice max 100 (from various devices, but all go through a processor-device).
Payload per message: 16 bytes probably, most are shorter, some are longer but I can split or combine them if needed.
Range: about 10 meters max, but in a music/band stage environments
Channels: I will not use the WIFI channels, but a range of others, also (professional) wireless mics do not work on 2.4 GHz, so I don't expect too many problems.

About channels: I don't expect any problems. I should have enough channels between 2.484 and 2.525 GHz. This gives me about 40 channels for 1 mbps or 20channels for 2 mbps to chose from.

sources:

2.484 GHz: WIFI Channels, first table with red/green items
2.525 GHz: Datasheet, paragraph 6.3.

At 2 Mbps, a 32-byte packet (40 bytes with preamble, addresses, CRC) will be approx 160 microseconds long.  The round-trip time is likely to be much longer, since the microcontroller or radio will need additional time delays for auto-retry, sending and receiving the response packet, PLL lock, reading the data registers, etc.  In my experience a 2 ms round trip is possible, and the best way to do that is make use of the nRF built-in features:

-- IRQ interrupt: interrupts = fast

-- Enhanced Shockburst: this automatically handles lost packets and failed transmissions.  You can't get that capability any faster via the microcontroller coding.

On top of this, there is scope to use fast SPI libraries (or use SPDR/SPCR registers directly) to transfer data to and from the radio module.  If speed is your goal, don't rely on plug-and-play libraries that others have written.  Read the data sheets carefully and minimize unnecessary delays within the Arduino code.


Trouble connecting Arduino Pro Mini (Atmega328, 3.3V) to nRF24L01 over SPI, receiving all 0 values when I use radio.printDetails(); I am trying to connect my Arduino Pro Mini 3.3V to an nRF24L01 transceiver and cannot see what I am doing wrong. I've checked my wiring a million times because the problem hints there is an invalid or no connection between the Arduino and the transceiver. I have the following pin connections:

  Arduino --------------- nRF24L01

  --GND ------------------- GND

  --VCC ------------------- VCC

  ---D9 --------------------- CE

  --D10 -------------------- CSN

  --D13 -------------------- SCK

  --D11 -------------------- MOSI

  --D12 -------------------- MISO

I am using the following sketch

#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
#include "printf.h"

RF24 radio(9, 10);

const uint64_t pipes[2] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0C2LL };     //Addresses to send/receive

void setup()
{
  printf_begin();
  Serial.begin(9600);
  radio.begin();
  radio.setRetries(15, 15);
  radio.openReadingPipe(1, pipes[0]);
  radio.printDetails();
  radio.stopListening();
}

void loop()
{
  const char text[] = "Hello World";
  radio.write(&text, sizeof(text));

  delay(1000);
}

I have no clue where I am going wrong. This setup works well on my Uno, however I cannot replicate it on the Arduino Pro Mini. Can anyone tell me if I am doing something super wrong that would prevent this from working? I'm all out of ideas. Appreciate any help in advanced!

Update:

I forgot to copy and paste the output from printDetails():

STATUS  = 0x00
RX_DR=0
TX_DS=0
MAX_RT=0
RX_P_NO=0
TX_FULL=0
RX_ADDR_P0-1    = 0x0000000000 0x0000000000
RX_ADDR_P2-5    = 0x00 0x00 0x00 0x00
TX_ADDR = 0x0000000000
RX_PW_P0-6  = 0x00 0x00 0x00 0x00 0x00 0x00
EN_AA   = 0x00
EN_RXADDR   = 0x00
RF_CH   = 0x00
RF_SETUP    = 0x00
CONFIG  = 0x00
DYNPD/FEATURE   = 0x00 0x00
Data Rate   = 1MBPS
Model   = nRF24L01
CRC Length  = Disabled
PA Power = PA_MIN

Whenever you get an all zeros output from the printDetails() function you can bet you are having a communication issue between the Arduino and the nRF24 module.

Start by checking your connections.

Check your connections again, using a multimeter to ensure continuity.

Check your connections again (no, I'm not joking).

Finally add a capacitor (anything between 1uF and 100uF will do) between the VCC and GND pins of your nRF24 module: those modules are pretty sensitive to voltage fluctuations and they are subject to current consumption spikes at startup.

Pair that with a possibly not state of the art voltage regulator (especially on cheap Arduino clones) and you end up with a non responding nRF24 module: the capacitor will provide the extra juice whenever it's required by the radio module.

This is such a common problem that I started soldering the capacitors directly onto the modules to save breadboard space!