Remembering a colour Hey guys I have a led grid. it's 8 sides that are addressable with the bytes '1' through '8'. (a Kinect is sending these bytes through processing)  I have also creates three buttons in processing that change the colour of the leds. ('R','G','B').

I'm stuck in the code, my code now when receiving the bytes: 'R', 'G' or 'B' changes all leds to that colour. instead of remembering the colour and only lighting up the sides determined by the '1', '2', '3', '4', '5', '6', '7', '8' values.

I need it to remember the chosen R,G,B colour until another colour is chosen and only  use the bytes '1', '2', '3', '4', '5', '6', '7', '8' to select what side of the grid to light up.

Here is my code so far:

#include <FastLED.h>

#define LED_PIN     6
#define NUM_LEDS    360

CRGB leds[NUM_LEDS];
CRGB saved_color;

void setup()
{
  FastLED.addLeds<WS2812, LED_PIN, GRB>(leds, NUM_LEDS);
  FastLED.setBrightness(50);

  Serial.begin(9600);

  FastLED.clear();
  FastLED.show();

}

void loop()
{

  if (Serial.available() > 1)
  {
    int incomingByte = Serial.read();

    if (incomingByte > '0' && incomingByte < '9')
    {
      FastLED.clear();
    }

    if (incomingByte == 'R') {
      saved_color = CRGB(255, 0, 0);
    }
    else if (incomingByte == 'G') {
      saved_color = CRGB(0, 255, 0);
    }
    else if (incomingByte == 'B') {
      saved_color = CRGB(0, 0, 255);

    }

    if (incomingByte == '1')
      for (int i = 0; i <= 44; i++) {
        leds[i] = saved_color;
      }

    else if (incomingByte == '2')
      for (int i = 44; i <= 89; i++) {
        leds[i] = saved_color;
      }
    else if (incomingByte == '3')
      for (int i = 90; i <= 134; i++) {
        leds[i] = saved_color;
      }

    else if (incomingByte == '4')
      for (int i = 135; i <= 179; i++) {
        leds[i] = saved_color;
      }
    else if (incomingByte == '5')
      for (int i = 180; i <= 224; i++) {
        leds[i] = saved_color;
      }
    else if (incomingByte == '6')
      for (int i = 225; i <= 269; i++) {
        leds[i] = saved_color;
      }
    else if (incomingByte == '7')
      for (int i = 270; i <= 314; i++) {
        leds[i] = saved_color;
      }
    else if (incomingByte == '8')
      for (int i = 315; i <= 359; i++) {
        leds[i] = saved_color;

      }

    FastLED.show();
  }
}

I'll describe the project a bit more to elaborate. It's a lamp (octagon shape) with 45 leds on the 8 sides. each side is triggered by movement and  sends a byte ('1', '2', '3', '4', '5', '6', '7', '8') to turn on one side of the lamp.

I want to be able to select the colour before sending the bytes. so I need arduino to remember the 'R', 'G', 'B' bytes and only change when I send the other byte.

The array CRGB leds[NUM_LEDS] only holds the current state of the LEDs. It is used to push the data out to the LEDs. If you want the code to save one color to use later, you need an extra variable, that can hold the color.

Add a variable at global scope:

CRGB saved_color;

In the if statements for R, G and B you can set this variable to the corresponding value, for example:

if(incomingByte == 'R'){
    saved_color = CRGB(255,0,0);
}

And in the if statements of 1 to 8 you can use this value, for example:

if (incomingByte == '1'){
    for (int i = 0; i <= 44; i++) {
        leds[i] = saved_color;
    }
}

Note: The above code does not change any LEDs on R, G or B. They just set the color for future operation 1 to 8.


Arduino motor control using digital pins I am new to these Arduino things, and I am currently using an Uno board for my projects.

I don't know how to control the DC motor with the help of digital pins via L293D. But I cannot use the PWM pins of Arduino, since I have already used them for controlling servos and other things, which need higher accuracy.

I tried using the SoftPWM library to control motor, but it is conflicting with other things like ultrasonic sensor. I don't know what the problem is.

Could someone suggest me a solution?

You can implement PWM using digital pins by turning the pin on and off with respect to your duty cycle, because PWM (Pulse Width Modulation) depends upon the duty cycle the % amount during which the pin is HIGH or LOW

Let say pin 13 of arduino is connected to your l293D enable pin

Sample Code:

void setup()
{
  pinMode(13, OUTPUT);
}

void loop()
{
  digitalWrite(13, HIGH);
  delayMicroseconds(100); // Approximately 10% duty cycle @ 1KHz
  digitalWrite(13, LOW);
  delayMicroseconds(1000 - 100);
}

Details are also on Arduino Help

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


MQTT not working on ESP8266 (Nodemcu 0.9) I'm trying to use NodeMCU on my ESP8266 (NodeMCU 0.9) but the board keep crashing and I don't understand why.

I tested the mqtt broker using command line and it works perfectly, so I can suppose that the problem is not the server.

I was following this guide but it doesn't seem to work with me.

Here's the code I wrote:

Previously:

#include <PubSubClient.h>
#define MQTT_SERVER    "1.2.3.4"
#define MQTT_PORT      1883
#define MQTT_USER     "user"
#define MQTT_PSW      "psw"
...
WiFiClient client;

Then:

