Undefined reference in Eclipse of .h and .cpp files I'm trying to create a linked list for use on the Arduino, in the Eclipse IDE with the Arduino/Sloeber plugin. The linked list is written in a .h and .cpp file, and included locally in the project.

However, when building, I get the error undefined reference to Structures::LinkedList<int>::LinkedList().

And despite the fact that I've added the local folder to the list of includes (and it can find the top level file containing setup() and loop()), the problem persists;

My relevant file listings are below. Any ideas of what settings I can add to Eclipse in order to solve this? Potentially, could it be something to do with the use of template<typename T> in the header file?

Thanks very much,

David

FYI: This problem does not occur with the core libraries i.e. I can run examples like Serial and Blink.

My top level .cpp is pretty simple:

#include "LinkedList.h"
#include "RAStarSearch.h"
#include "Arduino.h"

using namespace Structures;
void setup() { }

void loop() {
  LinkedList<int> list = LinkedList<int>();
  return;
}

And the referenced .h is:

#ifndef LINKEDLIST_H_
#define LINKEDLIST_H_
#include "Arduino.h"

namespace Structures {
template<typename T>
class LinkedList {
  public:
    /// Struct inside the class LinkedList
    struct Link {
      T value;
      Link *next;
    };

    LinkedList<T>(); ///< Default constructor
    void addValue(T val); ///< prepends new value at beginning of list
    T popValue(); ///< returns first element and deletes Link.
    Link* peekLink(); ///< Looks at first value
  private:
    Link *head; // this is the private member variable. It is just a pointer to the first Node
};
const int ERRNUM = 0x8000000; ///<Error number used, as exceptions not supported
}
#endif /* LINKEDLIST_H_ */

EDIT

On request I have included my code for LinkedList.cpp

#include "LinkedList.h"
#include "Arduino.h"

namespace Structures {
  template<typename T>
  LinkedList<T>::LinkedList() {
    head = NULL; // set head to NULL
  }
  template<typename T>
  void LinkedList<T>::addValue(T val) {
    Link *n = new Link();   // create new Node
    n->value = val;             // set value]

    if (head == NULL) { //i.e. if list is empty
      n->next = head;         // make the node point to the next node or NULL
      head = n;    // last but not least, make the head point at the new node.
    } else {
      Link *it = head;
      Link *oldIt = NULL;
      //TODO check edge cases i.e. insertion at beginning and end of list
      while (n->value > it->value){ //until place in list is found, needs T to have > operator
        oldIt = it;
        it = it->next;
      }
      oldIt->next = n; //Set pointer to n
      n->next = it; //Set n pointer to next
    }
  }
  template<typename T>
  T LinkedList<T>::popValue() {
    T retval = ERRNUM;
    if (head != NULL) {
      Link *n = head;
      retval = head->value;
      head = head->next;
      delete n;
    }
    return retval;
  }
  template<typename T>
  typename LinkedList<T>::Link* LinkedList<T>::peekLink() {
    return head;
  }
}

Have you tried placing the H file in the same folder as you main cpp file.  This should prove beyond all doubt that there is nothing wrong with the code (I can't see anything wrong).

I suspect its a path issue.  You need to check that Eclipse is setup up properly to source the libraries from you custom location.  Also it needs to be passing this location on to the compiler.  I don't know how to do that in Eclipse but Google should point you in the right direction. Try this http://forum.arduino.cc/index.php?topic=39972.0 ?

Also you might find it easier to specify the include files in the order system, 3rd party libraries, local libraries and then local include files.  This means that duplicate definition faults are reported against the files nearest to the ones you have written.  If you define time_t using your ordering the fault will be reported against  rather than your header file.

Also a using namespace foo statement removes the benefits that namespaces provide, so its best not to do it.

EDIT
Doh - I should have spotted this sooner.  Template classes have to have the functions inline not in a CPP file.  This is because the CPP file can't change what T is at compile time, but because the H file is included in the file it is used in when it is preprocessed the object represented by T can change.
Basically inline your functions and it will work.


Arduino Ethernet Shield Response Process, Time, and Synchronization I have a ethenet shield. I want to update my server page. Server page have to show current time. The code is given in this link. Code works but there is two problem

1- When i press the stop button in the browser, Arduino stops. After this i press refresh button and there is no response.

2- How can i synchronize the arduino time. From where? without setup another server. Is there any time stamp server that compatible with arduino?

I don't have an answer for question 1.

For question 2:

You can add a function to implement an NTP (network time protocol) client.  For example, see the UdpNtpClient article on arduino.cc.  In your setup() or loop() code call the function initially or perhaps hourly or daily to set system time via an NTP time server.  The server's IP address can be hardcoded or otherwise as you like.

For lists of public time servers, see www.ntp.org and pool.ntp.org.

Alternately, you could add a DS1302 or similar clock chip board to your hardware.


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

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

How do I go about this?

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


Unable to use RGB matrix and the serial monitor at once Recently I bought the following matrix:
https://learn.adafruit.com/32x16-32x32-rgb-led-matrix/overview

I own an Arduino Uno for those who are interested.

I got the 32x32 variant and I am very happy with it. I managed to connect all the wires correctly and get the examples of the library working.

The problem I am facing right now is I can't get it to work properly for a personal project of mine. Somehow I am unable to use the serial functions and the matrix library functions in one project.

Currently my project looks like this:

My Arduino is connected like this:

And the code I wrote is:

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

#define CLK 8
#define OE  9
#define LAT 10
#define A   A0
#define B   A1
#define C   A2
#define D   A3

RGBmatrixPanel matrix(A, B, C, D, CLK, LAT, OE, false);
String incomingCommand = "";

void setup() {
  Serial.begin(9600);
  matrix.begin();
  matrix.fillRect(0, 0, 32, 32, matrix.Color333(0, 0, 0));
}

void loop() {
  if (Serial.available() > 0) {
    int incomingByte = Serial.read();
    char receivedChar = (char) incomingByte;
    incomingCommand += receivedChar;
  }

  if (incomingCommand.indexOf('#') > - 1 && incomingCommand.indexOf('%') > - 1) {
    String rawCommand = incomingCommand.substring(incomingCommand.indexOf('#'), incomingCommand.indexOf('%') + 1);
    rawCommand = rawCommand.substring(1, rawCommand.length() - 1);
    Serial.print("Following command received: ");
    Serial.println(rawCommand);
    if (rawCommand == "turnledon") {
      matrix.drawPixel(0, 0, matrix.Color333(7, 7, 7));
    }
    incomingCommand = "";
    rawCommand = "";
  }
}

The idea is that a command gets sent from the serial monitor. Based on the command one led on the matrix will turn on. An example of a future command will look similar to this: "#drawPixel_X1_Y2%", hence the part that checks on "#" and "&".

The problem is that the functionality of the serial monitor isn't working with line 14 and 48 of the code. As soon as I remove those lines, the serial monitor works perfectly and I can receive and write to the serial monitor. I have no idea what is causing this.

I was wondering if someone ever faced a similar problem or knows what I am doing wrong right now.

Thank you in advance!

According to Adafruit https://learn.adafruit.com/32x16-32x32-rgb-led-matrix/overview these led matrixes require active scanning. It means that the RGBMatrixPanel will set up some scanning interrupt to refresh the screen periodically.

This can very much interfere with serial receive, as according to Adafruit, the panels require a serious data transmission all the time.

Try the followings:

have one byte serial commands, e.g. N for "on" and F for "off" (I know you will need more complex commands, but this is just to verify the theory)
remove all debug Serial.printlns (those also consume some time)

So try this:

void loop() {
  if (Serial.available() > 0) {
    char incomingByte = Serial.read();
    if (incomingByte=='N') {
       matrix.drawPixel(0, 0, matrix.Color333(7, 7, 7));
    }
    if (incomingByte=='F') {
       matrix.drawPixel(0, 0, matrix.Color333(0, 0, 0));
    }
  }
}


Arduino ESP8266 direct/fast control of the digital pins How does one control a digital pin directly avoiding the slow digitalWrite or digitalRead?

After a weekend of searching and trying, here is what I was looking for:

It is slightly different than for the AVR chips. There is one register for setting the pins to HIGH and another one to set the pins to low.

Setting the pin HIGH:

GPOS = (1 << PIN_OUT);

Setting the pin LOW:

GPOC = (1 << PIN_OUT);

using this, I managed to speed up my code by a factor of three. It is not as dramatic as for the AVR chips, since the digitalWrite function is much more simple for the ESP8266.


Arduino Uno + Wifi Shield + PS2 Keyboard + LCD Display I'm new in the Arduino Community and I'm facing a problem when I try to use a PS2 Keyboard and an LCD Display (16x2) on an Arduino Uno with a Wifi shield.

I would like to write something with the keyboard and display it in the LCD before sending it to a webservice.

Here is my problem:

When I use the keyboard and the display on my Arduino WITHOUT the wifi shield --> All is OK. I can write on the display the key that has been pressed.
When I use the keyboard and the display on my Arduino WITH the wifi shield --> All is OK until I write something on the display. As soon as I write on the display with the function lcd.print(), the keyboard does not work anymore (it detect the character '2' every time I press a key).

It's very surprisingly because if I dont use lcd.print(), the keybord works without any problem.

Here is a part of my code:

#include <LiquidCrystal.h>
#include <PS2Keyboard.h>

LiquidCrystal lcd(12, 11, 2, 5, 6, 8);
PS2Keyboard keyboard;

const int DataPin = 9;
const int IRQpin = 3;

void setup(){
  keyboard.begin(DataPin, IRQpin);
  lcd.begin(16, 2);
}

void loop(){
  checkKeyboard();
}

void checkKeyboard(){
  if (keyboard.available()) {

    char c = keyboard.read();

    // check for some of the special keys
    if (c == PS2_ENTER) {
      Serial.println();
    } else if (c == PS2_TAB) {
      Serial.print("[Tab]");
    } else if (c == PS2_ESC) {
      Serial.print("[ESC]");
    } else if (c == PS2_PAGEDOWN) {
      Serial.print("[PgDn]");
    } else if (c == PS2_PAGEUP) {
      Serial.print("[PgUp]");
    } else if (c == PS2_LEFTARROW) {
      Serial.print("[Left]");
    } else if (c == PS2_RIGHTARROW) {
      Serial.print("[Right]");
    } else if (c == PS2_UPARROW) {
      Serial.print("[Up]");
    } else if (c == PS2_DOWNARROW) {
      Serial.print("[Down]");
    } else if (c == PS2_DELETE) {
      Serial.print("[Del]");
    } else {
      Serial.print(c);
      displayText(c);
    }
  }
}

void displayText(char c){
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("Pressed key:");
  lcd.setCursor(0,1);
  lcd.print(c);
}

Does somebody know how to solve this problem?

Thank you very much in advance :)

Edit: Here are the pins that I use on the board :

Arduino pin 2 -> LCD pin 11
Arduino pin 5 -> LCD pin 12
Arduino pin 6 -> LCD pin 13
Arduino pin 8 -> LCD pin 14
Arduino pin 11 -> LCD pin 6
Arduino pin 12 -> LCD pin 4
Arduino pin 3 -> Keyboard IRQ
Arduino pin 9 -> Keyboard Data

Sorry I do not have enough reputation to place a comment.