PubSubClient clientMqtt(MQTT_SERVER, MQTT_PORT, this->client);
//Try mqtt connection
while (!clientMqtt.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (clientMqtt.connect("ESP8266Client", MQTT_USER, MQTT_PSW)) {
      Serial.println("connected");
    } else {
      Serial.print("failed, rc=");
      Serial.print(clientMqtt.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
}

//Try send message
clientMqtt.publish("bin", "test", true);

The code works correcty until clientMqtt.connect("ESP8266Client", MQTT_USER, MQTT_PSW) where at the first/second attempt crashes.

This is the output:

Attempting MQTT connection...
failed, rc=-2 try again in 5 seconds
Attempting MQTT connection...
failed, rc=-2 try again in 5 seconds
Attempting MQTT connection...

Soft WDT reset

ctx: cont
sp: 3ffefa90 end: 3ffefe30 offset: 01b0

>>>stack>>>
3ffefc40:  3ffe897d 40202c5d 3ffefcc4 40202dab
3ffefc50:  3ffe89b7 3ffefcc0 3ffefcc4 40203cdc
3ffefc60:  514d0400 00045454 3ffe89a7 40204cdc
3ffefc70:  3ffe89c0 3ffe89a9 00000000 3ffe88fa
3ffefc80:  3ffeeb70 3ffefdb0 3ffeedd8 3ffe88fa

The Soft WDT reset means that the software watchdog timer reset. Depending on the version of Arduino core to the ESP8266 using delay() can cause this to happen, though current versions handle this better, and using delay() does not cause problems. Make sure you are up-to-date with the Board Manager definitions for ESP8266-based projects.

This page has lots of information on the watchdog timers and especially notes how to use a tool called ESP8266/ESP32 Exception Stack Trace Decoder to determine exactly what line in your code caused the reset to happen.

This page notes that the PubSubClient library can cause problems with the watchdog feeding and gives examples of some alternative yield() and delay() functions you can include and call instead of the built-in versions, which help alleviate resets when using PubSub on ESP8266.

The software watchdog timeout is on the order of 3 seconds, so you can also try reducing your delay(5000) to something shorter, like delay(1000) while debugging, to rule out the 3-second WDT reset due to the delay() call.

Your output also indicates status -2 to the state() function. The documentation for PubSubClient notes that this means "the network connection failed". So one other thing to check is that your device actually connects to the WiFi network and that the MQTT server is listening on the IP address and port you specify.


Finding connectors for push button component What type of connectors would I use for these buttons?:

http://www.adafruit.com/product/1477

They sell wires with the connectors already crimped on, but I only need the connectors.

I found https://www.jameco.com, but i'm not sure which connector would be right, or what to look for specifically.

Go down to your local (decently-stocked) hardware store and ask for "quick connect terminals". From the dimensional drawing you'll need 2mm or 5/64" terminals.


Arduino Uno questions Anyways cutting to the chase I am pretty good at C++ as I have been doing it for over 6 months pretty much 1-2 hours each day and I am looking for cool things to use my knowledge on ,I have heard of the Arduino's but the problem is I don't know my arse from my elbow when it comes to electrical engineering and all that so I have a couple of questions.
1. Do I need to have a background in engineering to use an Arduino.
2. Is there any cheap alternatives to the quite costly starter kit.

I don't know my arse from my elbow when it comes to electrical engineering and all that so I have a couple of questions. 1. Do I need to have a background in engineering to use an Arduino.

The answer to your first question: it depends on what you want to achieve, and how much time you are willing to spend stuck.

A bit of electrical/electronic background can help you a lot.  Basics such as Ohm's, Kirchhoff's.  Semiconductor devices (diodes, transistors, OpAmps).  It's very useful to understand what kinds of test&measurement equipment exists and how it can be used.

You can pursue C++ for 6 months 1-2 hours a day.  You can pursue electrical knowledge in the same way as well.  A solid book like "The Art of Electronics" will help you a lot (doesn't have to be the latest edition).

Then you can pursue more exciting things: sensors (for example).


Supply arduino through Vin pin with a battery is it dangerous for arduino the below circuit because GND pin is common with -12V battery pole?
is it dangerous for lots of 5v circuit to be grounded on -12v battery pole?
in case i don't connect GND arduino pin with -12v , does arduino works?
in case that 1,2 question is dangerous for arduino,does it safe if a connect a diode at P1 mark?

Voltages, being a potential difference are always measured relative to another voltage.  Normally that reference voltage is referred to as ground, though may not always be.

The + and - on the battery refers to the polarity of the battery not the polarity of the voltage.

For instance, relative to the - terminal the positive terminal is 12 volts higher, or +12V.  Relative to the + terminal the negative terminal is 12V lower, so -12V.

When one of your battery terminals is connected to a point in your circuit nominated as ground (the - terminal of your battery in this case) then your battery voltage at the + terminal is measured relative to ground, which we say is 0V.  So the + terminal is 12V higher than the - terminal, and the - terminal is 0V, so therefore the + terminal must be 12V with respect to ground.  The - terminal, since it is connected to ground is at the same voltage as ground, so it is 0V with respect to ground.

If you were to connect the + terminal of a battery to ground instead, then the - terminal would be 12V lower than ground, so would be -12V with respect to ground.  The + terminal would be 0V with respect to ground.


How is better to store html / java script / in code or in flash on esp32 I have an esp32 which is running a web page together with a java script and using socket I update some values on the web page. I am doing this very fast (like each 50ms). Now I am serving all the html/java script code stored in a string variable but I am wondering which is the best? To store this html in spiff or in code ? and why?
Thank you very much

Best is to store static files in SPIFFS and serve them with Expires header set, to let the browser cache the html, css, js files and pictures files.

How to build the Expires header:

unsigned long expires = now() + SECS_PER_YEAR;
bp.printf(F("Expires: %s, "), dayShortStr(weekday(expires))); // two printfs because ShortStr functions share the buffer
bp.printf(F("%d %s %d 00:00:00 GMT"), day(expires), monthShortStr(month(expires)), year(expires));

And use AJAX method to show data on the page. Make the request with XMLHttpRequest object:

function getData(cmd) {
  var xhr = new XMLHttpRequest();
  xhr.onerror = function(e) {
    alert(xhr.status + " " + xhr.statusText);
  }
  xhr.onload = function(e) {
    showValues(xhr.responseText);
  };
  xhr.open("GET", "http://" + host + ":" + restPort + "/" + cmd, true);
  xhr.send();
}

showValues would be your function to fill the data into page

In ESP32 build the response as JSON for simple handling of the data in JavaScript.

Here is the WebServer in my project. It uses the basic Arduino Server class, not the esp WebServer. It has #ifdefs for SD or SPIFFS. The static files of my project including the js file are here.


Arduino timer ctc mode 4 vs 14 I'm trying to gain an understanding of the Arduino timer and interrupts, particularly the CTC-modes 4 and 12. I wrote a small example in which I generate interrupts while the mainloop sleeps for 1 second and the display how many interrupts occured. It can toggle between mode 4 and 12 with the #if 1.

This works fine for mode 12 ( 50 interrupts/sec ) but in mode 4 it gives -12k interrupts / seconds... unless when I set OCR1A to 39999 again inside the ISR then it does give the expected 50 interrupts/sec, but I'd like to know why.

I think my confusion might be related to not understanding the table-header explaining the modes where it says "Update of OCR1x at". What is meant with that ( who updates it, and to what value? or do I need to update it in the ISR ) ?
Why would OCR1x be updated in mode 12 ( the table seems to state that it is) ? And it seems to work, even if I don't update it...?

Also, the only difference between mode 4 and 12 seems to be the register used for comparing to the timervalue (OCR1A vs ICR1)... but what is so fundamentally different between those? Why are there 2 options and what is the argument to choose for either mode 4 or 12 ?

Update: The issue seems to be related to initialization-order. If OCR1A is set to 39999 at the current location it gets reset to 0 a few lines further. When moving it after TCCR1A = TCCR1B = 0; then OCR1A keeps the value. So it's not necessary to set it on every interrupt.
This also explains why we get -12k counts on mode 4 (because we are comparing OCR1A in that mode, comparing to 0 and generating loads of interrupts)...

Any insight into why the initialization-order matters in this case would be appreciated.

Thanks in advance!

volatile int isr1 = 0;

ISR(TIMER1_COMPA_vect)
{
  // this is called every time our timer-compare matches to ICR1 or OCR1A
  isr1++;

  // when using the #if part below, we need to do this, or we end up with weird values for isr1 ( around -12.000 )
  // If we set it to the original value then we get 50 interrupts per second...
  OCR1A= 39999;
}

void setup() {

  Serial.begin(115200);
  delay(50);

  ICR1 = 39999;                   // 50Hz signal @ 16MHz clock
  OCR1A= 39999;

//TIMSK1 |= 1 << ICIE;            // bit 5: Input Capture Interrupt Enable (execute interrupt when TIFR1.ICF flag is set)
  TIMSK1 |= 1 << OCIE1A;          // bit 4 : Enable the Timer-Output-CompareA-Match Interrupt

  TCCR1A = TCCR1B = 0;            // reset timer-config flags
   // An interrupt can be generated at each time the counter value reaches the TOP value by either using the OCF1A or ICF1 Flag,
   // depending on the actual CTC mode. If the interrupt is enabled, the interrupt handler routine can be used for updating the TOP value.
#if 1
  // Arduino Datasheet 20.12.2. : The counter value (TCNT1) increases until a compare match occurs with OCR1A, and then TCNT1 is cleared.
  TCCR1B |= 1<<WGM12;             // code 4 (CTC, compare with OCR1A, Immediate update of OCR1x, overflow on MAX)
#else
  // Arduino Datasheet 20.12.2. : The counter value (TCNT1) increases until a compare match occurs with ICR1, and then TCNT1 is cleared.
  TCCR1B |= 1<<WGM13 | 1<<WGM12;  // code 12 (CTC, compare with ICR1, Immediate update of OCR1x(?), overflow on MAX)
#endif

  // using a prescaler of 8, which "slows down" the clockticks by factor 8.
  // 1 clocktick takes 0.5 microseconds, so 39999 clockticks need 19999,5 microseconds
  // 1 second = 1.000.000 microseconds, so we get 50 interrupts per second
  TCCR1B |= 1<<CS11;   // timer CS11 = clki/o/8, 1 tick per 0.5 microseconds
}

void loop()
{
  delay(1000);            // wait 1 second
  Serial.println(isr1);   // print how many interrupts we had in that second
  isr1 = 0;               // and reset for the next second.
}

As described in the operation part of the datasheet section, OC1x is double-buffered; the code sets a shadow buffer to a given value and then at some point the hardware copies the shadow buffer to the register that controls operation. "Immediate" means that the buffer is completely transparent since the value is copied immediately.

The difference between modes 4 and 12 is that mode 4 allows the use of ICP1 for input capture and mode 12 allows the use of OC1A for waveform generation.


Digispark / DigiKeyboard change keyboard layout I'm trying to use the Digispark as a Rubber Ducky but the Digispark is only usable with the US laylout. German keyboard layout is QWERTZ. Some keys can be changed, like y and z, but if there are [ or ] this isn't possible. Trying to define a [-key in DigiKeyboard.h displays a ü.

Does someone know a solution?

You can edit the file scancode-ascii-table.h in your DigiKeyboard library.
It basically states which ASCII code corresponds to which keyboard scancode.

So if you try to print the ':' character but get a '>' instead, you know that in the above mentioned file at the ASCII position for ':' is the scancode for a '>'.

Using this, you can swap the scancodes around and basically create your own 'mapping'. For example, if you swap the values at ASCII 89, 90 and 121, 122 you for example solve the Y/Z switch.

However, I have not figured out how to correctly print a backslash. You might have to map that do a different ASCII character you don't need.

To add to this answer, there exists a workaround using mame82's duck2spark:
https://github.com/mame82/duck2spark


Externally Powering a 3.3V device (nRL24L01+) with a 5V Arduino Pro Mini? I have seen several references where the solution to interfacing a 5V Arduino with a 3.3V nRF24L01+ was to power the nRF24L01+ externally.

How do I do this?  The ground of the nRF24L01+ is connected to the Arduino; can I simply attach 3.3V power between the power and ground pins of the nRF24L01+?

To connect the nRF24L01+ to a 5V Pro Mini you will need external 3.3V power supply to power the nRF24L01+.  The ground for the Pro Mini and the ground for the nRF24L01+ should be tied together to ensure a common ground reference.

The inputs to the nRF24L01+ are 5V tolerant so you will not need a level shifter to convert the 5V Digital IO on the Pro Mini to 3.3V. Be aware the not all 3.3V devices have 5V tolerant inputs like nRF24L01+.

You might want to look into using a 3.3V Pro Mini with that you should be able to use the regulated 3.3V power on the Pro Mini to power the nRF24L01+. Be aware that the 3.3V Pro Mini only runs at 8MHz instead of 16MHz.


Arduino code for XBee I am trying to send analog data, from a LM35, using an XBee (series 1 - XB24).

My setup:

Transmitting Module: XBee with USB explorer+Arduino+LM35 (temperature sensor)
Receiving Module: XBee with XBee shield+Arduino

I read analog data using the Arduino and send it through the XBee in the USB explorer, then the receiving XBee module receives it and shows it in the serial monitor of the Arduino.

I have tried many ways but I can't reach it and I have figured out that my problem lies in the Arduino code.

So, please can anyone help with some demo code for this project?

You probably want to take a look at Robert Faludi's book Building Wireless Sensor Networks, published by O'Reilly. He describes, step by step, a very similar project, but without the Arduino.

Or Alasdair Allan's Distributed Network Data, also published by O'Reilly, which has a similar project using an Arduino.

Also, take a look at Robert Faludi's blog TMP36 Instructions: Simple Sensor Network.


How to code Arduino to follow schedule I'm working on my system and I have to make arduino repeat such action or block of code if its the set time .. I'm using DS3231 module to track date and time .Example If I set the time in 6:00 AM and when the arduino reads the module and it turns out that its already 6:00 AM the arduino will now execute some action or the block of code .. sorry for my english ..

Check out how the DS3231 Alarm functions work.  They will interrupt even a delay() statement.  At the appointed time the specified function is called.

This same question was answered here:

How to set Alarms on the DS3231 easily?

For another way to see how to set this up, let me refer you to this article:

Build Programmable Time-based Switches Using a Real Time Clock

The code can be downloaded Here


Arduino ESP8266 Webserver What I would like to do is control my garden lights using the ESP8266. For this I use the Arduino approach from here. This works great, I use bootstrap and jquery even :D all is well!

Switching lights on and off using my code is fine but now I'd like to switch some continues routines, like blinking. I can start the blinking from the webpage but this code is a loop so I cannot get back to turn it  off again.

I could make it blink for a set amount of loops, so eventually it will stop blinking and show the control webpage again.
Or I can add the blinking to the hardware, maybe use a 555 for the first time?
But there might be a better way of implementing this..

Using Google I found information about Break and Interrupts, not yet what I am looking for.

#include <Arduino.h>

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

const char *ssid = "mynetwork";
const char *password = "mypassword";

ESP8266WebServer server ( 80 );

const int led = 5;
String webPage =
"<!DOCTYPE html>\
\
\
  <title>Funny Bunny Control</title>\
  <meta charset='utf-8'>\
  <meta name='viewport' content='width=device-width, initial-scale=1'>\
  <link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css'>\
  \
  \
\
\

\

\

Funny Bunny v0.1
\

\

Omdat snuffelen er bij hoort.
\

Niet voeren aub.
\

\

aan
\

uit
\

\

\
\
";

void handleRoot() {
  server.send(200, "text/html", webPage);
}

void aan() {
  digitalWrite ( led, 1 );
  server.send(200, "text/html", webPage);
}

void uit() {
  digitalWrite ( led, 0 );
  server.send(200, "text/html", webPage);
}

void setup ( void ) {
  pinMode ( led, OUTPUT );
  digitalWrite ( led, 0 );
  Serial.begin ( 115200 );
  WiFi.begin ( ssid, password );
  Serial.println ( "" );

  // Wait for connection
  while ( WiFi.status() != WL_CONNECTED ) {
    delay ( 500 );
    Serial.print ( "." );
  }

  Serial.println ( "" );
  Serial.print ( "Connected to " );
  Serial.println ( ssid );
  Serial.print ( "IP address: " );
  Serial.println ( WiFi.localIP() );

  if ( MDNS.begin ( "esp8266" ) ) {
    Serial.println ( "MDNS responder started" );
  }

  server.on ( "/", handleRoot );
  server.on ( "/aan", aan );
  server.on ( "/uit", uit );
  server.onNotFound ( handleRoot );
  server.begin();
  Serial.println ( "HTTP server started" );
}

void loop ( void ) {
  server.handleClient();
}

Take a look at the SimpleTimer [http://playground.arduino.cc/Code/SimpleTimer] library in the Arduino IDE environment.

You can have timers to:

call a function at a consistent interval,
call a function once after a set delay,
call a function a set number of times with a consistent interval
between.


Arduino parsing JSON I have created an API in Ruby on Rails and it send the following JSON response:

{"sun_position":{"altitude":"32.46","azimuth":"223.93"}}

I'm able to successfully hit the API and store the response. But when I try to parse it and store data it gives me an error. I have used the Arduino JSON library.

The code for parsing the JSON is as follows:

bool parseSunPosData(char* content, SunPosData* sunPos) {
  StaticJsonBuffer<JSONBUFFER_SIZE> jsonBuffer;
  JsonObject& root = jsonBuffer.parseObject(content);
  Serial.println("In parse fuc");
  Serial.println(content);
  Serial.println("==============");
  if (!root.success()) {
    Serial.println("JSON parsing failed!");
    return false;
  }

And the output on the serial monitor is as follows:

  In parse fuc 38

  {"sun_position":{"altitude":"32.46","azimuth":"223.93"}} 0

  ==============

  JSON parsing failed! Disconnect

My guess is it can't parse the data due to the numbers 38 and zero printing... I don't know what that is and what it is.

PS: New to Arduino coding.

you have the HTTP chunked transfer encoding numbers in the content. 38 is the length of the body and it is on the first line of the HTTP body and 0 marks the end.
maybe try using ArduinoHttpClient library for HTTP


How do I convert code between Arduino platforms? What documentation is available regarding the differences between the different Arduino platforms?

For example, I have some code written for an Arduino Teensy that I would like to run on an Arduino Mega.

Is there documentation on the capabilities and equivalencies between each of the platforms?  e.g. memory, number of PWM outputs, etc?

The most detailed one seems to be Baldengineer's, but Arduino, SparkFun, and Adafruit have their own as well, although more limited.

As always, the best source for information about them is the datasheets for both the MCU(s) used as well as for the boards themselves.

And note that different macros are predefined for each MCU and feature (e.g. __AVR_ATmega328__ and __AVR_HAVE_MUL__); it is possible to test for their existence in order to customize behavior.


When it comes to UART to RS485 communication, what is the difference between the 'MAX485' and the 'HW-0519' module? I recently found this model with the ID 'HW-0519' on it. It can be found online (HW-0519 in Aliexpress) and is sold for the purpose of converting UART to RS485 communication using Arduino devices. The MAX485 module (MAX485 in Banggood) is the more commonly used module for this purpose and has been used in many projects. The MAX485 has the following pins DI (data in), RO (receiver out), DE (Data Enable), RE (Receiver Enable), VCC, GND and the 'A' and 'B' pins for the RS485 device (Shown below).

The HW-0519 module, has a slightly different pin configuration, and I can't seem to wrap my head around it. It has Tx and Rx pins, which I am guessing match up with RO and DI respectively, but don't have enable pins. They have the VCC and GND pins along with the 'A' and 'B' pins, but also come with this pin marked in Chinese. I translated it using Google translate and it translates to something similar to 'Ground'. Which is not connected to the GND pin though (Shown below).

Does anyone know whether I can use the HW-0519 module in the same manner as the MAX485? If so, are there any libraries written for this module? I want to use the module for communication with a pH sensor like the one in this link.

I did a bit of research and found others who use this particular component for their RS485 communication purposes. It is difficult to get clear info because the device goes by different names and the most commonly used name is MAX485 (name of the IC), which is used interchangeably for both the components shown in the question.
It seems the more I search for the 'HW-0519', the more names I find for it. So far, it goes by the name 'MAX485', 'XY-017', and 'XY-K485'. A clear advantage for this 'HW-0519' is that it does not require D or R enabling, just straightforward Tx and Rx. It also has LEDs to show the data transfers. I found a project that used this module here. I am unsure about their pin connections from the ESP-32 though. It looks like they've connected the ESP-32's TX2 to the HW-0519's Tx, and the RX2 to the Rx. I thought it should be the other way around.


Can anybody advise what type of connector this is? I recently purchased an LiPower shield from SparkFun.

I also bought a Lithium Polymer battery off eBay and it appears to have a JST male connector (i could be wrong)?

I expected it to slot right into the board however the fit is slightly too large. Can any advise me of the name of the connector for the board battery supply, or have I mistaken the battery output connector?

Please see pictures below, thanks!

The board uses a JST PH connector, with 2.0mm spacing. The battery has a JST XH connector, with 2.5mm spacing. You will need to replace the battery connector or put a XH socket on the board.


Why do most arduino function return a -1 instead of a 0 Many arduino functions return -1 if something 'fails'. Serial.read for example returns -1 or the infamous ÿ when this function is called while the serial buffer is empty.

As embedded C progammer, I am personally a fan of letting functions return data in the form of modifying pointers which points to passed on addresses and return states with the actual return functionality of a function. I am used to return a 0 if a function is 'not done' or 'failed'.

I see no logic in why many arduino functions return an int type which contains -1 instead of just a 0.

Would it not be better to let functions return a boolean type or an unsigned char type in which false or '0' would indicate a 'failed' process and true or '1' would indicate a 'succesful' process?

Also: if I type:
if(Serial.read()) {/* body */ }
and Serial.read() returns -1 because the buffer is empty. Will the If's body be executed or not?

I cannot assert anything for sure, as I was not involved in the design
of the Arduino APIs. However, just like Elliot Alderson, I suspect this
was inspired by the traditional C APIs. The manual page for getchar(),
which is a very old function from the standard C library, states:

  fgetc(),  getc() and getchar() return the character read
  as an unsigned char cast to an int or EOF on end of file or
  error.

Given that EOF is usually defined as -1, this is consistent with the
behavior of Serial.read().

Being beginner-friendly is also a major goal of the API. Pointers are
known to be a huge difficulty for beginners.

There may also be some efficiency considerations involved. Arduino
started on the AVR platform. This is a RISC architecture, with a large
number of generic CPU registers (namely 32). The compiler usually
manages to allocate most local variables to registers. The calling
convention ensures that in most cases function parameters and return
values also go through CPU registers. This means we can avoid many RAM
accesses, which are inherently much slower than register access. Using a
return-by-pointer convention defeats these optimizations.

Lastly, it is a good thing that simple things are easy to write. For
example, an interpreter for single-character commands can be very easily
written as:

switch (Serial.read()) {
case 'a':
    do_command_a();
    break;
case 'b':
    do_command_b();
    break;
// etc...
}

with no need to explicitly test for the serial buffer not being empty.
Obviously, a more complex command language will need a full-blown
interpreter, but the focus of Arduino has always been on simple
programs being easy to write.


Sketch will not start with external power source NOOB Question: when my Uno is connected to an external power source it will not start running the uploaded sketch. The Arduino web site says it's because the RX pin is not connected and then gets random data.

The site suggests grounding the RX pin using a resistor (granted it suggests a 10K and I used a smaller one ) or connecting it to the TX pin.

From Why doesn't my sketch start when I power up or reset the Arduino board?

  Most likely because you are sending serial data to the board when it
  firsts turns on. During the first few seconds, the bootloader (a
  program pre-burned onto the chip on the board) listens for the
  computer to send it a new sketch to be uploaded to the board. After a
  few seconds without communication, the bootloader will time out and
  start the sketch that's already on the board. If you continue to send
  data to the bootloader, it will never time out and your sketch will
  never start. You'll either need to find a way to stop serial data from
  arriving for the first few seconds when the board powers (e.g. by
  enabling the chip that sends the data from within your setup()
  function) or burn your sketch onto the board with an external
  programmer, replacing the bootloader.

From Why doesn't my sketch start when I'm powering the board with an external power supply? (Arduino Diecimila or earlier)

  Because the RX pin is unconnected, the bootloader on the board may be
  seeing garbage data coming in, meaning that it never times out and
  starts your sketch. Try tying the RX pin to ground with a 10K resistor
  (or connecting RX directly to the TX pin).

Both failed for me.

What should I do?

The problem was, as Gerben said, the battery was too weak to run the engine.


Arduino voltage drop while communicating with another Arduino I have an Arduino Uno rev 3 and an Arduino Nano in my Setup. I want to create a proof of concept, where one Arduino triggers the other via the Digital IOs.
Arduino 1 sets a blinking signal on a digital pin (500ms delay between high/low), which is received by arduino 2. If the signal is high, Arduino 2 triggers a LED (digital pin to LED+; LED- over 330 Ohm resistor to ground), so the signal gets looped through somehow. The grounds of the two Arduinos are connected, too.

Code Arduino #1:

void setup() {
  DDRD |=_BV(PD7); //Sets Digital Pin 7 as Output
}

void loop() {
 PORTD |=_BV(PD7); // equivalent with digitalWrite(7, HIGH);
 delay(500);
 PORTD &=~_BV(PD7); // equivalent with digitalWrite(7, LOW);
 delay(500);
}

Code Arduino #2:

void setup() {
  DDRD &=~_BV(PD7); //Sets Digital Pin 7 as Input
  DDRD |=_BV(PB0); //Set Digital Pin 8 as Output
}

bool set = false;

void loop() {
  if((PIND&_BV(PD7))==_BV(PD7)) { //true if digital pin 7 is set
    if(!set) {
      //PORTB |= _BV(PB0);
      digitalWrite(8, HIGH);
      set = true;
    }
  } else {
    //PORTB &=~_BV(PB0);
      digitalWrite(8, LOW);
    set = false;
  }

}

But instead of emitting a bright light, which can be seen if connecting the blinking signal directly to the LED, it emits a faint light. The voltmeter also shows an significant Voltage drop. Whilst the digital pin should have a voltage of ~5V when set to HIGH (never reached because of inner resitance inside the arduino), it measures about 1.6-1.8V.
I also switched the both Arduinos which showed the same result, so it shouldn't be a hardware defect.

Thanks in Advance!

the line DDRD |=_BV(PB0); should be DDRB |=_BV(PB0); currently PB0 is set as an input so when you set it high it is just turning on the pull-up resistor, which is basically adding another ~10k in series with the LED, hence the dim light.


How to control 19 RGB LED strips with one arduino? I need to light up 19 RGB LED strips, which it seems would require 19*3=57 PWM outs and 57 transistors.  The transistors aren't an issue, but of course the 57 PWM's is.  Even if I hacked the digital IO ports to work as PWM, I still wouldn't have enough.

How can I do this more simply?  Is there some kind of device I can get that would let me just pass data to it, perhaps over I2C, and it would control many PWMs? Is there another solution I haven't considered?  Maybe whatever is used to control those 8x8 RGB LED dot matrixes?

Any help would be greatly appreciated.  Thank you!

You can use addressable LEDs that allow chaining from one LED to another using a serial protocol.

Like this :

This would alow you to set the first row blue, the second purple, each one can be controled independently.

Take a look at Ada Fruit's neopixels to start. These are basically skillfully branded WS2811 & WS2812 LEDs, but they are very well documented and well built. They feature 8 bit per channel RGB color (24 bit color) and take care of PWM internally. You could even chain the end of one strip to another, allowing all control to come from two pins of an arduino.

Assuming you go this route, consider the following:

You will need enough RAM to store the full array of pixels in memory, which is 3 bytes per pixel.  Alternatively, you can create a custom library with reduced bit depth, or one that stores pixels in clusters, because at the end of the day you are just operating a giant shift register.
You will need to supply enough current (60mA per led), and supply it at several points along longer strips.  You will likely need to use external power sources.  You can drive a decent amount of LEDs from Vin (before the power regulator), but not anything near 19 strips.

Now if you already have the strips, and they are analog strips, I think you can find similar drivers that output more power to drive strips, but still use a serial protocol.

You can use my example code here:

// NeoPixel Demo minimum
// By leo etchaas
// released under the GPLv3 license to match the rest of the AdaFruit NeoPixel library

#include <Adafruit_NeoPixel.h>
#include <avr/power.h>

// Which pin on the Arduino is connected to the NeoPixels?
// On a Trinket or Gemma we suggest changing this to 1
#define PIN            6

// How many NeoPixels are attached to the Arduino?
#define NUMPIXELS      55

// When we setup the NeoPixel library, we tell it how many pixels, and which pin to use to send signals.
// Note that for older NeoPixel strips you might need to change the third parameter--see the strandtest
// example for more information on possible values.
Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);

int delayval = 500; // delay for half a second

void setup() {
  // This is for Trinket 5V 16MHz, you can remove these three lines if you are not using a Trinket
#if defined (__AVR_ATtiny85__)
if (F_CPU == 16000000) clock_prescale_set(clock_div_1);
#endif
// End of trinket special code

pixels.begin(); // This initializes the NeoPixel library.
}

void loop() {

// For a set of NeoPixels the first NeoPixel is 0, second is 1, all the way up to the count of pixels minus one.

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

// pixels.Color takes RGB values, from 0,0,0 up to 255,255,255
pixels.setPixelColor(i, pixels.Color(25,255,255)); // Moderately bright green color.

pixels.show(); // This sends the updated pixel color to the hardware.

delay(delayval); // Delay for a period of time (in milliseconds).

}for(int i;i>0;i-=1){

// pixels.Color takes RGB values, from 0,0,0 up to 255,255,255
pixels.setPixelColor(i, pixels.Color(255,5,255)); // Moderately bright green color.

pixels.show(); // This sends the updated pixel color to the hardware.

delay(delayval); // Delay for a period of time (in milliseconds).

}
}


Unreliable communication with low baudrate on Leonardo I am using an Arduino Leonardo (more precisely this product), to communicate with servo-motors) using RS485.

Everything works fine as long as I don't go below a baud rate or 115200bps. If I go below, as 57600 or 9600, I start to get ill-formed packets from my motors: the 4 first bytes are usually correct, but the end of the packet contains incoherent data, and the checksum is obviously wrong.

I am using IndustrialShields (my PLC/Arduino vendor) library for RS485, and I don't see any mention of this problem.
I am using Half-duplex communication, with U2X if I correcly understand the source code of the library.

Note that the documentation of the servo-motors mentions there is a small error margin on the clock for low baud rates, but since it works with 115200bps, which has the highest error margin, it shouldn't be a problem.

Also the motors seems to understand the packet I send, but I do not receive their packet correctly.

Is there an edge-case I am not aware of? Sorry for the lack of details, I am not sure what else I can say.

I suspect that the RS-485 interface in your servo is what is at fault.  Nothing to do with the Arduino or your communication, or software.

Without knowing more about the servos and how they are wired internally it's hard to be certain, but I can assume:

The servo has some kind of controller in it which communicates over the bus
That controller may or may not directly control the direction pin on its interface

It's the latter that is critical. There is a way of wiring up a MAX485 that automatically controls the direction pin - immediately you start sending data it asserts it into TX mode. The trouble comes when switching back to RX mode - there's a few ways of doing that:

Shortly after the last bit of a certain value (0 or 1) has been sent (the bit stream keeps a capacitor charged)
A certain time after the start of communication.

The first method is usually more reliable across multiple baud rates, but can be sensitive to the values of the bytes sent - if it relies on a 1 being sent to keep the capacitor charged and a number of 0 bytes are being sent it won't see the 1 that keeps the transmit mode open, and it can close prematurely.

The second method is more reliable for fixed length packets, but will only work for a certain (or small range) of baud rates. If sending a packet takes longer than the allotted window then it will truncate regardless.

However if the controller in the servo is itself directly controlling the data direction pin then it could be that there is a bug in its firmware. Maybe it's working on a delay principle and they got the time calculations wrong.  Maybe it's working on a "queue being empty" principle and they forgot about there being a hardware buffer that also needs to empty, but high baud rates just manage to squeeze through in time.

It's impossible to be sure, but going by the symptoms you describe those seem to be the most logical scenarios.


I want 2 output pins to working alternately I have given pwm output on pin(9) and I Want pin(10) to be high when pin(9) is low and pin(10) to be low when pin(9) is high.  So what should i add to my code?

You can set pin 10 to run in “inverted PWM” mode, and leave
pin 9 in the default non-inverted mode. Pin 9 is the “OC1A”
pin of the AVR microcontroller (output compare of Timer 1,
channel A), whereas pin 10 is OC1B (channel B of the same
timer). Inverting the PWM mode of channel B is a matter of changing
a single bit in one of the control registers of Timer 1:
TCCR1A |= _BV(COM1B0);

You can do this once in setup(), the setting should persist. Then just
analogWrite() the same value to both pins. For some background on how
all this works, see the datasheet of the ATmega328P
microcontroller (the MCU at the hearth of your Uno),
especially section 16 “16-bit Timer/Counter1 with PWM” and table
16-3 “Compare Output Mode, Phase Correct and Phase and Frequency Correct
PWM”.


Arduino boards are not working with powerbanks! I have used many Arduino boards with adapters and other power supplies. While connecting with a powerbank for portable projects I have noticed that the power goes off after a couple of seconds and then turn on again after sometimes. Why this is happening with power bank?
I have used following powerbanks:

Basus
Xiaomi

Most USB powerbanks will automatically turn off if there is not a minimum current draw to keep them turned on.  The Arduino is obviously drawing current below the limit for the devices you have.
A couple of options:

Add some additional load to keep the powerbank on indefinitely.  Of course this may waste power but that's part of the price to pay.
Find a power bank that is less sophisticated.  I have one with a manual on/off switch.  It powers the Arduino just fine until it runs out of power.
Find a different powerbank that has a lower threshold for staying on.  Some vendors give you this spec and others don't.
Modify the powerbank to stay on.  I'm not sure there is a general way to do this but you might experiment with it and see.


Connect ESP8266 to Thingspeak I have an Arduino UNO and an ESP8266 module.
I would like to connect my ESP to my wifi network and upload data to Thingspeak.
How can I do it?
What I find on the web is a bit misleading and non-specific to my case.

Thank you very much.

Here's an instructable on ESP8266+Arduino+thingspeak.com environment monitors:
http://www.instructables.com/id/ESP8266Arduinothingspeakcom-environment-monitors/

Lots of examples in the thingspeak documentation:
https://www.mathworks.com/help/thingspeak/examples.html

-Rob


How can I attach I2C sensors on the small board of Intel Edison? Sensors like Skin conductance, Body temperature and Heart Rate. Please imagine to talk to a child and keep the answer very simple so I can understand you and you don't lose time to write explanations for your answer.

If you're using the mini-breakout board (https://www.sparkfun.com/products/13025), then you can get the I2C connections from the board (connections available through holes under the Edison; you can see them from the backside; see: https://cdn.sparkfun.com//assets/parts/1/0/0/1/1/13025-02.jpg). You can solder headers on or can solder wires directly to the required pins. You can find the pin mapping here: http://iotdk.intel.com/docs/master/mraa/edison.html


How can you count the number of interrupts that have taken place? I'm trying to program a Timer Interrupt that will go off every 33 ms. I am doing this on the ATtiny85 which has a 20MHz clock. The maximum prescaler I can set is 32 so the longest possible time a single interrupt can be is 408 microseconds.

My plan to reach 33 milliseconds is to just run the interrupt 81 times and that will get me the desired 33 milliseconds. However, I have no clue as to how you can actually count how many time an interrupt has taken place. Anyone on here know how to do that or have any idea as to what would work?

Yes, just add a check inside your ISR statement.

ISR(TIMER0_OVF_vect)
{
  static uint8_t postscale = 0;
  if (++postscale == 81)
  {
    postscale = 0;
    do_stuff();
  }
  else
  {
    go_to_sleep();
  }
}

You always have to enter the ISR method once you're done with the interrupt so just add that if statement and use a static variable (so that it keeps its value) to check if you have made the correct number of loops.


Use Arduino Uno digital pins instead of ESP8266 I would like to know if this is possible.

I am using an ESP8266-ESP01, which only has 2 digital pins. I have a project that needs 3 digital pins so I have planned to use my Arduino, so I can use more digital pins. My plan is instead of plugging the sensor in the GPIO1 of the ESP8266, I could somehow plug it in the Arduino digital pins and the data would just be transferred to the ESP8266 and be uploaded to an online cloud.

I can read the sensor data in the Arduino but I don't know how to transfer the data to the ESP8266 so the wifi module would just receive it and send it to the online cloud.

If anyone can help me to get some idea specifically on sending the data from Arduino to the ESP and receiving the data from the Arduino.

Thank you.

DDA's answer is perfectly correct.
Like he says you need to check the voltage and use a logic level shifter.

However looking at it from another angle there are a whole range of ESP that have an increasing number of digital pins.  You could look at using an ESP-5, or an ESP-12E, these have different forms and increasing number of digital pins.

You could also look at the Wemos range, I believe there is an UNO form board and there is the Wemos D1-Mini, which has 10 digital and 1 analog.

Running on two boards is usually more of an issue than running on one board, god help you if you have synchronisation issues!


avrdude fuse error when programming ATMEGA328 without crystal I built several boards with an ATMEGA328 and no crystal a couple of years ago. I programmed them successfully with a bootloader using usbasp, and with a sketch using the Arduino serial interface. I have now made some more, but I get an error message from AVRDUDE when I try to burn the bootloader:

***failed;
avrdude: WARNING: invalid value for unused bits in fuse "efuse", should be set to 1 according to datasheet
This behaviour is deprecated and will result in an error in future version
You probably want to use 0xfd instead of 0x05 (double check with your datasheet first).

I followed the instructions here and I am using the hardware configuration archive referenced on that page: breadboard-1-6-x.zip.
If I reprogram the bootloader on a device that does have a crystal, it works if I select Arduino Pro/Pro Mini (3.3V, 8MHz), but fails with the message above if I select the breadboard specified in the boards.txt from  breadboard-1-6-x.zip.
There are no other error messages, but... if I turn on verbose, it works.. turn verbose off and it stops working again. Maybe verbose mode modifies the timing enough to make it work.
I know that you can use the -B option to slow down avrdude when you run it from the command line: is there a way of doing the same thing from within the Arduino environment?

The ATMega328P datasheet has the following table in it:

The top 5 bits of the of the Extended Fuse Byte are default 1 and are reserved.  You're not really supposed to change them, since they might be used in the future for a 328P-like part and setting them to something other than 1 could have unexpected results.  In the 328PB variant bit number 3 is used for "Disable Clock Failure Detection".
The lower three bits of 0xFD and 0x05 are both 0b101.  In other words, taking into account only the bits you should be setting, for the BODLEVELn fuses, they would have the same effect.  But you are being WARNED that you should be using 0xFD rather than 0x05 for the above reason.
The boards.txt that comes in the breadboard-1-6-x.zip has a line that looks like this:

atmega328bb.bootloader.extended_fuses=0x05

You could change this yourself by editing the file, but really for what you're doing I'd recommend MCUdude MiniCore which is comparatively up to date.  If nothing else, its boards.txt file has been written with the correct fuse values.  You can see there for a plain 328P (not PB) which does not support clock failure detection, the CFD bit is just hardcoded to 1 in the file.
The message you're seeing is a "WARNING" through, rather than "ERROR".  The distinction being that warnings don't actually stop you from continuing.  It is likely that if you're having a problem isn't not really because they've incorrectly specified the high-order bits of the fuse.  If it's halting, it may be arduino-builder see a non-zero exit code for avrdude and thinking this means "ERROR" rather than "WARNING", in which case this problem will go away if you edit the boards.txt file (or adopt MiniCore) such that no longer produces the warning.
Unless you've brought the effective system clock below 1MHz, probably lower still, it's not likely that you'll need to change from the default ISP clock rate.  If you do though, that can also be done by editing board package files.


Use Arduino Uno to program the on-board Atmega328 in C I have an Arduino Uno board.  I have seen how it is possible to program external AVR's through the Arduino Uno board, for instance an ATtiny. But I'm starting with c for atmel µc and I just want to program Atmel328's through the Arduino hardware, and being able to use the arduino pins for outputs etc.

So my question is, can I use the Arduino Uno board together with avrdude and avr-gcc to program the on-board atmel328 in C? And thus being able to use the Arduino pins for output and input?

Yes, the Uno is designed to be very simple to program. The only extra hardware you need is a USB cable to connect it to your computer.

If you're completely new to this then the simplest way to start is by following the official "Getting Started" guide. Note that the section on drivers is particularly important.

The guide explains how to use the official Arduino IDE for programming the microcontroller. It automatically handles compiling and uploading your code via gcc and avrdude. It's technically configured to compile as C++ code, but plain C code should be fine too.

I don't recommend that IDE for long-term use though as it's really only aimed at beginners (it has a number of limitations and other problems). Using the command-line tools directly is certainly possible if you'd prefer that. However, you may also like to consider alternative IDEs which have support for Arduino plug-ins.


Digital Inputs have gone crazy My digital inputs are behaving as if they were floating, even though I've properly connected them with a resistor.  I've tried the pull-down configuration pictured below, as well as a internal pull-up.

By using digitalRead() and serial.pintln() I've collected the state of each input tested (0 to 10) and they all do the same: random 0's and 1's.  When I change a state (press or release the button), they seem to work for a second or two, then, they go crazy again.  Sometimes, they even work backwards (showing HIGH when it's supposed to be LOW) for a couple of seconds.

Is my two-day old Arduino UNO fried?

Solved it, but here is the solution, so there is an answer available for anyone who might encounter the same problem...

Quality check your protoboards.  This is making me feel stupid.  The protoboard I used had a faulty connection on the blue line I was using, causing an inevitable floating input.  So relieved I found the problem, and yet so annoyed!

Take care you all.


USB Mouse Passthrough I am currently doing research for a project of mine. My goal is simple: I want to pass input from a physical mouse, to a microcomputer to process the input and modify, and send the input in the form of USB HID to a PC.

  Mouse ---> Microcomputer (input modified) ---> PC

The Microcomputer preferably should be able to both send data to the PC (in the form of USB HID inputs as a mouse) and receive data from the PC.

I found the arduino Leonardo can act as a USB slave and emulate mouse movement, half of what I want. I need some microcomputer with capabilities to act both as a USB host and as a USB slave. I don't have experience with microcomputers, and I don't know how to find something with this feature.

Plug a USB Host Shield into the Leonardo.

USB mouse --- USB Host Shield --- Leonardo --- PC

USB Host Shield Library

Circuits@Home Project

/*
 * USB Mouse pass through. Works at HID report level. HID report is not decoded.
 * Tested on Leonardo with Arduino USB host shield, IDE 1.8.5, and Logitech Marble
 * trackball/mouse. This is a proof of concept so is not guaranteed to work with
 * all USB mice/trackballs.
 */
// USB host mouse from USB Host Shield Library. Install using Library Manager
#include <hidboot.h>

// USB device mouse library included with Arduino IDE 1.8.5
#include <Mouse.h>

// Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#endif
#include <SPI.h>

class MouseRptParser : public MouseReportParser
{
protected:
    void Parse(USBHID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf);
};

void MouseRptParser::Parse(USBHID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf)
{
  Serial.print("MouseRptParser::Parse");
  // Show USB HID mouse report
  for (uint8_t i = 0; i < len ; i++) {
    Serial.print(' '); Serial.print(buf[i], HEX);
  }
  Serial.println();

  // On error - return
  if (buf[2] == 1)
    return;

  if (len > 2) {
    uint8_t mouseRpt[4];
    mouseRpt[0] = buf[0];
    mouseRpt[1] = buf[1];
    mouseRpt[2] = buf[2];
    mouseRpt[3] = 0;
    HID().SendReport(1,mouseRpt,sizeof(mouseRpt));
  }
}

USB     Usb;
HIDBoot<USB_HID_PROTOCOL_MOUSE>    HidMouse(&Usb);

MouseRptParser Prs;

void setup()
{
  Serial.begin( 115200 );
#if !defined(__MIPSEL__)
  while (!Serial) delay(1); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
#endif
  Serial.println("Start");

  if (Usb.Init() == -1) {
    Serial.println("USB host shield did not start.");
  }
  delay( 200 );

  HidMouse.SetReportParser(0, &Prs);

  Mouse.begin();
}

void loop()
{
  Usb.Task();
}


Autonomous Quadcopter power distribution and sensing concerns I've been programming and testing an Arduino based quadcopter for the past 4 months. Until now I did not need to use an external power source for my sensors. Now I want to use the 'BEC' power from my electronics speed controllers.

Each of the 4 ESCs gives 5V @ 2A. I would set these up in a parallel circuit, which would give me 5V @ 8A (theoretically).

I also want to use a cheap chinese voltage sensor to sense the voltage from my 5000mAh 25-50c 11.1v battery. I'm not sure if it is safe to connect my batteries wires to my sensor with the 125A that it can put out.

My question is whether or not it is safe to have a common ground on Arduino with an 8A power supply AND if it is safe to use a 5V 8A power supply with these sensors.

Here is a problem that I've encountered before:

while powering my IMU off the BEC and sending motor PWM signals, my sketch would run for about 10 seconds then freeze. It was not until I powered my IMU off the Arduinos 5V power that I was able to run the sketch flawlessly. What could have been causing that?

I've made a diagram of my circuit in Fritzing (not actually tested yet due to fear of ruining my sensors). I'm using an Arduino Mega.

Your question is quite long. I've broken it up into several parts:

  whether or not it is safe to have a common ground on arduino with an 8 amp power supply

Yes. In fact, if you have any electrical connection (even a signal) between those two, you'll need a common ground to ensure integrity of the data being sent.

  if it is safe to use a 5 volt 8 amp power supply with these sensors.

I didn't see how much they drew. Without a lot of information, I'm going to say yes. If you don't need that much current, consider removing one of them so you only have 6A or 4A, since 8A is quite a bit if you aren't using it (and you might waste electricity in the conversion process). Make sure to have a thick enough wire for it. A best practice scenario would be to use each ESC separately or use two of the ESCs in parallel (with all  of the grounds connected!). This would isolate the current to either 4A or 2A.

  while powering my IMU off the BEC and sending motor PWM signals my sketch would run for about 10 seconds then freeze. It was not until i powered my IMU off the arduinos 5 volt power that I was able to run the sketch flawlessly. What could have been causing that?

I'm not quite sure what would be causing that without seeing the code/circuit for that. The only thing I can think of is the grounds weren't connected and the signal got corrupted.


How to connect Big Dome Button with arduino I am quite new to arduino and for a project I want to use big dome button which when pressed it will count how many times has been pressed.It is using 12 volts.The button is this https://www.sparkfun.com/products/9181

As others have said, the 12V powers the switch's internal LED.

EDIT:
Switches don't need power. If you skip all power to the switch it will still work but it won't light up.
End of edit:

If you want the switch to light up, connect the V in to 12V, or if you connect it to 5V, it will be dim, but -probably- still light. (You are certain to have a 5V pin on your Arduino board. Using that means you don't need a separate 5V supply.)
Now connect one lead of the switch to a digital input, and the other lead to ground.
Then set your switch pin to INPUT_PULLUP mode. Now your switch will read HIGH until it's pressed, then it will read LOW.
create a variable at the top of your code called buttonState:
byte buttonState = HIGH;

Also define an unsigned long variable nextReadMillis:
unsigned long nextReadMillis = 0;

and a pressCount variable:
unsigned int pressCount = 0;

And define a debounceTime:
#define debounceTime 50

In your loop, do something like this:
void loop() {
    //Get the new millis(value)
    unsigned long newMillis = millis();

    //only look at the new button value if enough time has elapsed.
    if (newMillis >= nextReadMillis) {
       byte newButtonState = digitalRead(buttonPin);

       //Only do something if the button state has changed
       if (buttonState != newButtonState) {
          buttonState = newButtonState;
          nextReadMillis = newMillis + debounceTime;
          //If the button is now in the pressed (LOW) state, increment the count
          if (buttonState == LOW) {
              pressCount++;
          }
       }
    }
}

That's pseudo-code. It likely has syntax errors. It's not meant to be copy/pasted. Use it as a guide for your project.
The code using millis() is a version of "software debouncing." Electrical switches tend to "jitter" or "bounce" between their on and off states very rapidly when they are first pressed/released. By only checking for state changes after a brief delay, you ignore the jitter in the readings.
Note that if you want your LED to only light when the button is pressed, you could control it with another digital pin. You'd assign a different pin to controlling the LED output, set that pin to OUTPUT mode, and switch the pin based on button state inside the body of the if (buttonState != newButtonState) if statement.
If your LED draws ≤20mA at 5V, you could connect it directly to your output pin. If it draws more than that, you will need a transistor to drive it so you don't draw too much current from your output pin and burn it out. Wiring a transistor driver is beyond the scope of this post however.


Why is my liquid crystal display not showing any output? UPDATE:
The LCD will light up only when the all my components are located in the bottom right of the breadboard. Why am I not able to use the entire breadboard for my circuit?
I am trying to display data from a temperature and humidity sensor on the serial monitor and the liquid crystal display.
I am using :

Arduino Uno R3
I2C 16x2 LCD Module
3 pin DHT11 sensor

Here is my code :
#include <dht.h>                // initialize the digital temperature and humidity sensor library ("DHTlib")
#include <LiquidCrystal_I2C.h>  // initialize the liquid crystal display library ("LiquidCrystal I2C")
#include <Wire.h>               // intialize the wire library

/*   the first parameter is the I2C address
 *   the second parameter is how many columns are on your screen
 *   the third parameter is how many rows are on your screen
*/
LiquidCrystal_I2C lcd(0x27, 16, 2);

dht DHT;              // create a handle to call functions from the sensor library
#define DHT11_PIN 7   // assign a digital pin number to the sensor
float TempC;          // create a variable to store temperature in celsius
float TempF;          // create a variable to store temperature in fahrenheit
float Humi;           // create a variable to store humidity

void setup()
{
  lcd.init();                // initialize liquid crystal display
  lcd.backlight();           // turn on the backlight of the lcd
  pinMode(DHT11_PIN,INPUT);  // configure the pin for the sensor as an input for reading the data
  Serial.begin(9600);        // set data rate in bits per second for serial data transmission
}

void loop()
{
  // collect sensor data
  int chk = DHT.read11(DHT11_PIN);  // store sensor data in a variable
  TempC = DHT.temperature;          // store temperature in Celsius
  TempF = 9 / 5 * TempC + 32;       // store temperature in Fahrenheit
  Humi = DHT.humidity;              // store relative humidity as a percentage

  // display sensor data on LCD
  lcd.setCursor(0,0);    //tell the screen to write on the top row
  lcd.print("T: ");
  lcd.print(TempC);    // print the temperature in Celsius
//  lcd.print(TempF);    // print the temperature in Fahrenheit
  lcd.print((char)223);  // print the degree symbol
  lcd.print(" C");
//  lcd.print(" F");
  lcd.setCursor(0,1);    // tell the screen to write on the bottom row
  lcd.print("H: ");
  lcd.print(Humi);       // print the humidity
  lcd.print(" %");

  // display sensor data on the serial monitor
  Serial.print("Temperature = ");
  Serial.print(TempC);     // print the temperature in Celsius
//  Serial.print(TempF);     // print the temperature in Fahrenheit
  Serial.print("\xc2\xb0");  // print the degree symbol
  Serial.println(" C");
//  Serial.println(" F");
  Serial.print("Humidity = ");
  Serial.print(Humi);        // print the humidity
  Serial.println(" %");

  delay(2000);  //delay fetching the next sensor values for 2 seconds
}

My jumper wires are connected as follows:

DHT plus → red plus row
DHT middle → digital pin 7
DHT minus → blue minus row
LCD GND → blue minus row
LCD VCC → red plus row
LCD SDA → analog pin A4
LCD SCL → analog pin A5
Red plus row → 5V pin
Blue minus row → GND pin

Your breadboard is one of those which have the power/GND lines interrupted between columns 31 and 33. I also once fell into this trap. If you look closely, you see that the blue and red lines are interrupted in the middle of the board. Just put wires between these pins to bridge the gap.


Using timer classes within classes I am trying to develop a class for a pump that works on a stepper motor, it should be simple but its not working the way I thought it would. Once I move the timer object into the class the code wont compile I have tried a lot of things but nothing seems to work correctly. The goal of this whole thing is getting the stepper motor to step on its own based off of the calls from the timer object.

pump.h

#include "TimerObject.h"`
#ifndef Pump_h
#define Pump_h

class Pump
{
  public:
     Pump(char pin_, char dir_);
    void pumpstep(void);
  private:
    char pin;
    char dir;
    TimerObject *pumptimer;
};

#endif

pump.cpp

Pump::Pump(char pin_, char dir_)
{
    pin = pin_;
    dir = dir_;
    pumptimer = new TimerObject(100, &this->pumpStep); //PROBLEM IS HERE

  pinMode(pin, OUTPUT);
  pinMode(dir, OUTPUT);
}

void Pump::pumpstep(void) {
     Serial.println("Stepping");
}

my .ino simply creates the class passing in the needed parameters but everything binds up when I try to compile because of the callback in the constructor for the timer, for some reason It wont let me use the address of a non-static method here but I cant make the method static each pumpstep() method must be separate depending on which pump is running.
I have tried using &Pump::pumpstep, &(Pump::pumpstep) and many more pointers but cant seem to get the one I need.

outside this class the timer was working great I used this line below:

pumptimer = new TimerObject(100, &pumpStep);

The library for the timer can be found here:
https://playground.arduino.cc/Code/ArduinoTimerObject

Any help would be greatly appreciated.

The function prototype of a member function is completely different to that of a global function. The two are not interchangeable.

There are ways of working around it, such as "bouncing" your callback through a global function, but they're messy.

However, in this situation you are better off just ditching TimerObjects.h and doing it manually - it's not exactly difficult:

#ifndef Pump_h
#define Pump_h

class Pump
{
  public:
     Pump(char pin_, char dir_);
     void pumpstep(void);
     uint32_t ts;
     void run()
  private:
    char pin;
    char dir;
};

#endif

Pump::Pump(char pin_, char dir_)
{
    pin = pin_;
    dir = dir_;
    ts = 0;
    pinMode(pin, OUTPUT);
    pinMode(dir, OUTPUT);
}

void Pump::pumpstep(void) {
     Serial.println("Stepping");
}

void Pump::run() {
    if (millis() - ts >= 100) {
        ts += 100;
        pumpStep();
    }
}

Then in loop call:

myPump.run();

You can, of course, just combine run() and pumpstep() into one single function.


ISR executes even though an interrupt is not triggered I am trying to implement a function queue scheduling system. INT1 is connected to a button and int1task causes an LED to flash.

typedef void (*funcptr)(void);
TPrioQueue *queue = NULL;

void int1ISR() {
  if (debounce(&int1time)) // Checks if the interrupt is caused by switch bouncing
    enq(queue, (void*) int1task, 1);
}

Next, I execute the function in loop() by:

typedef void (*funcptr)(void);

void loop(){
  funcptr func = (funcptr) deq(queue);
  if (func != NULL)
    (*func)(); // Stuck in a loop
}

For some reason, the LED keeps flashing even though I have not pressed the button. Why does this happen?

When I remove the line below, the ISR works properly.

enq(queue, (void*) int1task, 1)

The relevant sections of the code:

int debounce(unsigned long *debTimer) {
  unsigned long tmp = *debTimer;
  unsigned long currTime = millis();

  if ((currTime-tmp) > 500){
    *debTimer = currTime;
    return 1;
  }
  else
    return 0;
}

// Flashes LED at pin 6 five times at 2 Hz
void int1task(){
  for(int i=0; i<5; i++){
    digitalWrite(6, HIGH);
    delay(250);
    digitalWrite(6, LOW);
    delay(250);
  }
}

void setup() {
  pinMode(6, OUTPUT);
  attachInterrupt(1, int1ISR, RISING);
  Serial.begin(115200);
}

Code I used for the queue

Here is the schematic I am using:

After checking the queue functions that you use in your sketch, I see there is no protection against concurrent accesses in the enq and deq functions, which is a must-have if you use any of these functions from within an ISR.

I would suggest the simplest changes to these functions as follows:

void enq(TPrioQueue *queue, void *item, int priority)
{
    TPrioQEntry *newEntry=(TPrioQEntry *) malloc(sizeof(TPrioQEntry));

    if(newEntry != NULL)
    {
        newEntry->item=item;
        newEntry->prio=priority;
        newEntry->prev=NULL;
        newEntry->next=NULL;

        // Protect against concurrent accesses starting here
        uint8_t sreg = SREG;
        cli();
        if(queue->head==NULL)
            queue->head=newEntry;
        else
        {
            // Find insertion point.

            // First special case: Item at head has lower priority
            if(queue->head->prio > newEntry->prio)
            {
                // Insert item at the start of the queue.
                newEntry->next=queue->head;
                queue->head->prev=newEntry;
                queue->head=newEntry;
            }
            else
            {
                // Find your insertion point
                TPrioQEntry *trav= queue->head;

                while(trav->next!=NULL && trav->prio < newEntry->prio)
                    trav=trav->next;

                newEntry->prev=trav;
                newEntry->next=trav->next;
                if(trav->next != NULL)
                    trav->next->prev=newEntry;

                trav->next=newEntry;
            }
        }

        queue->itemCount++;
        // Protect against concurrent accesses stops here
        SREG = sreg;
    }
}

void *deq(TPrioQueue *queue)
{
    // Protect against concurrent accesses starting here
    uint8_t sreg = SREG;
    cli();
    // Return NULL if queue is empty
    if(queue->head == NULL)
    {
        // Protect against concurrent accesses stops here
        SREG = sreg;
        return NULL;
    }

    void *ret=queue->head->item;
    TPrioQEntry *tmp=queue->head;

    if(queue->head->next!=NULL)
        queue->head->next->prev=NULL;

    queue->head=queue->head->next;
    free(tmp);

    queue->itemCount--;

    // Protect against concurrent accesses stops here
    SREG = sreg;

    return ret;
}


Creating a clock using Arduino I want to make a large clock, 16 inch x 7.5 inch, which will display dd Month yyyy.
What would be the best way to do this?
Does Arduino have a built in clock, and I'd just need logic to turn on/off LEDs on a display that already has dd Month yyyy? Do such displays exist which I can connect to Arduino?

If you are willing to go the “barebones” route, you can turn an
ATmega328P (the MCU at the heart of the Arduino Uno) into a very
accurate RTC by hooking a watch crystal to it's clock pins. Given proper
calibration, you can get an accuracy of a few seconds per year.

This would require some coding though, and is not as straightforward as
using an off-the-shelf RTC. C.f.
this answer for the details.


Arduino LED Dimmer Proportionate to Ambient Light I am trying to get an LED dimming reversely proportionate to natural light level in a room.
So as the sun rises, the LED dims and vice-versa.
I am using the standard LDR+ 10k Ohm resistor divider, an LED, and an Arduino Leonardo Clone.

The issue is, regardless of the values I adjust in map(), it does not change the flickering rate or brightness of the LED.
What range of map shuold I be using?

The LED ought to shut off while the LDR takes a reading.
I have two variations of the code; one uses PWM, the other simulates PWM using delay()

Here are my sketches:

/set pin numbers
//const won't change
const int ledPin = 1;   //D1 the number of the LED pin (OR to MOSFET input wire for controlling high power LED
const int ldrPin = A0;  // A0 the number of the LDR pin
//10K ohm resistor as voltage reference.

void setup() {

  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);  //initialize the LED pin as an output
  pinMode(ldrPin, INPUT);   //initialize the LDR pin as an input
}

void loop() {
  digitalWrite(ledPin, LOW); //Shutoff LED invisibly rapid to get a reading of the ambient light without the LED on
  int ldrStatus = analogRead(ldrPin);   //read the status of the light sensor value
  // KEEP LED OFF TIME BASED ON AMBIENT LIGHT LEVEL...
  int dim2 = map(ldrStatus, 0, 1023, 500, 0); //OFF FOR UP TO 0.50 seconds.
  digitalWrite(ledPin, HIGH);
  delay(dim2);

   }

Sketch two:

//set pin numbers
//const won't change
const int ledPin = 1;   //D1 the number of the LED pin (OR to MOSFET input wire for controlling high power LED
const int ldrPin = A0;  // A0 the number of the LDR pin
//10K OHM resistor as voltage reference.

void setup() {

  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);  //initialize the LED pin as an output
  pinMode(ldrPin, INPUT);   //initialize the LDR pin as an input
}

void loop() {
  digitalWrite(ledPin, LOW); //Shutoff LED invisibly rapid to get a reading of the ambient light without the LED on
  int ldrStatus = analogRead(ldrPin);   //read the status of the light sensor value
  int dim = map(ldrStatus, 0, 1023, 255, 0);     // scale it to use it with the LED (value between 0 and 255)
  digitalWrite(ledPin, dim);               //Flash LED at that rate to adjust brightness.

   }

For certain Arduino models, the PWM pins are different. For the iteaduino lite, a usable PWM pin is pin D5.

Here is the code updated to use D5 instead of D1, which lacks PWM abilities:

//set pin numbers
//const won't change
const int ledPin = 5;   //D5 PWM the number of the LED pin (OR to MOSFET input wire for controlling high power LED
const int ldrPin = A0;  // A0 the number of the LDR pin
//10K OHM resistor as voltage reference.

void setup() {

  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);  //initialize the LED pin as an output
  pinMode(ldrPin, INPUT);   //initialize the LDR pin as an input
}

void loop() {
  digitalWrite(ledPin, LOW); //Shutoff LED invisibly rapid to get a reading of the ambient light without the LED on
  int ldrStatus = analogRead(ldrPin);   //read the status of the light sensor value
  int dim = map(ldrStatus, 0, 1023, 0, 255);     // scale it to use it with the LED (value between 0 and 255)
  analogWrite(ledPin, dim);               //Flash LED at that rate to adjust brightness.
  Serial.println(dim);
   }

There is still flickering, but that is to be expected. map() ranges can be adjusted to set when the LED will be fully off or on.

It is still unclear how to allow the light sensor to take a reading while the LED is OFF, then power back on rapidly enough to not have a visible flicker.
If anyone has thoughts on that, it would be appreciated!
Thanks everyone for helping.


I2C on non I2C pins, possible? I have 2 I2C devices that uses the same address. One of them is the DS3231 RTC. I use this library for the DS3231. I dont want to mess with the other one cause it is way more complicated then this one.:

#include <DS3231.h>

http://www.rinkydinkelectronics.com/library.php?id=73

Then, there is an object declaration for the real time clock:

DS3231  rtc(SDA, SCL);

I wounder if I can change that to:

DS3231  rtc(A0, A1);

I've seen the library but I haven't understand it yet (duh... I'm so stupid!). But is it possible to use an other pair of pins for I2C communication.

Note that I've already tried to use the soft I2C library but I really want to avoid it because it is just too much. If it is the final solution then so be it.

You can change the address of the GY-521 by pulling the AD0 pin to Vcc. After that the address will be 0x69 instead of 0x68.


How does the ssd1306 handle different screen sizes? I noticed that if I have two SSD1306 displays, the 128x32 display will lose every other row if written in x64 mode, and the 128x64 display will show blank horizontal lines if written in x32 mode. How does this physically work, and can I expect this to be a reliable feature?

I would have thought that half the screen would get cut off somehow, but it appears that it must interlace the data instead (which seems a lot more complicated). Yet there's also some sort of configuration to the driver chip to make it do this (It seems to be the 0xDA command, but I'm not clear how/why it has these options).