@Valentin from the link, you provided, to the wifi shield it states that it uses pins 11 ,12 and 13 on the UNO which will give you a conflict on pins 11 and 12 with the LCD. Not sure why that manifests as an apparent keyboard error though:

From the linked page:

  Arduino communicates with both the Wifi shield's processor and SD card using the SPI bus (through the ICSP header). This is on digital pins 11, 12, and 13 on the Uno and pins 50, >51, and 52 on the Mega. On both boards, pin 10 is used to select the HDG204 and pin 4 for >the SD card. These pins cannot be used for general I/O. On the Mega, the hardware SS pin, >53, is not used to select either the HDG204 or the SD card, but it must be kept as an output or the SPI interface won't work.

Again sorry this is not a full answer but thought it may help.


Arduino Audio Shield Problems I recently bought a Velleman KA02 Arduino Audio Shield (http://www.velleman.co.uk/contents/en-uk/p579_ka02.html), which uses an ISD1760PY audio chip and soldered it together. The first time I fired it up, it worked fine, I had freshly soldered it together. But from the next time up to now, if I press any button but the reset button, the onboard LED blinks 7 times and it doesn't record or do anything. I checked the solder joints and nothing fell out and I also checked the ISD1760PY datasheet but found nothing about my problem. Is there a way to fix this and why it it happening? Please note that I am not controlling the shield with SPI or with the Arduino.

This question was put on hold in the EE section so I an posting it here because the reason was that it has something to do with Arduino.

Look at page 35 of winbond datasheet.
If the LED is blinking 7 times either the chip is in isp mode or in an unstated mode. This can happen after power off during erase function.
I held erase button for about 20 seconds and after that I was able to record messages.


Websockets with the ESP8266 using arduino uno board I'm trying to make an iot device that connects to my wifi, establishes a socket connection with my golang backend and then starts to send sensor data from the ardunio.

I've got an ardunio uno board and this ESP8266:

I found this websockets library but I don't know if I can import the .h files if I have "arduino uno" selected in the IDE

My question:
Is it possible to establish a WebSocket connection with my go backend using the esp model that I have? If so, how can I import the required libraries in the arduno IDE? I would be happy if you could give me some directions.

The library you linked is not for Uno with esp8266 module.

It is possible to use the ESP-01 with Uno for WebSockets client for example with ArduinoHttpClient library over the WiFiEsp library.

Better option is to use only an esp8266 development board programmed with Arduino IDE without the Uno.


Please , explain about MAX30100 using for Arduino to read ADC in format (0-1023) can anyone help me..? I am using MAX30100 with arduino, and my expectation is i can to process the ADC as usual (0-1023), but I do not understand the signal processing. Has anyone used the MAX30100 here before? if so, how to process the ADC's wavelength?

This device does most of the low-level processing for you. The measurements and processing to compute pulse rate and oxygenation are done on the board. You need an I2C library (the 'wire' library is one), and a MAX30100 library (there appear to be a few of them).
Here is a link to the MAX30100 datasheet which has all of the low-level detail you might ever want to know about how this chip does what it does.
There is at least one tutorial for this device; I found this one that seems to make sense to me as I read it (and I have never used this device). It tells you which MAX30100 library the author used (there are a few) and provides some sample code.
If it were me, I'd follow the tutorial (the one I linked or some other one)
to get something working quickly, and use that knowledge to get your own project going. If you have questions about the device itself, you can find answers in the data sheet.


One time execution of a variable incrementation As part of a larger script intended for a very simple arduino "synthesizer" I am trying to increment the amount of cycles a melody will be played once a key is pressed (the key in turn passes a value to the variable selectMel). The problem I encounter is that the moment I call my function in the main void loop() function, I cannot control the incrementation of the variable ncycles, which is intended to be only increased once per key press. I tried to solve this by creating a global switchVar variable as an "on/off" switch but that did not do much to solve the issue at hand.

Any tips or help will be greatly appreciated!

PS: I have of course googled and tried the solutions posted on similar stackExchange posts but to no avail, sadly.

      void playMan (int ncycles, int mSpeed) {

        switch (selectMel) {
        case 1:
          if (ncycles > 0) {
            tone(12, NOTE_B7, mSpeed);
            delay(100);
            tone(12, NOTE_B5, mSpeed);
            delay(100);
            tone(12, NOTE_B3, mSpeed);
            delay(100);
            tone(12, NOTE_B1, mSpeed);
            delay(100);
            ncycles--;
            break;
          case 2:
            if (millis() % 100 == 0) {
              if (switchVar == 1) {
                ncycles += 5;
                switchVar = 0;
              }
              Serial << ncycles << endl;
            }
            break;
          default:
            break;
          }
        }
      }

See http://www.gammon.com.au/switches.

Basically you need to detect the transition between the switch not being pressed before, and now being pressed. This transition will occur once per press (possibly after you add debouncing). If you just test for the switch pressed naturally you will get multiple increments.

  Assuming I add debouncing, how would it help in incrementing the value of ncycles only once ?

To clarify, you increment once on a transition, note when you did this (eg, by calling millis() ) and then ignore any further transitions for, say 10 ms.


NeoPixel Gradient sweep function I'm trying to create a function that takes two colours and creates a smooth gradient between them one colour at the beginning and one at the end

I just can't figure the math of mixing them evenly

I'm using neopixel library

I can think of two ways of doing this.

One is to use the H channel of the HSV colour space (as I show in the answer to this question. This would give you a smooth transition between two colours through the pre-defined spectrum of the hue range.

The second is to simply specify two colours and then mix them at different percentages depending on how far along the length you are.

For example, here's a (untested) small function that "mixes" two individual colour channels together and returns the result:

uint8_t mix(uint8_t a, uint8_t b, int pct, int range) {
    if (pct <= 0) return a;
    if (pct >= range) return b;
    return (((uint32_t)a * (range-pct)) / range) + (((uint32_t)b * pct) / range);
}

pct is the led number in your chain, and range is the total number of LEDs.

So you could (hypothetically):

uint8_t red1 = 0, green1 = 255, blue1 = 0;
uint8_t red2 = 255, green2 = 100, blue2 = 100;

for (int i = 0; i < 50; i++) {
    uint8_t red = mix(red1, red2, i, 50);
    uint8_t green = mix(green1, green2, i, 50);
    uint8_t blue = mix(blue1, blue2, i, 50);
    setLedColor(i, red, green, blue);
}


Cheap Wired Multipoint Mesh Network I'm looking to make a 15 x 15 grid of load sensors and RGB LEDs for an interactive dance floor. Each node will be driven by an arduino and the entire floor will be managed by a RaspberryPi. I'm trying to figure out the best way to have the nodes communicate with the Pi. Ideally the network would have these characteristics:

Low cost per node
Raspberry Pi as the master, arduino nodes as slaves
Ability to know where each node is in the grid
Healing: If a node goes down it doesn't take out all the others.
Can easily replace broken nodes
The electronics for each node will be ~12 inches apart
The master will be 5 - 10 feet away from the matrix.

So far I have been toiling over a few ides.

I2C
This would allow each node to be addressable, however, it seems that Arduino will only allow up to 127 addresses and this matrix will have at least 225 nodes.

SPI
If daisy chained it would be easy to know where each node is in the matrix. But if one node were to break all the nodes after it would stop communicating. (right?) I could have each row daisy chained separately, so if one goes down it only affects that row.

1-Wire
1-wire also looks promising. I'd have to figure out my own way of determining node placement, which could be achieved a variety of ways.

Custom Serial
Each node has a serial connection (rx/tx) for each of it's four sides. This would allow it to communicate to each of it's neighbors directly and pass along messages that are not addressed to it. If one node were to go down, the message would be automatically routed around the broken node since there are several paths to each destination. This option is a little crazy and I'd prefer to avoid something so custom and convoluted.

USB
This would require a USB hub in each node.

XBee
Too expensive.

Other thoughts or options?

For I2C you can try http://www.linear.com/product/LTC4312

This will allow you to make two I2C networks to address all the nodes.

However, the wiring for I2C will be a nightmare, but it might be necessary if you want the nodes to be independent.


What sensors do I need to detect magnetic "take off"? I want to build a sensor using arduino (or any other esp) measuring the release of a leg on a floor panel. I've build a prototype using copper plates and a BBC Micro:bit, which works fairly well. But I want to use magnetic sensors, determining release of the leg.
My education on magnetic is - simple. I know it exists. I know it's one of four basic forces in nature (ha!). But I don't know how to measure it using electronic circuits (I'm new to this topic).
Imagine one person stands on a plate, wearing magnets on his foot (say "magnetic socks"). I want to immediately detect when the person raises his leg. What kind of sensors do I need?

You have two options here, either a Hall Effect sensor or an Inductive Sensor. The hall effect sensor is probably the best option. This will likely need some calibration on your end to identify the exact value you record at "Take Off" for your setup.


Arduino Due analog output has 500mV offset I use a simple serial connection to tell the Due what to output into an analog output pin. However, the outputs are offset about 550mV (as seen on an oscilloscope) and the maximum value of 255 gives ~2.7V. What am I missing? Why can't the DAC output 0V - 3.3V mapped onto 0 - 255 values?

int output = DAC1; // analog output pin
String inData;

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

void loop() {
  while (Serial.available() > 0) {
    char value = Serial.read();
    inData += value;
    if(value == '\n'){
      val = inData.toInt(); // 0..255
      analogWrite(output, val);
      Serial.println(val);
      inData = "";
    }
  }
}

I don't know how old this thread is, anyway I thought it doesn't hurt to give some insight because I experienced the same problem. Look at:
http://www.atmel.com/Images/Atmel-42187-ATSAM3X-and-ATSAM3A-Series-Checklist_AP-Note_AT03462.pdf
page 13: DAC0 and 1 voltage lays between 1/6 ADVREF and 5/6 ADVREF which corresponds to approximately ADVREF=3.2v; Span is (4/6)*3.2 = 2.1v
for periodic signals, Offset can be removed by using a small decoupling capacitor which will act as a high pass filter.
Hope this helps


replacing #define with typedefs for bracket scope I have a project in which basically i have to concatenate existing code.
Each code comes with its own #defines.
But defines are not touched by the compiler, but the preprocessor.

Each snippet of the program will exist in its own fucntion.

Is it possible to include the #defines of each program - now each function, inside this function (and visible only to this function's scope)?

The proper way to do it, would be to replace text reassignment from #define to typedef?

I understand typedef is originally for defining types. But can it be used here? Is there another alternative?

It is possible to use "namespace { ... }" to create local defines for a *.cpp file.
In the Arduino IDE all *.ino files are combined in a single *.cpp file, therefor the "namespace" is not very useful.

When you create new tabs in the Arduino IDE and name them *.cpp, then you have different *.cpp files. Then you can use the "namespace" to create defines that are only valid for that *.cpp file.

More info: Hackaday: Using Modern C++ Techniques with Arduino


Can PWM break a DC motor? I want to know if controlling the speed of a DC motor with PWM could break (burn out the DC motor. Sorry my English isn't that good.

Provided that the voltage specs of the motor are not violated, no. However, the inductance of the motor stands a very good chance of destroying the switch unless an appropriately-rated flyback diode is used.


Arduino - Progamming issue my first post here.

Anyway I'm working on a Simon Says game.
I have a weird bug with the function that reads button input.

This is the code:

int deBounce(int count){
  int pressed=-1;
  int laastButtons[3]; // save the previous deBounce read.
  for(int x; x<4; x++)
  {
    laastButtons[x] = lastButtons[x];
    lastButtons[x] = !digitalRead(button[x]);
    if(lastButtons[x] == true)
    {
      delay(50);
      lastButtons[x] = !digitalRead(button[x]);
      if(lastButtons[x] == 1){ pressed = x;}
      nt("Pressed!, Button ID: ");nt(x); nt(" pressed:  ");nt(pressed); nt(" state "); ntln(lastButtons[x]);
    }
  }
  if((lastButtons[0] + lastButtons[1] + lastButtons[2] + lastButtons[3]) > 1)
  {
    ntln("ERROR: dont press more than one button at a time. ");
  }
  if( ((lastButtons[0] + lastButtons[1] + lastButtons[2] + lastButtons[3]) == 1 ) && !laastButtons[pressed] && (pressed != -1) ) {
    pressButtons[count] = pressed;
    nt("Pressed!, ID: ");nt(count); nt(" Button ID ");ntln(pressed);
    return count++;
  }else return count;
}

This is what I recieve in the Serial Monitor if I press one of the buttons.

  Pressed!, Button ID: 3 pressed: -1 state 1

How is that possible? Note the lines where that line is printed and the line above it.
Seems like that if should run, but the line pressed = x; doesn't function.
Note that, nt and ntln are just a short for Serial.print.
I have this weird bug and sometimes it seems like the chip is glitching!

Another question is- I tried attaching interrupt and it didn't worked,
Is it possible that my board is not compatiable with them? (It's not original).

Thanks.

EDIT:

After Majenko helped me figure it out,
The thing that created the bug was that I expected a x==0, but I didn't define it in the for loop.

Before:

for(int x; x<4; x++)

After:

for(int x=0; x<4; x++)

Thanks again Majenko!

int laastButtons[3]; // save the previous deBounce read.
for(int x; x<4; x++)
{
   laastButtons[x] = lastButtons[x];

Well, there's a common bug right away.  An array with three slices, numbered 0, 1 and 2, and you're accessing them with a loop that counts from 0 to 3.

Spot the error.

Also, in the for loop, what number does it start counting from?

And now for your "bug".  This block of code:

if(lastButtons[x] == true)
{
  delay(50);
  lastButtons[x] = !digitalRead(button[x]);
  if(lastButtons[x] == 1){ pressed = x;}
  nt("Pressed!, Button ID: ");nt(x); nt(" pressed:  ");nt(pressed); nt(" state "); ntln(lastButtons[x]);
}

I think you have it slightly wrong.  Let's convert it into plain english:

If button is pressed:

Delay 50 ms
Read button again
If button is pressed:

Set pressed to the button number

Print the button message

Note the indenting, which highlights what gets executed for what IF statement.  The print is going to happen regardless of the setting of the pressed variable.

I think the structure you wanted is:

If button is pressed:

Delay 50 ms
Read button again
If button is pressed:

Set pressed to the button number
Print the button message

In that layout the second If is controlling both the setting of the pressed variable as well as whether or not to print the Pressed! message.

if(lastButtons[x] == 1){ pressed = x;}

That line is saying "If last buttons X is 1, then set pressed to X. That is all it is doing. Nothing more, nothing less.


Combining two codes to jump back and forth between them I have a code for both a magnetometer, and a GPS, both written to give off just one reading at a time. I'm trying to make a sketch that is able to go back and forth between these two codes so I get both sets of data.

Here is the GPS Code:

#include <NMEAGPS.h>
#include <NeoSWSerial.h>

NeoSWSerial gpsSerial(3, 2);
NMEAGPS     GPS;
gps_fix     fix;

void setup()
{
Serial.begin(115200);
Serial.println( F("Run once!") ); // F macro saves RAM!

gpsSerial.begin(9600);
gpsSerial.println( F("$PMTK314,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0*28") ); // RMC & GGA only
gpsSerial.println( F("$PMTK220,1000*1F") ); // 1Hz update rate

waitForFix();
printFix();
}

void loop()
{
}

void waitForFix()
{
uint8_t fixes = 0;

do {
if (GPS.available( gpsSerial )) {
  fix = GPS.read();
  fixes++;
}
} while ((fixes < 2) && !fix.valid.location);

} // waitForFix

void printFix()
{
Serial.print( F("Time: ") );
if (fix.valid.time) {
if (fix.dateTime.hours < 10)
  Serial.print( '0' );
Serial.print(fix.dateTime.hours);
Serial.print(':');
if (fix.dateTime.hours < 10)
  Serial.print( '0' );
Serial.print(fix.dateTime.minutes);
Serial.print(':');
if (fix.dateTime.hours < 10)
  Serial.print( '0' );
Serial.print(fix.dateTime.seconds);
Serial.print('.');
if (fix.dateTime_cs < 10)
  Serial.print( '0' );
Serial.print(fix.dateTime_cs);
}
Serial.println();

Serial.print( F("Date: ") );
if (fix.valid.date) {
Serial.print(fix.dateTime.day);
Serial.print('/');
Serial.print(fix.dateTime.month);
Serial.print('/');
Serial.print( fix.dateTime.full_year() );
}
Serial.println();

Serial.print( F("Fix status: ") );
if (fix.valid.status)
Serial.print( (int) fix.status );
Serial.println();

if (fix.valid.location) {
Serial.print( F("Location: ") );
Serial.print( fix.latitude(), 4 );
Serial.print( F(", ") );
Serial.println(fix.longitude(), 4);
}

if (fix.valid.speed) {
Serial.print("Speed (knots): ");
Serial.println( fix.speed() );
}

if (fix.valid.heading) {
Serial.print( F("Angle: ") );
Serial.println( fix.heading() );
}

if (fix.valid.altitude) {
Serial.print( F("Altitude: ") );
Serial.println( fix.altitude() );
}

if (fix.valid.satellites) {
Serial.print( F("Satellites: ") );
Serial.println( fix.satellites );
}
}

Here is the Magnetometer Code:

#include <Wire.h> //I2C Arduino Library

#define address 0x1E //0011110b, I2C 7bit address of HMC5883

void setup(){
//Initialize Serial and I2C communications
Serial.begin(9600);
Wire.begin();

//Put the HMC5883 IC into the correct operating mode
Wire.beginTransmission(address); //open communication with HMC5883
Wire.write(0x02); //select mode register
Wire.write(0x00); //continuous measurement mode
Wire.endTransmission();
}
void loop(){

int x,y,z; //triple axis data

//Tell the HMC5883L where to begin reading data
Wire.beginTransmission(address);
Wire.write(0x03); //select register 3, X MSB register
Wire.endTransmission();

//Read data from each axis, 2 registers per axis
Wire.requestFrom(address, 6);
if(6<=Wire.available()){

x = Wire.read()<<8; //X msb
x |= Wire.read(); //X lsb
z = Wire.read()<<8; //Z msb
z |= Wire.read(); //Z lsb
y = Wire.read()<<8; //Y msb
y |= Wire.read(); //Y lsb
}

//Print out values of each axis
Serial.print("x: ");
Serial.print(x);
Serial.print("  y: ");
Serial.print(y);
Serial.print("  z: ");
Serial.println(z);

delay(250);

while(1);

}

I don't know if this is even feasible, considering my lack of coding knowledge, but thanks for looking into it

The solution in short.

Although the link is very stupid, it shows very well what you have to do.

Pretty much make a code that combines both of them together. Put both setup in the new setup and carry on like that. Note that you have declared the serial monitor at 2 different baud rates so you can only pick one. Don't repeat previously declared things in your new code and you should be good to go.

Simple example:

Code 1:

const int buttonPin = 2;

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

void loop() {
  buttonVal = digitalRead(buttonPin);
  Serial.println(buttonVal);
}

Code 2:

const int potPin = A0;

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

void loop() {
  potVal = analogRead(potPin);
  Serial.println(potVal);
}

Fusionned code:

const int potPin = A0;
const int buttonPin = 2;

void setup() {
  pinMode(buttonPin, INPUT);
  Serial.begin(9600); //go for the lowest baud rate for reliability
}

void loop() {
  buttonVal = digitalRead(buttonPin);
  Serial.print(buttonVal);

  Serial.print("  -  ")

  potVal = analogRead(potPin);
  Serial.println(potVal);
}


Build Infrared Camera Remote I wish to build a remote for my Camera i.e Sony NEX 5R. It has a built in IR receiver and has several Sony as well as aftermarket remotes provided for it. Due to my interest in Micro controller design I wish to build one myself rather than use an aftermarket one.

A friend who did the same for his NEX 5 series camera posted a video of the same on Facebook, which inspired me to build my own. I plan to use an Arduino Uno R3 with the following additional components:

IR LED
NPN Transistor(for amplification)
Schmidt Triggers(for rectification)
9 Volt Battery

Ultimately I would like to swap out the Arduino for a standalone ATmega328 or ATtiny2313 but currently I have some issues as of now:

I currently do not have a schematic or a sample code which I can use. I have been trying to search the internet for the same but to no avail.
I am unsure of the protocol used by my camera. I have found it difficult to find documentation on the same.
How can I replace the 9-Volt battery for something smaller?
I would like to use a smaller micro controller but what differences will I encounter when trying to change my code for the smaller micro controller?
For such a project, will I need additional hardware?

Using the Arduino shouldn't be any different than any other microcontroller.
The IRremote library is my go-to library for any IR related stuff.
Power shouldn't be an issue, look at the Moteino from LowPowerLab and check out his coin cell battery tests. It's definitely possible. Not with a full blown Uno, but with a bare chip, yes.
You want to burn the bootloader on the IC first, before you can start writing Arduino code. Check out this tutorial: From Arduino to a Microcontroller on a Breadboard. It's the same process for an ATTiny, you just have to look at the datasheet to see where to plug things into. Specifically, MOSI, MISO, SCK, and Reset pins. The Tiny AVR Programmer is also a good choice. It's meant for the 8 pin micros but it has an ISP header so you can use it for almost any chip.

This may be useful for more information about decoding IR signals:

EEVblog #505 - IR Learning Remote Control Hack
EEVblog #506 - IR Remote Control Arduino Protocol Tutorial


Arduino DUE Interrupt 1MHz My Due is interfaces with a DAC which I need to update with freq 1MHz. The nice solution seems to be a timer interrupt. I found a thread here called "Arduino Due - creating an 8Mhz clock signal". I tried the following code to see if I can get 4MHz on P41. No luck. Any help will be greatly appreciated. Thanks.

volatile boolean l = false;

void TC6_Handler()
{
    TC_GetStatus(TC2, 0);
    digitalWrite(41, l = !l);
}

void startTimer(Tc *tc, uint32_t channel, IRQn_Type irq) {
    pmc_set_writeprotect(false);
    pmc_enable_periph_clk((uint32_t)irq);

    TC_Configure(tc, channel,
    TC_CMR_WAVE |
    TC_CMR_WAVSEL_UP_RC |
    TC_CMR_TCCLKS_TIMER_CLOCK1|
    TC_CMR_ACPA_TOGGLE );  // RC compare TOGGLES TIOA);

    TC_SetRA(tc, channel, 1); //50% high, 50% low
    TC_SetRC(tc, channel, 1);

    PIO_Configure(PIOC,
    PIO_PERIPH_B,
    PIO_PC25B_TIOA6,
    PIO_DEFAULT);

TC_Start(tc, channel);

}

void setup(){
pinMode(41,OUTPUT);
startTimer(TC2, 0, TC6_IRQn);
}

void loop(){
}

I'm not 100% certain without my Due in front of me to test this, but as far as I can see, you are configuring your clock to run at 42MHz with "TC_CMR_TCCLKS_TIMER_CLOCK1" and are getting the timer to trigger when the count is "1" with "TC_SetRC(tc, channel, 1);", which would give you 42MHz, not 4MHz.

Since the clock timer still increments during the TC6_Handler() function, I'm guessing that the interrupt triggers a second time before it has exited the function the first time causing a hang.

Try changing your code to "TC_SetRC(tc, channel, 42000000 / 4000000);" to see if that works.  Your interrupt will still be triggered every 10 ticks of the timer which will only give you 20 ticks of the CPU clock to do your work and exit.  I suspect this may still be too little time to exit before the next interrupt is triggered.  If you still don't get the result you want, try reducing the frequency considerably to see if your timer is actually getting configured correctly.  I don't think you can get exactly 4MHz as the Due timer frequencies are not divisible by 4000000, unless my brain is a little fuzzy this morning and I'm missing something obvious...

If you do need to optimise the code inside your handler so it can run faster, let me know and I'll post some ideas when I can get near my Due and my source code for reference.

You could always check out this link that I used when I needed to understand how to set up a timer for my own projects:
http://2manyprojects.net/timer-interrupts
Should that link go dead before you have a chance to read up, this is the example source from that page I modified for my own purposes:

// These are the clock frequencies available to the timers /2,/8,/32,/128
// 84Mhz/2 = 42.000 MHz
// 84Mhz/8 = 10.500 MHz
// 84Mhz/32 = 2.625 MHz
// 84Mhz/128 = 656.250 KHz
//
// 42Mhz/44.1Khz = 952.38
// 10.5Mhz/44.1Khz = 238.09
// 2.625Hmz/44.1Khz = 59.5
// 656Khz/44.1Khz = 14.88 // 131200 / 656000 = .2 (.2 seconds)

// 84Mhz/44.1Khz = 1904 instructions per tick
const int led_pin = 13;
int state = false;
int interruptCtr = 1;
int S = 0;

void setup()
{
  pinMode(led_pin, OUTPUT);
  /* turn on the timer clock in the power management controller */
  pmc_set_writeprotect(false);       // disable write protection for pmc registers
  pmc_enable_periph_clk(ID_TC7);     // enable peripheral clock TC7

  /* we want wavesel 01 with RC */
  TC_Configure(/* clock */TC2,/* channel */1, TC_CMR_WAVE | TC_CMR_WAVSEL_UP_RC | TC_CMR_TCCLKS_TIMER_CLOCK4);
  TC_SetRC(TC2, 1, 131200);
  TC_Start(TC2, 1);

  // enable timer interrupts on the timer
  TC2->TC_CHANNEL[1].TC_IER=TC_IER_CPCS;   // IER = interrupt enable register
  TC2->TC_CHANNEL[1].TC_IDR=~TC_IER_CPCS;  // IDR = interrupt disable register

  /* Enable the interrupt in the nested vector interrupt controller */
  /* TC4_IRQn where 4 is the timer number * timer channels (3) + the channel number (=(1*3)+1) for timer1 channel1 */
  NVIC_EnableIRQ(TC7_IRQn);
}

void loop()
{
  // do nothing timer interrupts will handle the blinking;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// INTERRUPT HANDLERS
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void TC7_Handler()
{
  // We need to get the status to clear it and allow the interrupt to fire again
  TC_GetStatus(TC2, 1);
  state = !state;
  digitalWrite(led_pin, state);

  if( interruptCtr++ >= 6 )
    {
     interruptCtr = 1;
     S = !S; // are we flashing S or O
     if( S ) // set time till next interrupt
        TC_SetRC(TC2, 1, 131200); // 131200 / 656000 = .2 seconds
     else
        TC_SetRC(TC2, 1, 656000); // 656000/ 656000 = 1 second
    }
}


Split string into an array of string I have a SIM900 module connected to an Arduino Uno, using an AT command for listing the SMS I get this output, how can i split this based on (,) to store each data in an array?

AT+CMGL="ALL"

+CMGL: 2,"REC READ","+639321576684","Ralph Manzano","16/04/25,21:51:33+32"
Yow!!!

OK

You could try to use strtok. Code from my mind and not tested:

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[])
{
    char string[] = "AT+CMGL=\"ALL\"\n"
    "\n"
    "+CMGL: 2,\"REC READ\",\"+639321576684\",\"Ralph Manzano\",\"16/04/25,21:51:33+32\"\n"
    "Yow!!!\n"
    "\n"
    "OK\n";
    char delimiter[] = ",\n";

    // initialize first part (string, delimiter)
    char* ptr = strtok(string, delimiter);

    while(ptr != NULL) {
        printf("found one part: %s\n", ptr);
        // create next part
        ptr = strtok(NULL, delimiter);
    }

    return 1;
}

Outputs:

found one part: AT+CMGL="ALL"
found one part: +CMGL: 2
found one part: "REC READ"
found one part: "+639321576684"
found one part: "Ralph Manzano"
found one part: "16/04/25
found one part: 21:51:33+32"
found one part: Yow!!!
found one part: OK


What is the cheapest way to add wifi to Arduino? I am trying to find some sort of wifi adapter for Arduino, it needs to be as small as possible (not a shield) and as cheap as possible.

So far I can only seem to find shields that cost about £10+ but I figured that if you can get a replacement wifi adapter for a laptop for next to nothing that I should be able to get a wifi adapter for Arduino much cheaper than this.

It's possible I just don't know what to search for.

Some months have passed since my previous answer and now the ESP8266 based WiFi modules are available.

They get connected to your project serially (3.3V) and are controlled in a modem like way using AT commands.

With a pricing of round about $5 they fit the question better than my previous OpenWrt based answer.

For more information about ESP8266 ask your favorite finding machine or list news with tag ESP8266 at Hackaday.

(Old answer from the pre-ESP8266-days:)

I vote for a small router reflashed with OpenWrt like "TP-Link TL-WR703N".

It is like building an own Yùn with an Arduino of your choice...

The WR703N:

It has Ethernet, 150MBit WiFi, USB and if you want to solder, a serial console and 2 GPIO-Pins which can be turned into I2C.

This sure is not a chip- or stamp-sized solution but often cheaper than the alternatives, more powerfull and extendable.

Search the net with your favourite find'o'bot for "arduino wr703n" and you'll find lots of examples...


Why should I put a 10K resistor with an LDR? I am wondering why should I put a 10K resistor with an LDR.

If I put a "stronger" resistor with another resistor (in this case the LDR), I'd get a lower voltage, and then I'd, too, get a lower value in the analogRead(). I'd like to know in what I'm doing wrong. Can someone help me?

LDRs themselves come in a considerable range of resistances. Search LDR specs and you will see what I mean. For example, from eBay I found one:

  Bright Resistance(10Lux)(KΩ):20-230

  Dark Resistance: 2 MΩ

This particular one, for example, seems to range from around 20k to 2M ohms. A reasonable series resistor would then seem to be somewhere in the middle of that range, otherwise all your readings would be skewed at one end of the scale.

For example, in this case if you used 10k and the LDR had 20 k resistance in very bright light, then the voltage would be 3.33 V

20000 / (20000 + 10000) * 5 = 3.33 V

Then if it got slightly darker and the LDR was 230 k, you would get:

230000 / (230000 + 10000) * 5 = 4.79 V

And if it was really dark you would get:

2000000 / (2000000 + 10000) * 5 = 4.98 V

You can see from those figures that you will never get a reading less than 3.33 V with this particular LDR and a 10k resistor. Thus a higher value resistor would give you a better range of readings.

However this totally depends on what resistance your particular LDR has.


Parsing Integers from Serial data stream I'm trying to send sensor data from my Remote Control to my Bot via Bluetooth.
It's 6 numbers that I would like to have read as integers on the other side.
I'm printing them to Serial on the Remote side with the numbers separated by commas. I've also added a start marker "<" and an end marker ">".

The incoming data from the remote looks like this in the Bots Serial Monitor:

<1,1,1,1,1,512>
<1,1,1,1,1,512>
<1,1,1,1,1,513>
<1,1,1,1,1,512>
<1,1,1,1,1,512>
etc

Before adding in the markers I was trying to use Serial.parseInt() to do this, but I kpet getting out of order numbers (probably from no start marker?).

if (Serial1.available() > 0) {

 trig1 = Serial.parseInt();
 trig2 = Serial.parseInt();
 trig3 = Serial.parseInt();
 trig4 = Serial.parseInt();
 trig5 = Serial.parseInt();
 pot = Serial.parseInt();

if (Serial.read() == '\n') {
}
}

But now that I have the markers I don't know the best way to initialize the code.  Anyone have any ideas on how to parse these 6 numbers into usable integers?

EDIT:  I've wrote a code based on VE7JRO's comments.

uint16_t myArray[6] = {};
int counter = 0;

void setup(){

Serial.begin(9600);

}

void loop(){
  if (Serial.available() > 0) {
  char* pch = strtok(Serial.read,"<>,\r\n");
   }
while(pch != NULL){
  myArray[counter] = atoi(pch);
  pch = strtok(NULL, "<>,\r\n");
  counter += 1;
 }

 trig1 = myArray[0];
 trig2 = myArray[1];
 trig3 = myArray[2];
 trig4 = myArray[3];
 trig5 = myArray[4];
 pot   = myArray[5];

 Serial.print (trig1);
 Serial.print (", ");
 Serial.print (trig2);
 Serial.print (", ");
 Serial.print (trig3);
 Serial.print (", ");
 Serial.print (trig4);
 Serial.print (", ");
 Serial.print (trig5);
 Serial.print (", ");
 Serial.println(pot);
 }

I'm getting this error code: invalid use of non-static member function
for this line:

      char* pch = strtok(Serial.read,"<>,\r\n");

Other than that. I subbed out the test input that  VE7JRO put in and inserted "Serial.read". Not sure if that is the correct way to do this.  Any ideas?

I tried your second sketch.  It kind of worked.  The data that printed to the serial monitor looked like this:

1, 1, 1, 1, 1, 519
518, 1, 1, 1, 1, 519
1, 1, 1, 1, 19, 9
1, 1, 1, 1, 1, 519
1, 1, 1, 1, 1, 519
1, 1, 1, 1, 1, 518
1, 1, 519, 518, 1, 518
1, 1, 519, 518, 1, 518
1, 1, 518, 518, 1, 518
1, 1, 1, 1, 1, 8
1, 1, 1, 1, 1, 519
1, 1, 518, 1, 1, 1
8, 1, 518, 1, 1, 1
1, 1, 519, 1, 1, 1
1, 1, 1, 519, 1, 1
1, 1, 1, 519, 1, 1
1, 1, 1, 1, 1, 519
1, 1, 1, 1, 1, 518
1, 1, 1, 1, 519, 8
1, 1, 1, 1, 1, 518
1, 1, 1, 1, 1, 519
1, 1, 1, 1, 1, 518
1, 1, 1, 1, 1, 518
1, 1, 1, 1, 1, 520

it should have all been   1, 1, 1, 1, 1, 518(ish).

Here is a sketch that uses strtok() and atoi() to parse the data and store the results in an integer array.

char testInput[] = "<1,2,3,4,5,512>\r\n";
uint16_t myArray[6] = {};

void setup(){

  Serial.begin(9600);

  int counter = 0;
  char* pch = strtok(testInput,"<>,\r\n");

  while(pch != NULL){
    myArray[counter] = atoi(pch);
    pch = strtok(NULL, "<>,\r\n");
    counter += 1;
  }

  // Print out the contents of the integer array.
  for(int i = 0; i < counter; i++){
    Serial.println(myArray[i]);
  }

}

void loop(){}

EDIT

Based on your comments, I have another sketch for you to try.

// Sample input: <1,2,3,4,5,512>
char testInput[40];
uint16_t myArray[6] = {};
int counter = 0;

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

void loop(){

  if(Serial.available() > 0){

    Serial.readBytesUntil('\n', testInput, 40);

    char* pch = strtok(testInput,"<>,\r\n");

    while(pch != NULL){
      myArray[counter] = atoi(pch);
      pch = strtok(NULL, "<>,\r\n");
      counter += 1;
    }

    Serial.print (myArray[0]);
    Serial.print (", ");
    Serial.print (myArray[1]);
    Serial.print (", ");
    Serial.print (myArray[2]);
    Serial.print (", ");
    Serial.print (myArray[3]);
    Serial.print (", ");
    Serial.print (myArray[4]);
    Serial.print (", ");
    Serial.println(myArray[5]);

    counter = 0;
  }
}


Arduino IDE doesn't release COM port after programming I have an arduino mega 2560 and I'm trying to program it using Arduino IDE 1.8.1. The problem is that I also need to keep open another program that will communicate with the Arduino using the COM port. I usually have to make very small changes to the code with the IDE and then check the results in the program.

However, when the IDE has finished uploading the program it will not release the COM port, and the program I'm using will give me an error message saying "access denied". This is a problem because I want to keep both programs open at the same time.

In fact I could just: make my correction to the code, close the IDE when it has finished, open the program I need, check whether the correction I made was right, otherwise close it again and open the IDE again, but that would take an insane amount of time and it would be quite annoying.

Is there a way to force the Arduino IDE to release the COM port so that other programs could communicate with the Aduino?

To force the Arduino IDE to disconnect from the COM port, simply go into the Tools menu, go to Ports and select another COM port.

Alternatively, you can open and then close the serial port monitor (Ctrl+Shift+M then Alt+F4).


Portal gun sound effects and lights I'm building a portal gun from the game Portal and I'm struggling with the wiring for the lights and sound. I've the lights working using the first image from Instructables and adding more LEDs shouldn't be a problem. I'm trying to add the SD card and speaker so when you flick the switch, as well as the lights changing, the firing sound is played. Image 2. everything is wired quite nicely the only change is I'm using pin 10 not 4 on the memory card.

This is my code and it all compiles fine and seems to make sense to me but I'm new to programming.

The lights work but none of the sounds play. I've formatted the SD card and also made sure the .wav files are the right format: mono 8 bit 16000 Hz. I can't work out what's wrong and why I can't get it to play the sounds.

I also have an Adafruit amp just in case it isn't loud enough but not a clue how to wire it in.

#include <pcmRF.h>
#include <TMRpcm.h>
#include <SD.h>                       // need to include the SD library
#define SD_ChipSelectPin 10            // using digital pin 10 on arduino uno 328, can use other pins
#include <SPI.h>

void setup()
{
  // put your setup code here, to run once:
  TMRpcm tmrpcm;
  tmrpcm.speakerPin = 9;          //5,6,11 or 46 on Mega, 9 on Uno, Nano, etc

  Serial.begin(9600);
  if (!SD.begin(SD_ChipSelectPin))
  {
    Serial.println("SD fail");
    return;
  }
  tmrpcm.setVolume(6);
  tmrpcm.play("1.wav");
  tmrpcm.play("2.wav");

  //set the switch input, pin 8, as an
  pinMode(8, INPUT);

  //set both the LED pins, pin 5 and 6 as OUTPUTs
  pinMode (5, OUTPUT);
  pinMode (6, OUTPUT);
}

void loop()
{
  TMRpcm tmrpcm;
  int switchValue = digitalRead(8);
  if (switchValue == 1)
  {
    digitalWrite(5, HIGH);
    digitalWrite(6, LOW);
    tmrpcm.setVolume(6);
    tmrpcm.play("4.wav");
  }
  else
  {
    digitalWrite(6, HIGH);
    digitalWrite(5, LOW);
    tmrpcm.setVolume(6);
    tmrpcm.play("5.wav");
  }
}

At a guess I would say your main problem is you are defining your TMRpcm objects within the setup and loop functions, which means that as soon as that function exits the TMRpcm objects will be disposed of. I.e., it won't work. It may start playing a sound in setup(), but it will stop (and maybe even crash completely) before you even have a chance to hear it.

Your TMRpcm object must be declared globally for you to have any hope of making it work.

TMRpcm tmrpcm;

void setup() {
    // ....
    tmrpcm.speakerPin=9;
    tmrpcm.setVolume(6);
    tmrpcm.play("1.wav");
}

etc.

Another thing to note is that TMRpcm plays the sounds asynchronously. That is, it doesn't wait while it plays the sound, so if you play one sound and then another sound the second sound will start before the first one has even begun playing, so you'll never hear the first one.  Instead, if you want to play sounds sequentially, you should for the first sample to finish using something like:

while (tmrpcm.isPlaying()) {
    delay(1);
}

which will stop your sketch running until the last sound has finished.  Including the delay(1) is a good idea since it allows yield() to execute allowing anything that needs it to run (not really a problem on an Uno, but on things like an ESP8266 it's absolutely critical or you get a watchdog timeout).


How to interface an arduino to load sensor with darlington transistor? I have a load sensor for measuring weights , it has for wires labelled E+,E-,S+,S-. I assume S means sensor and E means excitation and the power is sent into E+ and E-.
The output of any load sensor would be the order of typically millivolts if it takes a load (depending on the weight of the load of course) so I guess amplifying it with a darlington would make its output useful for an interface to an arduino.
What would be a generic circuit using a darlington transistor (e.g. a TIP 120) that can make the load sensor output useful for building an interface to an arduino with the minimal number of components? Ans this circuit is to be as simple as possible.
Im trying to build a circuit with the components I have which does include a tip 120 and I have a lot of other common components.

What you have there is (or sounds like) a full wheatstone bridge.

You require either a special amplifier (such as the HX711) or a highly sensitive and accurate differential ADC (such as the MCP3428 - (on  a shield)).


IR sensor does not work well on carpets I have facing a problem since long and cannot solve it. I built Arduino car and place 2 IR sensors shown in image, to check down distance to avoid falling from stairs. One is at back and other at front. On hard surface they work well but on carpet always give wrong reading like no object there which translates unsafe to move and my car stops. How can we solve this problem? I also tried Ultrasonic but it has same problem on carpets or fabric.

I tested this that on carpet it was giving a big distance reading but when I place a white paper, suddenly it was fixed and detected surface.

You may have noticed that this product is no longer available from well known parts distributors like adafruit.com, sparkfun.com or trossenrobotics.com. I would recommend using a Sharp distance sensor designed for the distances you are interested in:

It is about 10 times the price, but produces a variable voltage that you can read with the Arduino's ADC.  Then you can compensate for floor irregularities in your code.

If you care to experiment, I obsurved that the better distance measurement devices angle the emitter and sensor to light up & observe the same spot at the desired operating distance:

You might try this with your current sensor.  However, it does not appear the manufacture left you enough lead length to make such an adjustment.


Buzzer - Does the voltage change with the frequency? So I have this project where the component "buzzer" is implementet. I was wondering if the voltage is changing along the change of frequency given to the buzzer?

Note that the project just says "buzzer" - not any more details.

Project: http://www.instructables.com/id/Arduino-Distance-Detector-with-a-Buzzer-and-LEDs/?ALLSTEPS

No, the frequency of the "buzzer" has no relationship to the voltage.

The duty cycle of the generated tone is proportional to the average voltage though.  Typically the duty cycle is 50% - that is it's turned on for half the time, and turned off the other half the time, to make a square wave.  This means that the average voltage is 50% of the supply voltage.

If you were to low-pass filter the signal (say through an RC filter as many people do to create a crude DAC) you would end up with a voltage around 2.5V.

Changing the frequency doesn't change the duty cycle, it only changes the audio pitch.

The only caveat to that is that if the buzzer draws more current that the IO pin (or the power supply) can source then it may cause the voltage on that IO pin to droop.  That has nothing to do with the frequency though and it would droop just the same at all frequencies.  Basically the IO pin has a small resistance to Vcc through the MOSFET that drives it internally - the higher the current the more voltage is dropped across that resistance, and the lower your resultant output voltage.  Draw too much current and the heat dissipated by that MOSFET's resistance becomes too great and damages the chip.


Coding Arduino's samples/period and cycles/sample configurations for input signal Am I able to code the Arduino so that I can change cycles/sample of an input waveform and a number of samples/period configurations? I would like to modify these parameters in order to be able to store a high-frequency sinusoid but taking into account Arduino's 16MHz clock.
For examples, I have a 40,000kHz sine wave. I would like to sample it at 10 samples/period and having 10 cycles/sample. As a result, I need a (40,000kHz * 10samples/period * 10 cycles/sample = 4MHz clock, which Arduino can supply). Compared to a more standard 128 samples/period and 256 cycles/sample, which would require a 1.3GHz clock.

The limitation is in the ADC which by default takes 104 µs to make a sample. Now you can speed up the ADC, sacrificing accuracy, but even then you can probably practically only reach a sampling time of 13 µs. Plus you would have the issue of where to put these 400,000 samples in the 2KB of RAM you have.

To sample at 400,000 times a second you would need to sample every 2.5 µs, which you can see is way shorter than 13 µs.

Plus, you not only need space to put these 400,000 samples, but it would take time to store them.

For more information see my page about the ADC which has a lot of details about sampling times, frequencies, accuracy, etc.


NRF24L01 +pa +lna modules do not communicate I am building an rc airplane and I want the controller and the plane to communicate using 2 NRF24L01 +pa +lna modules. I am using an Arduino UNO and a Mega. I hooked them up corresponding to this website (https://howtomechatronics.com/tutorials/arduino/arduino-wireless-communication-nrf24l01-tutorial/).
To program I am using this (https://github.com/nRF24/RF24) library from github. Then I run the GettinStarted sketch from the library on both of the Arduinos one of them with the role set to 0 and one of them with the role set to 1.
Serial monitor for the transmitter:

Now sending
failed
Failed, response timed out.

And for the receiver:

*** PRESS 'T' to begin transmitting to the other node

Is there something I need to change or are the modules broken?

That sketch never worked for me also so try this:

Check whether your power supply can give a constant 3.3V and a minimum of 0.5A(500mA)?
Then try these connections:

Then try your code again.
If it fails to work try a simpler library like the NRFLite library and

I actually never got that library and that sketch to work, but when I kept everything the same and used the NRFLite library, everything worked!


Why is setup() executed twice at runtime? Code:

void setup() {
  Serial.begin(9600);
  Serial.println("hello");
}

void loop() {
}

Output:

hello
hello

Why does hello print twice?

It isn't, it's displaying the previous message from when you didn't have the Serial Monitor open yet, plus the new message caused by the Arduino resetting from the Serial Monitor being opened.

If you put a longer message in there you'll probably see the first line get cut off and then the full line.


"stray '/302' in program error" when compiling For some weird reason, the following code doesn't compile. I get a "stray '\302' in program" error around volatile unsigned int encoderPos = 0;, and I have no idea what the issue is. I've been trying to figure this out for over 40min, and nothing works. It doesn't make any sense

#include <U8g2lib.h>
#include <SPI.h>

//Pin definitions:

const int control_PWM = A3; //PWM output for the delay

const int btn_1 = 1; //Button for mode 1
const int btn_2 = 4; //Button for mode 2
const int btn_3 = 5; //Button for mode 3

const int r_A = 2; //Rotary encoder A's data
const int r_B = 3; //Rotary encoder A's data
const int r_SW = 0; //Rotary encoder's button data

const int oled_CLK = 9; //SPI cloack
const int oled_MOSI = 8; //MOSI pin
const int oled_CS = 7; //Chip Select pin
const int oled_DC = 6; //OLED's D/C pin
U8G2_SH1106_128X64_NONAME_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8);

int mode = 1; //1: RGB, 2: HSL, 3: Distance control
int value_selection = 1; //Actual value selectrion
int value1 = 0; //red in mode 1; tint in mode 2
int value2 = 0; ////green in mode 1; saturation in mode 2
int value3 = 0; //blue in mode 1; luminosity in mode 2

volatile unsigned int encoderPos = 0;  // rotary encoder's current position
unsigned int lastReportedPos = 1;   // rotary encoder's previous position
static boolean rotating=false;      // is the encoder activity status

// interrupter variables
boolean A_set = false;
boolean B_set = false;
boolean A_change = false;
boolean B_change= false;
void setup() {

}

void loop() {
}

0302 is 0xc2. Somewhere in your source you have one or more non-breaking spaces (0xa0) encoded in UTF-8 (0xc2 0xa0). Use od or a similar tool to find them, and then replace them with normal spaces. Since you have non-ASCII Latin-1 characters in your source, those characters are encoded as two bytes with the first being 0xc2 or 0xc3. Remove all non-ASCII characters before proceeding.


Which shield to use for GPRS? I'm planning to build a device that would read some sensor data and send it via GPRS, eg. once per day. (Not that original, yeah.) But my problem is choosing a GSM/GPRS shield.

The official shield has a nice interface for doing an HTTP POST/GET. OTOH, the shield seems to be sold out (and would be quite expensive anyway).

There seem to be other shields available, but their code examples tend to look quite hacky: the device waits for an arbitrary moment and then hopes that the server is done. That's IMO both inefficient or unreliable.

My question: which GSM/GPRS shield would you recommend, with these features:

a sane library w/ examples, such as the official onean external antennabonus: a competitive priceanother bonus: hopefully a "real" shield, so no soldering required and a few pins still easily usable for the sensors.

That library should work with pretty much anything that has the M10 module on it.

I only have experience with the SIM900 modules. Found the cheapest one on EBay.

While interfacing with these things can be a challenge at first, you really just need to read the manual for all the AT commands and execute them. I've written a couple of functions that may help:

Note: you may safely replace all instances of DEBUG_PRINT and DEBUG_PRINTLN with Serial.print and Serial.println.

SoftwareSerial SIM900(7, 8);

/*
    Sends AT commands to SIM900 module.

    Parameter   Description
    command     String containing the AT command to send to the module
    timeout     A timeout, in milliseconds, to wait for the response

    Returns a string containing the response. Returns NULL on timeout.

*/
String SIMCommunication::sendCommand(String command, int timeout) {
    SIM900.listen();
    // Clear read buffer before sending new command
    while(SIM900.available()) { SIM900.read(); }

    SIM900.println(command);

    if (responseTimedOut(timeout)) {
        DEBUG_PRINT(F("sendCommand Timed Out: "));DEBUG_PRINTLN(command);
        return NULL;
    }

    String response = "";

    while(SIM900.available()) {
        response.concat((char)SIM900.read());
        delayMicroseconds(500);
    }

    return response;
}

/*
    Waits for a response from SIM900 for <ms> milliseconds

    Returns true if timed out without response. False otherwise.
*/
bool SIMCommunication::responseTimedOut(int ms) {
    SIM900.listen();

    int counter = 0;
    while(!SIM900.available() && counter < ms) {
        counter++;
        delay(1);
    }

    // Timed out, return null
    if (counter >= ms) {
        return true;
    }
    counter = 0;
    return false;
}


Is it ok to declare variables inside timer interrupts? I am building a real time audio application using the Arduino DUE. This application needs big arrays like:

uint16_t sDelayBuffer0[46000];

The Due has only 96kb of RAM available so this array just ate up most ot its memory.
The problem is i need more arrays like this...

So, i was thinking, instead of declaring all of the arrays as global variables, to declare them inside the timer interrupt functions.

The loop() handles stuff like reading the ADCs. The actual effects are coded inside timer iterrupt funciton that are replayed over and over. So the code constantly loops in loop() and the selected timer interrupt function.

But other timer interrupt fucntions use other arrays. So i was thinking to declare every array that a corresponding timer interrupt function wants inside that fucntion.

So all arrays are not declared at the same time (since when we exit the timer interrupt function we were on and head either to loop or another interrupt function, the grabage collector will destroy the array right?)

The problem with this theory, is that this is a real time audio application. So is it wise to constantly declare a big array like this? Since the timer interrupt ficntion will run very very often. Won't i have delay problems iwth the actual sound? Or variable declarations happen extremely fast inside the CPU, even for big arrays?

The problem is i need more arrays like this...

you probably want to take a look at your processing flow to see if you need all of them at the same time. if you do, well, there is no alternative but to get a bigger chip.


Why isn't this EEPROM.get() working? I am trying to save a string/char to EEPROM with EEPROM.put() and then get the value, but it doesn't work and I get a blank value when I do a EEPROM.get().
I remember this is how it worked on arduino nano, but now I am trying with an ESP32 board, do they work different ?
#include <EEPROM.h>

char my_string[8];

void setup() {

  Serial.begin(115200);

// I am writing by this code, then comment it out to try to read from EEPROM
/*
    my_string[0] = 'S';
    my_string[1] = 'N';
    my_string[2] = '-';
    my_string[3] = 'A';
    my_string[4] = 'B';
    my_string[5] = 'C';
    my_string[6] = 'D';

  EEPROM.put(0, my_string);
*/

  EEPROM.get(0, my_string);

  Serial.println("data is: ");
  Serial.println((char*)my_string);
}

void loop() { }

EEPROM can't store string. It stores numbers.  put() takes a type and stores that type as numbers.
The char[] isn't a string - it's a number. More specifically it's a memory address for where the string data is stored.
All you're doing is storing that memory address, not the data itself.
Instead you need to iterate over your string. You should also store the length of the string if it's going to be variable.
For example:

void storeString(const char *str) {
    EEPROM.write(0, strlen(str)); // Store the string length
    for (int i = 0; i < strlen(str); i++) {
        EEPROM.write(i + 1, str[i]);
    }
}

void getString(char *str) {
    int len = EEPROM.read(0);
    for (int i = 0; i < len; i++) {
        str[i] = EEPROM.read(i + 1);
    }
}


Thunderstorm triggering button press? So I recently built a small IFTT powered button using an ESP8266 for my boys to play with. Tonight during an intense Thunderstorm, I kept getting alerts that it had been pressed. They weren't in the basement at all. Then I realized, giant crack of lightening === SMS message.

Now I don't think this has anything to do with the button mechanism itself, but the shoddy way I hooked it up, and stuffed it into an enclosure. I'm just curious - is this possible? Could some sort of static electricity from a few nearby lightening strikes do something that would send a 'high' signal to the GPIO Pin on my Espee? I had to use a pull up resistor, and I feel like there's probably a few bare-ish wires in there, but nothing touching, or even close enough to 'arc'. Am I crazy?

You aren't crazy. I had a similar thing happen when an external hot-water system turned on at midnight (someone was having a shower) and one of my systems detected input unexpectedly (and rang a bell right next to my ear while I was trying to sleep).

My solution was to have something like this:

The diodes clamp the input to acceptable ranges, and R1 is a current limit for the diodes. R2 and C1 are a filter that slows down the incoming signal (and thus eliminates sudden spikes). R3 is a pull-up resistor. In my case I had active-low. If you have active-high you could use a pull-down resistor instead.

Also see https://arduino.stackexchange.com/a/13128/10794

Further reference material:

10 Ways to Destroy An Arduino
Protection
Microcontroller Input Protection Techniques


GSM module not working after power off I am making a project on gsm module(sim 900a unofficial shield), when I will send a SMS led will turn ON. after uploading code, module works fine, and led turned ON after sending message. But when I power off sim900a and Arduino, and power on back, it's not working, led not power up after sending message, when I reupload sketches it is working fine, means every time after power off I need to upload code again, I am learning c and don't have much knowledge? Is my code right? Or some other fault?

#include <SoftwareSerial.h> //software serial library for serial communication b/w arduino & GSM

    SoftwareSerial mySerial(8, 9);//connect Tx pin of GSM to pin 8 of arduino && Rx pin of GSM to pin no 9 of arduino

    int led = 7;
    String message;

    void setup()
    {
      mySerial.begin(9600);   // Setting the baud rate of GSM Module
      Serial.begin(9600);    // Setting the baud rate of Serial Monitor (Arduino)
      delay(100);

      mySerial.println("AT+CNMI=2,2,0,0,0"); // AT Command to receive a live SMS
      delay(1000);
      pinMode(led,OUTPUT);
      digitalWrite(led,LOW);
    }

    void loop()
    {
      if (mySerial.available()>0){
      message = mySerial.readString();
      }

      if(message.indexOf("ON") > -1){
          Serial.println("LED ON");
         digitalWrite(led,HIGH);
         }
        else if(message.indexOf("OFF") > -1){

          Serial.println("LED OFF");
          digitalWrite(led,LOW);

      }

      delay(10);
    }

Circuit diagram

The GSM takes time to start up.  Your program needs to be far more complex than the simple "Throw commands at it and hope" method you are using.

First you need to query the modem repeatedly until it responds.  This is usually done with the AT command.  A sequence would look like:

Send: AT
(Wait for OK response or timeout)
Send: AT
(Wait for OK response or timeout)
Send: AT
(Wait for OK response or timeout)
Send: AT
(Wait for OK response or timeout)
Recv: OK

Once the modem has booted and is ready to receive commands you can start sending commands.  You shouldn't just "print and delay" though like you are at the moment. Instead you should send the command and then examine the response to see if the command worked ("OK") or failed ("ERR").


Cat motion detector that can tell the difference from humans I'm trying to build a cat motion detector but, to avoid getting false alarms when a person walks by, I was thinking of using RFID. i.e. the cat has a collar and the detector senses the collar when they get within a couple of feet and makes a noise.

The problem there seems to be with RFID is that the range is so short - e.g. 4".

Anyone have a better solution?

Place an additional motion sensor such that it can only detect motion from things significantly taller than cats, and use that as an inhibitor/classifier of the cat motion signal.


Webserver on Arduino How can I run a webserver in a Arduino Uno? I want to use my Arduino to monitor things in my home such as temperature. I want to be able to access this data through the internet.

You'll need something like the Ethernet Shield to connect your Arduino Uno to a LAN.

As for webserver functionality, the Webserver Example sketch does the bulk of what you need.

For the "access this data through the internet" part, assuming you want access beyond your LAN; you'll need to perform Port Forwarding on your local router (i.e. allow the "Internet" to see your Arduino).

If you need wifi, then personally I prefer the CC3300 to the Arduino Wifi shield.


How can higher current devices (motors, solenoids, lights, etc.) be controlled by an Arduino? I'm looking for a broadly applicable solution, one that can be adapted to a variety of projects.

I'm currently working on several projects that each require controlling devices ranging from 800mA to 2A from an Arduino Uno. One controls stepper motors, one controls 12vdc solenoid actuators, and one controls 12vdc pneumatic valves.

For example:

The Arduino monitors a button, and each time the button is pressed it triggers the solenoid actuator. Because the Arduino is unable to source the current required by the solenoid, a seperate power supply is required with the Arduino controlling a switch (relay, transistor, etc.) that allows the higher current to pass. For the stepper motor, the layout is more complex as there would need to be four pins controlling four separate switches (to maintain interoperability of the circuit). The relay controls an air valve and requires 12vdc as well.

I'm trying to figure out how to use a single circuit that can be used in each of these applications (and any future projects) that involve controlling higher current devices than the Arduino pins can handle.

Prototyping speed, standardized components, and low cost are the driving factors. Switching speed, useful life, and noise are also important.

Is there a breakout board, circuit, or component that can be connected to an Arduino pin and used to control a high current device? Ideally with a software controlled potentiometer so that the resistance for different projects could be set in the sketch itself.

To drive such high currents, you may have to cascade several transistors (you can also use a Darlington transistor). There are arrays of Darlingtons mounted in a chip (e.g. the ULN2803A has 8 darlington transistors, but is limited to 500mA).

You probably will have to deal with higher power transistors; as an example I have found STMicroelectronics TIP110 which can support switching a 2A current (4A peak), but it would probably need a heatsink to dissipate heat.

Note that I wonder if your steppers really need 2A current (are they that big?). For steppers, you can generally find IC that can drive them easily, e.g. the L293D but this one can drive "only" 600mA).

As a conclusion, I am afraid you will not find a "one size fits all" solution, as all your devices are different and should be driven by the appropriate circuit.

Edit:

Since oversizing is not an issue in your prototyping case, then you could go with a MOSFET instead of usual bipolar transistors. A MOSFET will be able to drive higher currents and voltages than standard transistors.

The downside is you can use it as a switch only (like e.g. a relay) and thus can't really drive the exact power for your devices. I guess that does not matter for a Stepper motor, or a Solenoid, but that may be important for driving lights for instance.

However, the good point is that you can still use PWM for that as the MOSFET switching speed is good enough for such purposes.

Regarding price, there are many diferent kinds of MOSFET out there, but I guess you can find one that fits yours needs (12V, 2A) for less than $1.

I advise you to take a look at this great article about this topic.


MAX7219 with 8digit 7seg array I have a concern about the library port handling. I have used direct port direction manipulation successfully in previous projects but there seems to be a problem here.

// This code mostly taken from the example
#include "LedControl.h"

LedControl lc=LedControl(11,13,10,1);
//LedControl lc=LedControl(12,11,10,1); // original
// pin 12 is connected to the DIN pin (now MOSI 11)
// pin 11 is connected to the CLK pin (now SCK 13)
// pin 10 is connected to the CS pin  (now SS 10)
// 1 as we are only using 1 MAX7219

// I am actually using all arduino pins except 12 for my project
#define PD_MSK  B11111100 // Data pins PD2..7 (pins2..7)
#define PB_MSK  B00000011 // Data pins PB0,1 (pins8,9)
#define PC_MSK  B00001111 // Data pins PC0..3 (pins 14..17)

void setup()
{
// set pins 2..9 as inputs
  DDRD = DDRD & !PD_MSK; // this works OK
  DDRB = DDRB & !PB_MSK; // configure ports D,B inputs *** doesnt work with this
 // pinMode(8, INPUT); //*** does work with this
  //pinMode(9, INPUT); //*** does work with this

  DDRC = DDRC | PC_MSK; // configure PortC0..3 as outputs
  PORTC |= 0x0F; // set PortC0..3 high (default)

  // the zero refers to the MAX7219 number, it is zero for 1 chip
  lc.shutdown(0,false);// turn off power saving, enables display
  lc.setIntensity(0,8);// sets brightness (0~15 possible values)
  lc.clearDisplay(0);// clear screen

}
void loop()
{
  //numbers 7 to 0
  for (int a=0; a<8; a++)
  {
    lc.setDigit(0,a,a,false);
  }

  delay(1000);

  //display number 8 on all segments
  for (int a=0; a<8; a++)
  {
    lc.setDigit(0,a,8,false);
  }
  delay(1000);

  // numbers 7 to 0 reverse order
  for (int a=8; a>=0; a--)
  {
    lc.setDigit(0,a,a,false);
    //delay(100);
  }
  delay(1000);

}

The direct port direction setting does not seem to allow the library to work while the pinMode commands doing the same job do. I note that the library uses software SPI but I would like to use hardware if possible. I have certainly used hardware SPI with frequent port direction changes on the remaining pins for other projects.
Any insight as to why this problem occurs?

Thanks.

As always I recommend the old RTFM (read the f***ing manual) of the LedControl.h library.
In the FAQ its clearly stated:

  Why don't you use the hardware SPI-Bus of the Arduino?

  When I wrote the first version of the library I didn't knew much about
  the Arduino or AVR processors in general and I knew nothing about
  writing code for the hardware SPI-bus on an ATMega. But I knew how the
  SPI protocol works and how I could make this work using simple
  digitalWrite() commands. I turned out the library code is fast enough
  for common use cases, so there is no need for doing Hi-Speed
  communications.

  Other strong points in favour of the (admittedly trivial) code design
  are - Use any three free IO-Pins of your board for the hardware -
  Simple to debug. Much easier than managing 3 differnt SPI devices
  connected to the same hardware bus - Library is easily portable to
  other platforms, since it uses only two very basic functions from the
  Arduino language

So with this library you clearly have never used hardware SPI (although you could use the pins, but only via softwareSPI)


How to send a number as a byte? I want to send a number between 0 and 120 as a byte over Serial port. I'm working on a project that involves sending ultrasonic sensor readings over Bluetooth to an Android. I would like to send the entire reading as a byte and I think this can be done because an signed byte ranges from -128 to 127. However, the byte received in my Android app doesn't show the correct sensor reading. Here's the relevant code snippet:
  while (true){
      //ultrasonic sensor sends out signal
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);
      pinMode(echoPin, INPUT);
      duration = pulseIn(echoPin, HIGH);

      cm = (duration / 2) / 29.1;   // Divide by 29.1 or multiply by 0.0343
      inches = (duration / 2) / 74; // Divide by 74 or multiply by 0.0135
      // max range is 156 inches, but our app will only display up to 100 inches
      inches = min(127, inches);
      Serial.print(inches, BIN);
      delay(50);

In my Android app written in Java I read the value like this:
b = (byte) inputStream.read();

For example, if inches is 100 and I send that over Serial port, how can I expect to get the same reading in my Android app?

The problem is the BIN in your print statement.  Everything is ALWAYS binary.  The BIN means to break that binary up into ascii digits 0 and 1.  So if you send
Serial.print(21, BIN);
then the print function takes 21 as a binary number, 00010101 and then sends those binary digits as ascii.  So what goes out on the wire is 8 separate bytes, it goes 48, 48, 48, 49, 48, 49, 48, 49 as 48 and 49 are the ascii codes for 0 and 1.
What you want to do is just to send the raw byte.  So use Serial.write instead.  The print functions convert things to ascii representations but the write function just sends the raw bytes out.  So if you write:
Serial.write(inches);

Assuming that inches is a byte type variable then it just sends the raw byte out.


Arduino Keyboard starts lower case (but it shouldn't) So I flashed the KeyboardMessage example to my Arduino SS Micro ATmega32U4.
When I open an editor and push the button, I would assume the output to be

Zou pressed the button XX times.

(The "Z" is because I use a German keyboard)
In some editors (Arduino IDE, LibreOffice) this assumption is fulfilled.
However, in several other editors (Linux Shell, gedit), most of the times the output is

zou pressed the button 1 times.

starting with a lower case "z".
I use a Debian Testing computer. The only thing I changed in the sketch was the buttonPin as my button is soldered to pin 11.
I noticed, that this problem doesn't occur when the button is pressed a second time shortly after the first message. To investigate this, I coded a little sketch to find the threshold.
This is what I got (in gedit)

As line 8 shows, even after 70 millis, the upper case start is not reliable, however, somewhere after 250 millis, the error occurs every time.
My questions are:

What could be the cause for this issue?
How can it be fixed (if necessary, I also welcome a workaround)?

Please tell me if you need any additional information.
[edit]
After slightly altering the script, I noticed, that the problem doesn't only occur on the start of a line, but also (although less often) later in the output. See lines 24, 31 and 52 for example

I am not sure I have the answer to your problem, just a collection of
observations that hopefully steer you in the right direction.
According to your nopaste link, when you send "ON", the first four
keyboard events received by xev are: press(Shift_L), press(O),
release(Shift_L), release(o). One may notice that there is no point in
releasing the Shift key if it's going to be pressed again right away,
but let's assume that simply holding Shift is not such a useful
optimization. The detail that strikes me is that the last two events
look backwards: you usually release the letter before releasing Shift.
As a result of releasing Shift first, the release event for the O key
reports lowercase "o" as a keysym. I tried this backward way of
releasing the keys on a real keyboard, but both gnome-terminal and gedit
correctly registered the uppercase letters.
Another detail apparent in the xev dump is that the two key presses
(Shit and O) happen at the exact same time. Ditto for the corresponding
key releases. Looking at the source of the Keyboard library, it appears
that both key presses are sent to the PC as a single "key report". Same
for the key releases. This is contrary to what a real keyboard does:
actuations on the Shift keys are reported immediately, irrespective of
whether other keys are actuated.
You may try to modify the Keyboard library so that the actuations on
Shift are sent in their own reports. Maybe something like this
(warning: completely untested):
diff --git a/src/Keyboard.cpp b/src/Keyboard.cpp
index 4a948f6..9fbf7b6 100644
--- a/src/Keyboard.cpp
+++ b/src/Keyboard.cpp
@@ -239,6 +239,7 @@ size_t Keyboard_::press(uint8_t k)
        }
        if (k & 0x80) {                     // it's a capital letter or other character reached with shift
            _keyReport.modifiers |= 0x02;   // the left shift modifier
+           sendReport(&_keyReport);        // send the shift key by itself
            k &= 0x7F;
        }
    }
@@ -270,6 +271,7 @@ size_t Keyboard_::press(uint8_t k)
 size_t Keyboard_::release(uint8_t k)
 {
    uint8_t i;
+   bool has_shift = false;
    if (k >= 136) {         // it's a non-printing key (not a modifier)
        k = k - 136;
    } else if (k >= 128) {  // it's a modifier key
@@ -281,7 +283,7 @@ size_t Keyboard_::release(uint8_t k)
            return 0;
        }
        if (k & 0x80) {                         // it's a capital letter or other character reached with shift
-           _keyReport.modifiers &= ~(0x02);    // the left shift modifier
+           has_shift = true;
            k &= 0x7F;
        }
    }
@@ -295,6 +297,10 @@ size_t Keyboard_::release(uint8_t k)
    }

    sendReport(&_keyReport);
+   if (has_shift) {
+       _keyReport.modifiers &= ~(0x02);    // the left shift modifier
+       sendReport(&_keyReport);            // release shift after releasing the letter
+   }
    return 1;
 }

Alternatively, as suggested by @jstola in a comment, you may try to
press the Shift key by itself. Maybe you don't need to care about the
key release, or about any character but the first one (as it is the only
one that seems to cause problems). A minimal workaround to try would be:
Keyboard.press(KEY_LEFT_SHIFT);
Keyboard.println("ON");


Sending Variable to IFTTT via ESP32 using Asynchronous Web Server I have been trying to send three variables to IFTTT from my ESP32 using Asynchronous Web Server. However, I couldn't set the "URL" that was supposed to be the response that will trigger my IFTTT. Here's is my code:

server.on("/ifttt", HTTP_GET, [](AsyncWebServerRequest *request){

String jsonObject = "{\"value1\":\"" + Global_T + "\"" + ",\"value2\":\"" + Global_H  + "\"" + ",\"value3\":\"" + Global_K +  "\"}";

AsyncWebServerResponse *response = request->beginResponse(200, "application/json", jsonObject);

response ->addHeader("Host", server_ifttt);
request ->send(response);
});

It shall get triggered every fixed interval that I have set, and enter here to send it to IFTTT, but this is how it looks like. I not sure where should I add in the "URL" so that the response could be directed to IFTTT.

As already said in the comments you need client code - Here are ready to use blocks for your scenario - NEVER use String class if you want to have a stable running IoT device, so define global char arrays (compiled to flash) and keep heap fragmentation at a minimum, The code is commented to get you started, change to your needs:

/* Your constants */
#define READ_THIS_PIN 4
const char MakerIFTTT_Key[] = "r8X-blahblahYourKeyGoesHere";
const char MakerIFTTT_Event[] = "stack_exchange_example";

/* Define global char arrays to get rid of string class */
    char numBuf[20];       // We "just know" this is big enough for (un)signed longs
    char postRequest[256];    // Hand-calculated to be big enough (size to your needs)
/* Helper functions for constructing the POST data
    append a string or int to a buffer, return the resulting end of string */

char *appendStr(char *tempChr, char *s) {
    while ((*tempChr++ = *s++))
        ;
    return tempChr-1;
}

char *appendUl(char *tempChr, unsigned long u) {
    return appendStr(tempChr, ultoa(u, numBuf, 10));
}
/*
 This is called once per iteration to read the pin
 and send a POST to trigger the IFTTT/Maker event
*/

void updateEvent() {
    WiFiClient client;

    /* Connect to the Maker event server */
    client.connect("maker.ifttt.com", 80);

    /* Construct the POST request */

    postRequest[0] = {'\0'}; /* Reset char array */
    char *p = postRequest;
    p = appendStr(p, "POST /trigger/");
    p = appendStr(p, "MakerIFTTT_Event");
    p = appendStr(p, "/with/key/");
    p = appendStr(p, "MakerIFTTT_Key");
    p = appendStr(p, " HTTP/1.1\r\n");
    p = appendStr(p, "Host: maker.ifttt.com\r\n");
    p = appendStr(p, "Content-Type: application/json\r\n");
    p = appendStr(p, "Content-Length: ");

    /* We need to remember where the content length will go, which is: */
    char *contentLengthHere = p;

    /* It's always two digits, so reserve space for them (the NN) */
    p = appendStr(p, "NN\r\n");

    /* End of headers */
    p = appendStr(p, "\r\n");

    /* Construct the JSON; remember where we started so we will know len */
    char *jsonStart = p;

    // This example reports a pin, uptime, and "hello stack" change to your need */
    p = appendStr(p, "{\"value1\":\"");
    p = appendUl(p, 12);    //analogRead(READ_THIS_PIN));
    p = appendStr(p, "\",\"value2\":\"");
    p = appendUl(p, millis());
    p = appendStr(p, "\",\"value3\":\"");
    p = appendStr(p, "hello, stack!");
    p = appendStr(p, "\"}");

    /* Go back and fill in the JSON length
       we just know this is at most 2 digits (and need to fill in both) */
    uint8_t i = strlen(jsonStart);
    contentLengthHere[0] = '0' + (i/10);
    contentLengthHere[1] = '0' + (i%10);

    // finally we are ready to send the POST to the server!
    client.print(postRequest);
    client.stop();
}


How to capture the compilaton output to a text file in Windows? I am trying to capture the verbose output of the compilation to get it into a text file. I am using the IDE 1.8.12 running on Windows 10. I have tried looking for a right mouse button context menu, CTRL-C doesn't work, and finally in desperation, the CMD.exe trick of hitting the Enter key after selecting text.
I also went to the build folder in appdata/local/temp/arduino_build_nnnnn but there's nothing like that there.
There is a topic already about this but it refers to the Linux IDE which can be launched from the command line. It turns out that it's somewhat the same on Windows.

The post Capturing avrdude command in IDE gave me the clue. Under Windows the file
C:\Program Files (x86)\Arduino\arduino_debug.exe
can have its output redirected to files same as a shell command.
In the CMD.exe DOS box, I executed:
C:\Program Files (x86)\Arduino>arduino_debug.exe >\temp\logfile.txt 2>\temp\errfile.txt
and the regular log stuff went to logfile and the errors and warnings went to errfile.
There's enough material in those two files to hurt yourself.


Can't get ESP8266 working I have received an ESP8266 (ESP-07) Wi-Fi module from DealExtreme (Link: http://bit.ly/2dFJdxE).
It is a 4-pin module with the following pins: RX, TX, VCC and GND.
The module has a switch so you can switch between the following modes: Program & UART. The module also has a RESET-button.
Here's a picture of my module:

I've connected the module to my Arduino Uno like this:
RX > RX,
TX > TX(TX>RX & RX > TX, like mentioned in manuals, results in no connection),
VCC > 3.3v (not using any level shifters because the module has on board level shifters),
GND > GND.

I found a lot of manuals to test the module, but apparantly I can't get my module working. I am using Windows with the Arduino IDE.
The boards mentioned on the manuals/tutorials also seem to differ from my module because most of the manuals are talking about a board that has 8-pins (with an extra GPO0, GPO2 CH_PD and RST pin).
I've tried to upload the BareMinimum sketch to the module, which only finishes uploading if I disconnect and reconnect the 3.3v input that's feeded to the ESP-board when the Arduino IDE says "Uploading...... " while the ESP-board is in Program-mode.
I have installed the ESP8266 library within the Arduino IDE and the Generic ESP8266 Module is selected.
Then when I open the serial monitor in the Arduino IDE, to test the AT commands (on different BAUD values), it does not respond (neither in Program-, nor in UART-mode).
Strange thing is when I keep the serial monitor on at 74880 BAUD (and UART-mode on the module) and I push the RESET button on the module, it gives the following message:

ets Jan  8 2013,rst cause:2, boot mode:(3,7)
ets_main.c

I've tried several things.  But none of them seem to work; like trying to flash new firmware (for example 'v0.9.5.2 AT Firmware.bin' and 'esp8266-2016-05-03-v1.8.bin') with esptool.py with the following command:

esptool.py -b 115200 -p COM3 write_flash 0 FIRMWARE.bin

It says that the writing is finished and no errors appear after running the esptool. This is what is printed + command that is used:

esptool.py -p com3 -b 115200 write_flash 0 firmware.bin
esptool.py v1.2-dev
Connecting...
Running Cesanta flasher stub...
Flash params set to 0x0000
Writing 520192 @ 0x0... 520192 (100 %)
Wrote 520192 bytes at 0x0 in 44.2 seconds (94.1 kbit/s)...
Leaving...

A strange thing is when I open the serial monitor in the Arduino IDE after that moment (without resetting the module/unplug from 3.3v or change to UART mode), it keeps printing the following at 115200 BAUD:

Fatal exception (28):
epc1=0x4000228b, epc2=0x00000000, epc3=0x00000000, excvaddr=0x000000b5, depc=0x00000000

I even tried it with the erase_flash before and 0x00000 instead of 0. Also tried to run the command with a variety of flash_sizes (with the command --flash_size=Xm).
Esptool looks like the only tool where I can flash new binaries successfully, tried some others that where on some manuals but without success.
When I run esptool.py -p flash_id

I get the following response:

Connecting...
Manufacturer: e0
Device: 4014

Who knows how to fix this problem so I can send AT commands to the module through the serial monitor in the Arduino IDE.
Thanks in regards (this is my first post so if some things are unclear, please let me know)
Edit: Note that I have to disconnect and reconnect the 3.3v to the module EVERY time to successfully run a command (like write_flash, flash_id et cetera). Also tried connecting it to 5v and using an external power supply next to the USB.

Personally I think using an ESP as a interface for an Arduino is backwards and the Arduino ought to act as the interface to your devices for the much more powerful ESP.

I think you had a board that was configured to work as a interface between serial and Wifi, not as a normal board.  I'm pretty sure that you have now shagged it totally by trying to write programs to it.  However you might be able to recover it if you can find the original program and upload that to it.  You don't need the ability to program and ESP-8266 in the IDE to use this board, you can not upload sketches to it, you can't access the GPIOs.

I think you should just be able to slide the switch to "program" power the board up and type AT commands via a terminal emulator to set the board up and then power down, slide the switch back to UART and away it goes.  As to the Tx and Rx pins, that depends on weather its saying "this is the Rx pin" or "this is the Rx connection", you'll get it right second time :)

If you want a ESP8266 try AliExpress they cost between £1 and £2 and I've never had any problems, probably because they were made in China.


How can I make the Serial Monitor work with the Serial Commands library? I am using the library SerialCommands and I am just trying to print the first text message in the Serial Monitor. But this code does not work for some reason.

The expected result is that the Serial monitor prints a message ("Hello world !!") when I write "hello" and press "enter" as input. Is there something wrong or is this not working like I was expecting? Is there another way to check if these commands work? Is there anythin that I am missing?

#include <SerialCommands.h>

char serial_command_buffer_[32];
SerialCommands serial_commands_(&Serial, serial_command_buffer_, sizeof(serial_command_buffer_), "\r\n", ",");

void cmd_hello(SerialCommands* sender) {
  sender->GetSerial()->println("Hello world !!");
}

SerialCommand cmd_hello_("hello", cmd_hello);

void cmd_unrecognized(SerialCommands* sender, const char* cmd) {
  sender->GetSerial()->print("ERROR: Unrecognized command [");
  sender->GetSerial()->print(cmd);
  sender->GetSerial()->println("]");
}

void setup() {
  Serial.begin(9600); // Serial comm begin at 9600bps
  serial_commands_.AddCommand(&cmd_hello_);
  serial_commands_.SetDefaultHandler(&cmd_unrecognized);
  Serial.println("Ready");
}

void loop() {
  serial_commands_.ReadSerial();
}

You defined, that every command will end with \r\n. So you need to choose "Both NL & CR" as line ending in the Serial monitor, so that it appends the line ending to your command. If you don't send the correct line ending, the library will think, that the command hasn't finished yet, and thus will do nothing, until it receives the correct line ending.