Can I expect that, at least if I use the same driver library, that using the wrong screen will always have this behavior? I was planning to use it to help the user detect what screen they have.

The SSD1306 does not handle different sizes, it's ever only handling it's maximum size 128x64. But one can decide to only use less pins of the driver for a smaller display.

The SSD1306 has 128 segment pins, which activate the current column, so that the states of the 64 common signal pins will be used by the display for that column. For smaller display sizes there are just some pins of the SSD1306 left unconnected. They get set like all the other pins, but they are not connected to anything, thus the information gets lost.

For accommodating that, the library sets the pixel according to the size by not using every second row (aka common signal) for half size displays. That's why you get horizontal black lines, when using a 128x64 display with the library in 128x32 mode. The library thinks, that every second row is not connected either way and thus sets these pixels to black. The 128x32 display is loosing every second row when used with the library in 128x64 mode, because every second row is not connected.

Note, that nor the library neither the SSD1306 know about how the display is connected. You need to tell the library this, by setting the mode, and it will control the SSD1306 accordingly. So there is no feedback about the display, that you could use.

  Can I expect that, at least if I use the same driver library, that using the wrong screen will always have this behavior?

Yes and no. The library handles it this way, because it is the common way to leave out every second pin for displays of half size. But it comes down to the manufacturer to decide this. We cannot guarantee, that nobody will ever connect the SSD1306 in a different way to a display.

For most manufacturers you will be good. If you simply plan to provide the displays for your user, so that they can change them their selves, you can be sure. If the user should be able to use her/his own display, purchased anywhere else, you might run into problems (though rarely).


Arduino relay. risks? I just started working with arduinos recently. I'm really interested in working with relays. I would like to turn a desk lamp on and off using an ios app or a web browser button. I have no experience working with relays but I would love to experiment with relays in order to turn a desk lamp on or off based on an external switch in like an IOS app or a browser.

I am wondering what are the risks in relays with arduino ? I would like to switch a desk lamp on or off using a relay but I don't really understand the risks with creating a desk lamp powered using a wall socket and turned on or off using a arduino relay module . What is the worst case scenario if I screw up ? What are the risks and precautions I should take while working with relays and trying to build a relay controlled desk lamp?

I live in an apartment and I am trying to make sure that my entire building does not lose electricity or I don't screw up the electricity in my unit. What are protective measures that I can take to minimize damages while working on this project?

Basic safety precautions:

Always fully unplug the lamp before working on any wiring, even when working with the low-voltage side of things.
Invest in a proper enclosure and follow the rules of insulation and earthing: if the enclosure is metal or has exposed metal they have to be earthed. If it is plastic it is insulated and there is nothing to earth (plastic is best).
Use nylon bolts etc when situated near mains voltages.
A proper relay module with good screw terminals is recommended.
Do not tin your mains wires when screwing them into a terminal block
Do your mains wiring with your left hand in your pocket (an old electrician's trick: if you should get a shock the path to earth is down the side of your body and through your foot. If you have your left hand touching something the path to earth could well be straight across your chest, through your heart, and down your other arm, killing you. It has saved my life a few times...)
Keep mains voltages and low-voltage areas separate. Cable ties and self-adhesive nylon cable tie pads are great for keeping cables where they should be.
Shield any exposed mains connections from touch. Things like the underside of the relay module where the terminal blocks are soldered, that sort of thing.
Don't let the relay module wave around loosely. Keep it well secured in the enclosure.

I'm sure I could find more tips if I tried :)

The main thing to remember is that mains electricity is deadly and should be treated with the utmost respect.

For the ultimate in safety though you could get an isolating transformer. This separates your work from the main supply and means that the only way of getting a shock is by actively touching both outputs of the transformer at once - something you're not really likely to do - and even then it's usually a very localised path for the electricity (through a finger or two).

Adding an ELCB to the lamp's plug (if it is earthed) can be a good precaution while you are working too - and making sure the socket is connected to a ring main that is protected by an RCD is pretty much essential (in the UK it is the law that all ring mains are protected by an RCD - I would hope the same is the case where you live).


Help Connecting MicroSD Module with Arduino Uno I am Trying to make a MicroSD .wav file player using Arduino Uno. I have ordered a MicroSD Card Module from ebay today.

Product Link : http://www.ebay.in/itm/Micro-SD-Card-Module-SD-Storage-Board-TF-Card-Memory-Shield-SPI-For-Arduino-/161696480012?

As You can See in the Product Image, there is not mentioned on the PCB that which Pin Is ground or VCC Or any other SPI pin.
1. How will I identify the correct pins of the MicroSD Module ?
2. How can I connect a speaker to arduino to play .wav files. Is Amplifier neccessary? I am weak when it comes to electronics.

I have listened that when I connect a Capacitor in series with speaker, it will boost the output volume. There will not be music but only voice recordings in .wav files. I want to listen it clearly only.

OMG, what a vile listing!

Anyway, I think you'll probably find they are in the order listed in the description when the connector is facing south. It's probably printed on the rear of the board which they don't show.

That is, from left to right, GND, VCC, MISO, MOSI, SCK, CS.

As for connecting a speaker, that depends if you want low quality (PWM) audio, or high quality (DAC) audio.  The latter requires the addition of an audio shield, most of which have an SD card slot on them already thus alleviating the need for this SD card breakout board.

For the former there is a library and instructions here: http://www.hackerspace-ffm.de/wiki/index.php?title=SimpleSDAudio


Control time without delay() Arduino For the last couple of day I've been trying and failed many times just to not use the delay() funtion in Arduino. I have to admitted that my coding skill are extremely bad.

What i trying to do is:
If button is pressed:
Motor A and B move for 1 second at slow speed == > Motor A keep moving but at fast speed and motor B stop.
else:
Motor A and B both stop.

I managed to wrote the code by using delay function for that 1 second. However i got no idea how to do it WITHOUT DELAY() there will be sensor reading as well at the same time, i cant afford that 1 second delay of sensor reading).

Here is my code:

int dir1PinA = 2;
int dir2PinA = 3;
int speedPinA = 9; // Needs to be a PWM pin to be able to control motor speed

// Motor 2
int dir1PinB = 4;
int dir2PinB = 5;
int speedPinB = 10; // Needs to be a PWM pin to be able to control motor speed

int button = 6;

void setup() {  // Setup runs once per reset
// initialize serial communication @ 9600 baud:
Serial.begin(9600);

//Define L298N Dual H-Bridge Motor Controller Pins

pinMode(dir1PinA,OUTPUT);
pinMode(dir2PinA,OUTPUT);
pinMode(speedPinA,OUTPUT);
pinMode(dir1PinB,OUTPUT);
pinMode(dir2PinB,OUTPUT);
pinMode(speedPinB,OUTPUT);

// Define button pin
pinMode(button,INPUT);

}

void loop() {
  if( button == LOW){           // if button is pressed
    // Motor A (move slow) and B  moving
    analogWrite(speedPinA, 100);//Sets speed variable via PWM
    digitalWrite(dir1PinA, LOW);
    digitalWrite(dir2PinA, HIGH);
    analogWrite(speedPinB, 255);
    digitalWrite(dir1PinB, LOW);
    digitalWrite(dir2PinB, HIGH);
    delay(1000);

    // After 1 second Motr A (move fast)and B stop every time button pressed
    analogWrite(speedPinA, 255);//Sets speed variable via PWM
    digitalWrite(dir1PinA, LOW);
    digitalWrite(dir2PinA, HIGH);
    analogWrite(speedPinB, 0);
    digitalWrite(dir1PinB, LOW);
    digitalWrite(dir2PinB, LOW);
  }
  else
  {
    // Both motor not moving
    analogWrite(speedPinA, 0);//Sets speed variable via PWM
    digitalWrite(dir1PinA, LOW);
    digitalWrite(dir2PinA, LOW);
    analogWrite(speedPinB, 0);
    digitalWrite(dir1PinB, LOW);
    digitalWrite(dir2PinB, LOW);
  }
}

Please point me out the direction or give me an example of code. And I have already try the Blinkwithoutdelay Arduino example but it does not work for this case.

Very much appreciated.

If button is pressed: Motor A and B move for 1 second at slow speed == > Motor A keep moving but at fast speed and motor B stop. else: Motor A and B both stop.

I would do a quick state machine:

  STATE / button released: do nothing;
      STATE / button pressed: run motors a+b;
      STATE / run motor a+b: run motor a+b; if 1 second has passed, advance to just run motor a;
      STATE / run motor a: run motor a at fast speed and stop motor b.

fairly easy to code as well.


Can an accelerometer be used to detect heart sound? I've recently come across accelerometer and how it can detect electrical mechanical response. I was wondering can it be used to detect heart sound? Lets say you attach the device close to your chest (where heat lies) and detect sounds and send it over bluetooth? LPMS-B2 OEM

An accelerometer detects motion (acceleration) of the physical device.

If you can convert the sound of the heart into physical vibration then the accelerometer can detect that vibration.

Converting the tiny amount of sound the heart produces into a large enough vibration for the accelerometer to detect would entail (realistically) using a microhone, amplifier, and speaker, with the accelerometer attached to the speaker cone.

So while theoretically yes, you can do it, practically why would you when you can just use the microphone and amplifier that you'd be using anyway. It's pointless.

So in reality: no, you can't.


Running multiple tasks at once For a school project we're working on a wearable device to track people's movement and heart rate. We use an Arduino Pro Mini with a heartbeat sensor and an accelerometer. The wearable device uses Bluetooth to send data, but only once or twice a day to save battery.

The problem we currently face is having the Arduino keep track of the accelerometer data while also reading the heartbeat sensor on a select interval. See the pseudo-code underneath. In what way (preferably without implementing too many libraries) could we merge these two loops so the accelerometer is read non-stop while keeping an interval (of about 30 minutes) between the heart beat readings? Any input would be greatly appreciated and if needed I can provide additional information.

void loop() {
// Heartbeat sensor loop
  while (array is not full) {
    delay(30 minutes);
    heartbeatArray[index++] = readHeartbeat();
  }
  sendData_Bluetooth(heartbeatArray);
  emptyArray();
// End of heartbeat sensor loop

// Accelerometer loop
  while (true)
    if (readAccelerometerData > limit)
      sendAlert();
// End of accelerometer loop
}

What you want to do is rather easy task, you just need to forget about delay() function. When writing some more complex programs using it is generally a bad idea, as it blocks code execution, so you won't get any sensor readings, communication, anything. Instead try something like this:

unsigned long delay1 = 100;
unsigned long delay2 = 1800000; //30 minutes in miliseconds
unsigned long t1, t2;

void setup() {
  t1 = t2 = millis();
}

void loop() {
  if(millis() - t1 > delay1) { //this will be executed every delay1 ms
    // do one part of code
    t1 = millis();
  }

  if(millis() - t2 > delay2) { //this will be executed every delay2 ms
    // do another part of code
    t2 = millis();
  }

  // here insert the code that should be executed as frequently as possible
  // (every loop passage)
}

There is also a nice Arduino library called TaskScheduler, that basically does the same thing: periodically executes different functions with different time intervals.


Arduino timer interrupts for PID I'm working on a robotics project where an arduino nano is acting as the motion controller. I'm trying to use a trapezoidal motion profile generator and PID loop to follow that profile, but I found out the motion was quite jerky and I assumed it's because both the motion profile and the PID run at the same speed (10ms loop using timer interrupt library)
#include <TimerOne.h>
void setup() {
  Timer1.initialize(10000);
  Timer1.attachInterrupt(Compute);
}

now I want to use two seperate loops, one running at the same 10ms interval for the profile generation and one running at 1ms for the PID (I'm not sure if the motors can actually act that quickly, but I can adjust the timings a bit), this way the PID has about 10 loops to get to the desired position accurately, reducing the jerky motion.
I'm not sure how I can set up two different interrupts using that library or by setting the flags like TCCR0A to generate the desired interrupt timers.
Here's the actual "Compute" function in case it's relevant (there are some bugs regarding the direction and it's using two different methods for generating the profile, also I'm changing it so don't think it matters, but just in case it does, I posted it)
void Compute(){
  int dir;
  if (setPoint > target){
    dir = 1;
  } else if (setPoint < target){
    dir = -1;
  }
  if (mode == 1) {
    target += v*dir;
    if (abs(setPoint - target) <= turningPoint){
      v -= acceleration;
    } else {
      if (v < maxV){
        v += acceleration;
      }
    }
    if (abs(target) >= abs(setPoint)){
      target = setPoint;
      mode = 0;
      v = 0;
      Serial.println("Finished!");
    }
    #ifdef DEBUG
      printDebug();
    #endif
  } else if (mode ==2){
    target += v*dir;
    if (phase == 1 and v < reachableV){
      v += acceleration;
      if (v >= reachableV){
        phase = 3;
        v = reachableV;
      }
    } else if (phase == 3){
      v -= acceleration;
      if (v <= 0){
        target = setPoint;
        mode = 0;
        v = 0;
        phase = 0;
        Serial.println("Finished!");
      }
    }
    #ifdef DEBUG
      printDebug();
    #endif
  }
  error = target- pos;
/////////////////////////////////////////////////
  PID_P = kp * error;
  if (PID_P > outMax) PID_P = outMax;
  if (PID_P < outMin) PID_P = outMin;
/////////////////////////////////////////////////
  if (abs(error) < 50){
    PID_I += ki * error * sampleTime;
  } else {
    PID_I *= 0.8;
  }
/////////////////////////////////////////////////
  PID_D = kd * (pos - lastPos) / sampleTime;
  if (PID_D > outMax) PID_D = outMax;
  if (PID_D < outMin) PID_D = outMin;
/////////////////////////////////////////////////
  output = PID_P - PID_D + PID_I;
  if (output > outMax) output = outMax;
  if (output < outMin) output = outMin;
/////////////////////////////////////////////////
  lastPos = pos;
  if (output < 0){
    digitalWrite(DIR,1);
  } else {
    digitalWrite(DIR,0);
  }
  analogWrite(PWM,abs(output));
/////////////////////////////////////////////////
}

p.s: I'm most likly going to use the PID library instead of trying to write my own like I currently have the code.

Just use a single 1ms timer interrupt and count them. Every 10 interrupts do both things.
void interruptHandler() {
   counter++;

   // do things that happen every 1ms

   if(counter == 10) {
      // do things that happen every 10ms
      counter = 0;
   }
}


Best way to store files on Arduino I was wondering what is the best way to store files on Arduino, I've seen that is possible using the SD Card module but I only want like 2/3 file texts so having a whole SD Card for that sounds a bit overkill, is there any other way to store files like that?

Cheers!

If you want files, then you need a filesystem. The only simple to use and reliable things on an Arduino that have a filesystem are SD cards or USB memory sticks through the USB Host Shield.

However, most of what people think they want to store in "text files" is actually data that can better be stored in other ways. Using text to store numeric values that only the Arduino will ever see is pointless - store it as numeric values.

The most convenient place to store such values (if you don't have lots of them) is in the internal EEPROM.

If you have more than a few values you can use an external EEPROM or serial Flash chip to store larger amounts of data.

Anything more than that, though, and SD card rapidly becomes the most cost effective method.


Ok to Connect 2.9V Stepper to 3.3V pin? So I have a stepper motor that's rated for 2.9V and 0.8A and I connected it to a L9110 Driver and I wanted to drive it with my arduino. But I don't know how to drive it safely without damaging the motor. I am using the stepper.h library and thought of connecting it to 3.3V pin on the Arduino but I am a bit concerned.. is it Ok to power it with 3.3V if no then What can I do?
Edit: the L9110 module I am using is a dual H Bridge.
Edit2: I was Indead Powering the Stepper and the Module directly from the arduino.. luckily the arduino survived.
Edit3: So I didn't have a 3V power supply so I used a Voltage Divider with a 9V battery and connected the L9110s module with the battery (after its voltage divided) and the module powers on.. but when the arduino starts driving the stepper the module's led starts Flickering instead of staying on and the stepper doesn't turn... I don't know what is the problem.

Motors draw a LOT of current compared to CMOS circuits.
The 3.3V output on most Arduinos can only provide a very small amount of current. The Arduino Uno, for example, says it only provides a max of 50mA from its 3.3V regulator. Your motor driver probably needs >10X more than that.
The overload protection on the Arduino's voltage regulator will probably kick in and cause it to shut off. It might take a while to cool down before 3.3V output comes back. I've heard that the protection on Arduino knockoffs doesn't always work, so you could also fry the voltage regulator if you try to draw too much from it.
Bottom line: Don't do that.
Get a high current supply for your motor driver.


How to prevent optocoupler to activate when resetting the arduino? From various example on how to use optocouplers ( eg 4N25)  I gathered that they
work in inverted way meaning that for the optocoupler to output a signal,
the input LED must be OFF.

This is very easy to process by code as I just need to use digitalWrite LOW
instead of digitalWrite HIGH to activate the output of the optocoupler.

My problem is that when I reboot the arduino, the optocupler LED goes OFF and thus activate the ouput of the optocoupler for a few seconds until the code is loaded on the arduino.

How can I prevent this behavior ? Should I connect the optocoupler in a non inverted way ? ( And if so how ? ). Should I use an inverter ?

The Fairchild datasheet for 4N25 shows this diagram:

describing the (or 'an') operation of the device. If this is how yours is operating, and if the input side is connected between an output pin and ground, then yes, on reset, the LED will go out and the switched output will go high. If you connect the device's input between the pin and +5v, the LED will light on reset, taking the switched output low. Plus, the switched output will now have the same sense as the Arduino output pin: i.e., digitalWrite(PIN, HIGH) will turn the switched output on, and vice-versa.


What kind of antenna should i use for my esp8266 module? I have an esp8266 module and i want to increase its range by adding an antenna to it. What kind of antena should i use. Can i use an antenna from a RC car remote?

You must use a WiFi (2.4 GHz) antenna. From the picture in your post, you have one of the esp8266 modules with a "built-in" antenna implemented via traces on the PCB. You cannot add an external antenna without removing the old one first, and even that will be very dodgy - you'll likely render your esp8266 useless for any purpose.

Instead, you could get an esp8266 that is made for connecting an external WiFi antenna. See the Wikipedia article for details. It specifically mentions model # ESP-WROOM-02U as having a connector for an external antenna.