How to make a button work a second time in my code? I am making a security system, and the alarm starts when the button gets pressed. If i turn the alarm off by the serial communication, and want to turn it on again using the button, it will only let the alarm go on for about 0.5 seconds. Does someone see the mistake i'm making, and can help me? Thanks in advance!

const int ledrood = 11;
const int ledgroen = 12;
const int buttonPin = 2;
int buttonState = LOW;

int statePin = LOW;
const int trigPin = 9;
const int echoPin = 10;
long duration;
int distance;
bool alarm = false;
int speakerPin = 8;
String Message = "";
String NMessage = "";
String Command = "";
int index = 0;
bool Bericht = true;

void PlaySong()
{
  tone(speakerPin, 4699, 500);
  delay(1000);
  tone(speakerPin, 4699, 500);
  delay(1000);
  tone(speakerPin, 4699, 500);
  delay(1000);
  tone(speakerPin, 4699, 500);
  delay(1000);
  tone(speakerPin, 4699, 500);
  delay(1000);
  tone(speakerPin, 4699, 500);
  delay(1000);
  tone(speakerPin, 4699, 500);
  delay(1000);
}
void alarmaan()
{
 alarm = true;

  digitalWrite(ledrood, HIGH);
  digitalWrite(ledgroen, LOW);
  digitalWrite(trigPin, LOW);

 }

void AlarmUit() {
  Serial.println("alarm uit");
  alarm = false;
  digitalWrite(ledgroen, HIGH);
  digitalWrite(ledrood, LOW);
  digitalWrite(trigPin, LOW);

 }
void setup() {
  pinMode(ledrood, OUTPUT);
  pinMode(ledgroen, OUTPUT);
  pinMode(buttonPin, INPUT);
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input
  Serial.begin(9600);
 }
String Doorsturen() //Methode om te communiceren via de serial monitor
{
 if (Serial.available() > 0)
  {
   char readChar = (char) Serial.read();
   NMessage = NMessage + readChar;
  }
  if (NMessage.startsWith("#") && NMessage.endsWith("%"))
  {
   index = NMessage.indexOf("%");
   NMessage = NMessage.substring(1, index);
   Serial.println(NMessage);
   Command = NMessage;
   NMessage = "";
   Bericht = true;
  }
  else if (NMessage.endsWith("%"))
 {
   NMessage = "";
 }
 return Command;
}
void loop() {
 Message = Doorsturen();
 int buttonState = digitalRead(buttonPin);
 digitalWrite(trigPin, HIGH);
 digitalWrite(trigPin, LOW);
 duration = pulseIn(echoPin, HIGH);
 distance = duration * 0.034 / 2;
 Serial.print("Distance: ");
 Serial.println(distance);

 if (alarm == false) {
   digitalWrite(ledgroen, HIGH);
 }

 if (Message == "alarm_off")
 {
   AlarmUit();
   Message = "";
 }
  if (Message == "1234")
  {
   AlarmUit();
   Message = "";
  }
  if (Message == "aan") {
   alarmaan();
   Message = "";
   }

  if (alarm == false) {
   if (buttonState == HIGH) {
    delay(50);
    while (digitalRead(buttonPin) == HIGH) {}
    alarmaan();
    Serial.println("fout");
   }
  }

  if (distance < 10 && alarm == true) {
   PlaySong();
  }

 if (alarm == true) {
   if (buttonState == HIGH) {
    delay(50);
    while (digitalRead(buttonPin) == HIGH) {}
    alarmaan();
    Serial.println("Test");
   }

 }
}

The problem is that Message = ""; doesn't actually do anything, because the next time doorsturen is called, it will just load the previous command from the command variable. I'd suggest having the doorsturen function only return the command once, and not on consecutive calls.

String Doorsturen() //Methode om te communiceren via de serial monitor
{
  Command = "";
  if (Serial.available() > 0)
  {
    char readChar = (char) Serial.read();
    NMessage = NMessage + readChar;

    if (NMessage.startsWith("#") && NMessage.endsWith("%"))
    {
      index = NMessage.indexOf("%");
      NMessage = NMessage.substring(1, index);
      Serial.println(NMessage);
      Command = NMessage;
      NMessage = "";
      Bericht = true;
    }
    else if (NMessage.endsWith("%"))
    {
      NMessage = "";
    }
  }
  return Command;
}

see comment in the code

if (alarm == false) {
  if (buttonState == HIGH) {
    //here you set alarm to true
  }
}

...

if (alarm == true) { //now this if statement is true
  if (buttonState == HIGH) {//also buttonState is still high, because it's never updated after you set alarm to true

  }

to fix do this

if (alarm == false) {
   if (buttonState == HIGH) {
    delay(50);
    while (digitalRead(buttonPin) == HIGH) {}
    delay(50);// this is to negate switch bounce, on release, from interfering
    buttonState = false;// add this line
    alarmaan();
    Serial.println("fout");
   }
  }


How to send sensor data from Arduino through NRF24L01 to Raspberry Pi I am able to send text from the Arduino wirelessly to RPi.  I am now trying to send the sensor data I'm measuring to the Pi.  This is what I have below:

int moisture = A0;
int temp = 3;

//Skipping the setup and reading of the values

radio.write(&moisture);
radio.write(&temp);

//the above couple lines is where I start having trouble.  The RPi will spit output a seemingly random selection of numbers

As you haven't said or shown which NRF24L01 library you are using, one can't say for sure what the problem is, but in some NRF24 implementations, the write() method accepts (or requires) a second parameter, len, giving the number of bytes to be sent.  If the library you're using doesn't require that parameter, it could be defaulting it to some value, or could be treating the buffer as a string, to be terminated with a null byte.

Either of those cases could produce erratic results.

Instead of leaving off the second parameter, specify it.  For example:

radio.write(&moisture, 2);
radio.write(&temp, 2);


Is it permissible to connect 3.3V powered devices to the 5V I2C bus? I have several devices on the I2C bus:

RTC DS3231SN
TMP100 temperature sensor
EEPROM 24LC256

All devices are powered by 3.3V. The voltage on the I2C bus is 5V.

Question:
Is the voltage difference on the bus and device power normal?

There are 3.3V devices that have 5V-tolerant inputs; that may be the case for your devices, but I would not risk it. Use a level converter designed for I2C, such as https://www.adafruit.com/product/757. Or you can make your own; https://cdn-shop.adafruit.com/datasheets/an97055.pdf explains how such a level converter works. Use a BSS138 if you are comfortable with soldering SMT components; otherwise use a 2N7000.


Arduino Interrupt Debouncing I have an issue with debouncing.
I am using a MCP23017 as an I/O-extender with an Arduino. This uses I2C to communicate with each other.

A variable amount of switches is connected to the MCP23017 (0-16 switches). On change of the inputs, an interrupt is generated and the Arduino captures this on rising edge. So whenever a button is pushed or released, an interrupt is generated.

Now I'm confused as how I should debug them. One option would be to set a delay after an interrupt (of let's say 50 ms), before turning the interrupts back on. This could have an issue however, since multiple inputs are connected to the same interrupt line.

Another option is to have a timestamp or something for the last time each switch was changed, and check if the time difference is big enough, otherwise ignore the next pulse. The problem with this is that it uses quit some resources as I have limited memory and there can be up to 8 extenders (so 8 * 16 = 128 inputs).

What is the most efficient way to handle these interrupts with debouncing?

Add debouncing circuitry if you can; it's not that difficult.


Arduino Wire.onReceive(handler) It says in the description of the function:

  Registers a function to be called when a slave device receives a transmission from a master.

So when does it exactly called? I guess it's not been called for each byte, but its the meaning of receiving transmission from the master. Does it called for each byte? When the master use transmissionBegin? transmissionEnd?

It is called at the end of the reception of the entire packet - i.e., when the slave receives the final STOP bit.  It is passed the number of bytes received (which is the number of bytes you requested since I2C has no way of being able to work out if it is actually receiving real data - see here) as the only parameter so you know how many bytes you can then read from the internal buffer without overflowing it.


My Arduino UNO turns LED ON forever when I connect it to my Laptop My Arduino UNO Board keeps the LED light turned on forever whenever I connect it to my PC. And, when I try to upload even a sample sketch, it says avrdude: stk500_recv(): programmer is not responding.

How can I fix this error?

When you connect the device, if you hear the Windows "found device" sound, then you need to check your COM port driver, as it's very likely that the COM port number may have changed. On your Desktop or in File Manager, right click "This PC" or "My Computer", and select "Manage" from the submenu.  That will bring up the Computer Management console. On the left, select "Device Manager".  That will bring up your list of devices. In the list look for "Ports (COM & LPT)".

If you don't see, "Ports", then click "View" and check "Show hidden devices".  If this is the only Arduino that you've ever used, you should only see one listing. Make note of the COM Port Number the driver is using. It's possible that the port number may have changed since you first used the device. Plug-n-play will do this if you plug the cable into a different USB port that may be using a different USB controller, etc.

Then in your Arduino IDE, click "Tools", then expand "Boards" and select "Arduino/Genuino UNO" board, then re-click "Tools", and hover over "Port", and select the port number that is assigned to the Port that you found in Device Manager.

If that doesn't work, then you may have a problem with your driver.  Some of the "cheap chinese board" use a different FTDI chipset, so the plug-n-play windows driver may not work. In that case, the manufacturer should point you to the correct driver. Download their provided driver, then you can update the driver in Device Manager.


Understanding WiFi.printDiag(Serial) I am having difficulty with setting up websockets using the Arduino IDE with an ESP8266 ESP8266 Websockets problem and I have added WiFi.printDiag(Serial) to the main loop of my code. The Output I get (with my comments added) is

14:34:03.325 -> DIAGNOSTIC INFO   Debug Comment I added
14:34:03.325 ->
14:34:03.325 -> Mode: AP          Presume this means ESP is in AP mode
14:34:03.325 -> PHY mode:N        XXX
14:34:03.325 -> Channel: 1        Presume this means AP is on channel 1
14:34:03.325 -> AP id: 0          XXX
14:34:03.325 -> Status: 255       XXX
14:34:03.325 -> Auto connect: 1   XXX
14:34:03.325 -> SSID (0):         XXX
14:34:03.325 -> Passphrase (0):   XXX
14:34:03.325 -> BSSID set: 0      XXX

The AP is setup and I can see it in WiFI Analyser on my phone.
Is there a reference somewhere that explains the lines with XXX in them, or can
someone suggest meanings? Thanks

Mode: AP

In access point mode. Can also be STA or STA+AP for Station or dual role modes.

  PHY mode:N

Physical interface mode. At the moment it's in 802.11n mode. Depends on the AP you are connecting to if any.

  Channel: 1

Which WiFi channel you are communicating on

All the following are meaningless in AP mode. They only pertain to STA mode:

  AP id: 0

Internal ID of the access point you are connecting to, if any.

  Status: 255

Connection status

  Auto connect: 1

Automatically connect to an access point.

  SSID (0):

Name of the access point currently connected to.

  Passphrase (0):

Password used to connect to the current access point

  BSSID set: 0

BSSID (kind of like the MAC address) of the access point connected to.

As you can see, much of it is meaningless for access point mode, since it mostly is to do with connecting the ESP8266 to an existing network.  In AP mode there's not a lot of debugging information you can get - "is it running?" is really all there is.


Is Arduino Mega useing one buffer or multiple buffers? So Arduino Mega has Serial, Serial1, Serial2, Serial3.

However, does those Serial lines use the same buffer? or four independent ones? i.e. are they truly receive single independently, or actually some sort of software sharing? How will that affect the coding?

Actually there are 2 buffers per Serial hardware interface: The hardware buffer, that is 1 byte (per direction of data transfer). The Serial library then transfers this byte in an extra buffer (64 bytes big) from an ISR. Every hardware Serial interface (Serial and Serial1 to 3 on the Mega) has it's own hardware buffer.

Then the Serial library is implemented as a class. Every hardware Serial interface get's it's own instance of this class, including the 64 byte buffer.

So the hardware and the memory is completely seperated. The only thing, what they share, is the CPU time for servicing the interrupts, which is no problem, until you are doing somehting very wrong with interrupts.


Documentation for creating a Board Manager profile for the Arduino IDE I'd like to write a Board Manager profile for some Arduino boards that I have. So far I've struck out on finding the documentation on the format and contents of the files. Does anybody know where I can find it?

Documentation is kind of scarce.

Basically there are two aspects to what you want - the board definition and the board manager JSON file.

The first describes the board to both the IDE (entry in boards.txt) and to the API software (definition of what pins are what and what peripherals are where, etc).  The latter is in the file pins_arduino.h.

Then there is the JSON file that describes the whole package to the board manager and is what allows people to download the boards.txt and pins_arduino.h files (and anything else you may require) from your website.

As there is not much documentation you are best off taking an existing set of files that are close to what you want and modifying them.  Most of the time it will be a slight tweak such as re-ordering a few pins in some arrays, or changing the name of the board and maybe an upload command or baud rate setting.


How to filter or eliminate earths magnetic field readings around 3D Magnetic sensor? Im using the SparkFun MAG3110 3D sensor:
https://www.sparkfun.com/products/12670

My application is essentially to make a contactless "magnetic joystick" using a local magnet for accurate and constant 3D position sensing in x, y, x planes of a local magnet, exactly like in this video (skip to 1:06):
https://www.youtube.com/watch?v=CO6y6bjFfmY

The magnet I'm using is constant, so i'm trying to figure out a way to remove the earths magnetic field noise around the sensor so it cannot interfere with the sensors readings as if the earths magnetic field was virtually not present.

I've already written code that takes about 50 samples in each plane (x,y,z) and takes the average of each of the planes and outputs those readings minus the average offset values (Ex: Serial.print(x-xavg), Serial.print(y-yavg), Serial.print(z-zavg)). I did this to basically "zero out" the earths magnetic field, like zeroing a weight scale.

That wasn't really effective and results were not anywhere near constant after introducing and removing the local magnet, over and over again.

I've considered:

a low pass filter
sensor fusion using my gyroscope/accelerometer module
(I know that sensor fusion is usually used to calibrate the Magnometer to be a more accurate compass, but is there anyway to use this technique to  eliminate the earths magnetic field?)
using data from http://www.magnetic-declination.com/ to tie into my calculations to offset the readings
Using an electromagnet module to output the earths magnetic field inverted continuously in an attempt to cancel out the earths magnetic field
trying to find a whole new sensor completely that does not have a low enough sensitivity to even detect earths magnetic field

So my questions are:

Is there any way to do this?
Are any of my considerations practical or possible?
Are there even any 3d magnetic sensors on the market that do NOT pick up the earths magnetic field? - I've contacted SparkFun, Arrow, ST, and other companies about this exact question and never really get a sure answer on this question specifically?
if not, how was this man in the video able to reduce noise around his sensor? - He shows visually that his sensor is starting to filter out noise, saying that he's using an "adaptive averages" algorithm and links to some code, but I was unable to see/find that and don't understand how he is doing that?

Earth magnetic field is pretty constant. In your measurements it will show up as an offset that you could subtract, but of course it will change if the sensor rotates.

Whatever measurement noise you see certainly doesnt' come from Earth. Either your setup is close to a local source of magnetic radiation (inductors, wires with high alternating current), or your sensor picks up noise from its power supply. Put your sensor away from high currents, power it with batteries and see how much noise you'll get in that case.


How to define function/macro so it is accesible throughout various cpp files I recently came across this nice SerialPrint() implementation:

void StreamPrint_progmem(Print &out,PGM_P format,...)
{
  // program memory version of printf - copy of format string and result share a buffer
  // so as to avoid too much memory use
  char formatString[128], *ptr;
  strncpy_P( formatString, format, sizeof(formatString) ); // copy in from program mem
  // null terminate - leave last char since we might need it in worst case for result's \0
  formatString[ sizeof(formatString)-2 ]='\0';
  ptr=&formatString[ strlen(formatString)+1 ]; // our result buffer...
  va_list args;
  va_start (args,format);
  vsnprintf(ptr, sizeof(formatString)-1-strlen(formatString), formatString, args );
  va_end (args);
  formatString[ sizeof(formatString)-1 ]='\0';
  out.print(ptr);
}

#define Serialprint(format, ...) StreamPrint_progmem(Serial,PSTR(format),##__VA_ARGS__)
#define Streamprint(stream,format, ...) StreamPrint_progmem(stream,PSTR(format),##__VA_ARGS__)

I want to use it in my more complex projects to save precious RAM space.

This works really well when I have just one *.ino file where I'm using the SerialPrint() function.
When I try to use it in my more complext projects, which consist of a central *.ino files and several .cpp/.h files (mostly one cpp/h pair per class).
The problem is if I put the code below into the *.ino file, it will not be known inside any of the *.cpp files. The compiler is not complanining, but I'm never seeing the serial output of my code.

Any ideas how to fix it?
I've tried putting this code in a central global.cpp/h file which I include everywhere, but it does not seem to work (no output on serial).

Thanks in advance!-

Have you thought of turning it into a small library?

libraries/StreamPrint/StreamPrint.cpp:

#include <StreamPrint.h>

void StreamPrint_progmem(Print &out,PGM_P format,...)
{
  // program memory version of printf - copy of format string and result share a buffer
  // so as to avoid too much memory use
  char formatString[128], *ptr;
  strncpy_P( formatString, format, sizeof(formatString) ); // copy in from program mem
  // null terminate - leave last char since we might need it in worst case for result's \0
  formatString[ sizeof(formatString)-2 ]='\0';
  ptr=&formatString[ strlen(formatString)+1 ]; // our result buffer...
  va_list args;
  va_start (args,format);
  vsnprintf(ptr, sizeof(formatString)-1-strlen(formatString), formatString, args );
  va_end (args);
  formatString[ sizeof(formatString)-1 ]='\0';
  out.print(ptr);
}

libraries/StreamPrint/StreamPrint.h:

#include <Arduino.h>

extern void StreamPrint_progmem(Print &out,PGM_P format,...);

#define Serialprint(format, ...) StreamPrint_progmem(Serial,PSTR(format),##__VA_ARGS__)
#define Streamprint(stream,format, ...) StreamPrint_progmem(stream,PSTR(format),##__VA_ARGS__)

Then in your code, wherever you want to use it:

#include <StreamPrint.h>

You can read more about writing libraries here: http://www.arduino.cc/en/Hacking/LibraryTutorial


How to cast float into four bytes? I'm trying to save GPS coordinates to an EEPROM.

In this example I feed it the latitude of 56060066 as the argument float x

void writeFloat(unsigned int addr, float x)
{
  byte seriesOfBytes[3];
  *((float *)seriesOfBytes) = x;
  // Write all four bytes.
  for(int i = 0; i < 4; i++)
  {
    i2c_eeprom_write_byte(0x57, addr, myFloat.bytes[i]); // Write byte to EEPROM
    Serial.println(seriesOfBytes[i],BIN);  // Debug line
  }
}

I'm expecting to receive the following four bytes from the serial print:

00000011
01010111
01101000
10100010

Instead I'm getting these:

00101000
11011010
01010101
01001100

I've tried changing all sorts of parameters, but can't seem to find the problem. Can anyone spot the issue?

You are getting exactly what you said you want. 4 bytes representing the number in float format.

What you are expecting to get, is 4 bytes representing the number in big-endian integer format.

Using Majenkos solution for casting, you need to change the types and reverse the for loop for big-endinaness.
I also used int32_t because the size of the int is 16-bit (2-byte) on the Arduino Uno (and other ATMega based boards) and on the Arduino Due it's 32-bit (4-byte). Its better to define the exact int in this case.

union {
    int32_t ival;
    byte bval[4];
} int32AsBytes;

void writeInt32(unsigned int addr, int32_t x)
{
    int32AsBytes.ival = x;
    for(int i = 3; i >= 0; i--) // reverse for big-endian
    {
        i2c_eeprom_write_byte(0x57, addr, myFloat.bytes[i]); // Write byte to EEPROM
        Serial.println(int32AsBytes.bval[i], BIN);  // Debug line
    }
}


Can I control analog IO pins using Yun Linux 2 days back I bought Arduino Yun. I'm able to flash Led on 13 pin. And I'm able to flash Led on Bread board connected to A0. I'm able to run linux commands.

Now I want control A0 pin using Linux/Python program. Is this possible? I read many documents. But I didn't find thing related to this.

How I  can flash the LED using Linux programs?

There are several libraries which will do this for you. Basically, you should upload a special sketch onto the Arduino, which listens to the serial port, and performs the I/O that the Linux chip requests. Libraries which can do this are

Firmata
Autobahn
LininoIO


inconsistent digital output on simple code so im new on arduino coding, and i made this code, where i input from serial monitor and then use it as a command for digital write. the problem is, sometimes the code work perfectly but then when i input 4, both D3 ad D4 is high and that also happens in D5 and D6. but its inconsistent, and i also print the 'out' value and also which digital pin is high to make it easier.
byte b;
int out;
int D3 = 3;int D4 = 4;int D5 = 5;int D6 = 6;int D7 = 7;int D8 = 8;
void setup() {
  Serial.begin(9600);
  pinMode(out, OUTPUT);
  digitalWrite(D3, LOW);digitalWrite(D4, LOW);digitalWrite(D5, LOW);digitalWrite(D6, LOW);digitalWrite(D7, LOW);digitalWrite(D8, LOW);

}

void loop() {
  while (Serial.available() == 0) {}
  b = Serial.read() - 48;
  out = b;
  Serial.print("\n Out is ");
  Serial.println(out);
  digitalWrite(out, HIGH);
  delay(600);
 if (digitalRead(D3) == HIGH)
{
   Serial.print("D3 HIGH");
}
 if (digitalRead(D4) == HIGH)
{
   Serial.print("D4 HIGH");}
 if (digitalRead(D5) == HIGH)
{
   Serial.print("D5 HIGH");
}
 if (digitalRead(D6) == HIGH)
{
   Serial.print("D6 HIGH");
   }
 if (digitalRead(D7) == HIGH)
{
   Serial.print("D7 HIGH");
}
 if (digitalRead(D8) == HIGH)
{
   Serial.print("D8 HIGH");
   }
  digitalWrite(out, LOW);
  delay(1000);

}

does anyone know why this happens? or can anyone recommend another method to do what im tryinng to do? thank you guys!!!

If I look at the first 5 lines:
byte b;
int out;
int D3 = 3;int D4 = 4;int D5 = 5;int D6 = 6;int D7 = 7;int D8 = 8;
void setup() {
  Serial.begin(9600);
  pinMode(out, OUTPUT);

You see that pinModeout, OUTPUT)uses a variableoutwhich is not initialized (it's only declared inint out`'.
I assume D3 to D8 are all output pins, so you have to replace the last line with:
pinMode(D3, OUTPUT);
pinMode(D4, OUTPUT);
pinMode(D5, OUTPUT);
pinMode(D6, OUTPUT);
pinMode(D7, OUTPUT);
pinMode(D8, OUTPUT);

Also, since you are using all pins in the same way, I suggest you use two variables: startPin and endPin. Then you can use a for loop to iterate through all pins. Also

always initialize variables.
use '0' instead of 48 when you convert from a byte value to a character (since you don't need to know the ASCII value of '0').

I don't have an Arduino compiler at hand, but it should look something like:
byte b = 0;
int out = 0;
const byte startPin = 3;
const byte endPin = 8;

void setup() {
  Serial.begin(9600);
  for (byte pin = startPin; pin <= endPin; pin++)
  {
      pinMode(pin, OUTPUT);
      digitalWrite(pin, LOW);
  }
}

void loop() {
  while (Serial.available() == 0) {}
  b = Serial.read() - '0';
  out = b;
  Serial.print("\n Out is ");
  Serial.println(out);
  digitalWrite(out, HIGH);
  delay(600);

  ...

However, from here you are using the pins as INPUT pins. You cannot change those on the fly, you might change them manually (by using pinMode(pin, INPUT)), but it does not seem normal to switch input and output pins, so maybe you should explain what you are intending with your application.


Two stepper one by one I want to run two stepper motor one after the other
Stepper1  has to5 rotation
And stepper 2  has to move 1rotation Here is the code

Stepper 1 is nema 34
And stepper 2 is nema 24

#include <AccelStepper.h>

// Define a stepper and the pins it will use
AccelStepper stepper1 (1, 3, 2); // Defaults to 4 pins on 2, 3, 4, 5 mortor (A)
AccelStepper stepper2 (1, 5, 4); // Defaults to 4 pins on 2, 3, 4, 5 motor (B)

long Steps_For_Distance1 = 3; // 3cm
long Steps_For_Distance2 = 5; // 5cm
long currentPos = 0;
long targetPos = 200;
long targetPos_Reverse = -200;
long Motor_Speed1 = 50;
long Motor_Speed2 = 400;
long Motor_Speed3 = 800;
int Op_Sw = 0;
const int buttonPin = 2;     // the number of the pushbutton pin

const int ledPin =  13;      // the number of the LED pin

// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status

void setup()
{
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);

  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
}

void checkStepper1_For_DT(AccelStepper &astepper)
{
  if (astepper.distanceToGo() == 0)
  {
    // Random change to speed, position and acceleration
    // Make sure we dont get 0 speed or accelerations
    astepper.setCurrentPosition(currentPos);
    astepper.moveTo(targetPos);
    astepper.setSpeed(Motor_Speed1);
    astepper.setAcceleration(100);
  }
}
void checkStepper2_For_360(AccelStepper &astepper)
{
  if (astepper.distanceToGo() == 0)
  {
    // Random change to speed, position and acceleration
    // Make sure we dont get 0 speed or accelerations

    astepper.moveTo(targetPos);
    astepper.setMaxSpeed(Motor_Speed2);
    astepper.setAcceleration(100);
  }
}
void PatternToBeLooped_For_Cycle1()
{
  int count = 0;

  for (count == 0; count <= 5; count ++)
  {
    checkStepper1_For_DT(stepper1);
    stepper1.runSpeedToPosition();
  }

  checkStepper2_For_360(stepper2);
  stepper2.runSpeedToPosition();
}
void loop() {
    PatternToBeLooped_For_Cycle1();
  }

I had run the code
But it didn't work
Both motor are running at same time

Please help me
Where I made mistake

Thank you in advance

I had try by delay (1000);
But
Still they  both stepper are moving  at a same time and get delay at same time

I looked into the source of the AccelStepper library here, which may be your library or one similar to it. The function runSpeedToPosition() does not block until the desired position is reached. Instead inside the function you see code that executes a step, when the right time (according to millis()), calculated through the speed, is reached, else it will return false. You are supposed to call this function very often while the motor moves. This enables you to drive more than one motor simultaneously with different speeds.

Since you don't want to drive both motors at the same time, you have to loop, until the first motor have reached the desired position; then doing the same with the second motor. Try something like this:

void PatternToBeLooped_For_Cycle1()
{
  int count = 0;
  for (count == 0; count <= 5; count ++)
  {
    checkStepper1_For_DT(stepper1);
    while(stepper1.currentPosition() != stepper1.targetPosition()) stepper1.runSpeedToPosition();
  }

  checkStepper2_For_360(stepper2);
  while(stepper2.currentPosition() != stepper2.targetPosition()) stepper2.runSpeedToPosition();
}

Note: With this change the function PatternToBeLooped_For_Cycle1() blocks the execution of the loop function, until the motors have done their movement. To avoid this you can use an if-statement, which executes the code for stepper1 or stepper2 depending on the millis() function. This works the same way as the BlinkWithoutDelay example in the Arduino IDE.


Send array of Infrared codes I'm having a bit of a problem when sending IR Codes stored in variables. I swear I had this convered up already. I don't actually know the reason why I can't use variables in the first place. I receive data over Bluetooth Serial Com and I'm using an Arduino ProMicro as ISP for the Arduino Nano.

I want to send data over Serial comm and then send an IR code to the end receiver.

Here is some of the code():

#include <IRremote.h> // IR Library - Encode/Decode

void irSerial( char SerChar[] ) // Receive array of characters

char IDChar[]={'s', 'i', 'u'}; // List of Serial Char to identify position
String HRD[]={"Power", "Input", "ChaUp"}; // Action referece
byte CodesIR[]={0x61A0F00F, 0x61A048B7, 0x61A050AF}; // IR Codes
int IRArray = 2; // Size Of The array

if ( SerChar[0] == 's' ) { // Compare Array
  for (int CountIR = 0; CountIR <= IRArray; CountIR++){ // Loop through array
    if ( SerChar[0] == IDChar[CountIR]) {
       bluetooth.println(HRD[CountIR]); // Send String in array - Works
       SendIR.sendNEC(CodesIR[CountIR],32); // Send IR in array position
    }
  }
}
}

There's not a problem with the current expression as it compiles normally and I can send serial data normally finishing the function. If I replace the array CodesIR[CountIR] for example with 0x61A0F00F then it works perfectly.

How can I use a variable instead? Can anyone help? It is the byte CodesIR[] ??

I used a Switch/Case and it works but I prefer a variable/array and less useless coding. Thanks for understanding!

Well as usual it was something stupid (-__-) I changed the byte array for long and it worked perfectly.

Here is the complete code working():

#include <IRremote.h> // IR Library - Encode/Decode

void irSerial( char SerChar[] ) { // Receive array of characters

    char IDChar[]={'s', 'i', 'u'}; // List of Serial Char to identify position
    String HRD[]={"Power", "Input", "ChaUp"}; // Action reference
    long CodesIR[]={0x61A0F00F, 0x61A048B7, 0x61A050AF}; // IR Codes
    int IRArray = 3; // Size Of The array # Edit

    if ( SerChar[0] == 's' ) { // Compare Array
      for (int CountIR = 0; CountIR < IRArray; CountIR++){ // Loop through array # Edit
        if ( SerChar[0] == IDChar[CountIR]) {
           Serial.println(HRD[CountIR]); // Send String in array - Works
           SendIR.sendNEC(CodesIR[CountIR],32); // Send IR in array position
        }
      }
    }
}


Human circuit trigger The main idea is to create trigger which can be switched on by touching 2 plates on opposite walls. And these should be performed by few peoples holding each other hands.

Obviously human body has big resistance so I couldn't just connect these plates to ground and to one of Arduino pins.

There is a toy that do almost what I what (see it there). But I haven't found any information about how to create it by myself.
Do you have any ideas how to create it?

I just tried it (using my own method), and I got it working with very good sensitivity (should be fine for two people) using a TIP102 Darlington transistor and some resistors. Here is what I did:

R1, the 1M pulldown resistor on the first pin of the Darlington is necessary to keep the light off when nobody is touching the wires. Without this, the light will turn on and off frantically.

R2, the 1k resistor keeps the Arduino from draining too much current (since that would be bad for the pin) in the case that your A0 is in OUTPUT mode and set to LOW.

R3 keeps the LED (or in my case, an AC relay connected to an actual light) from draining too much current from the Arduino. Note: The LED leads may be backward (reverse polarity) in the provided diagram.

Here is the code:

// I release this code under the standard MIT licence;
// (in addition to whatever StackExchange implies);

const short triggerThreshold = 10;// Lower is more sensitive;

void setup() {
  pinMode(A0, INPUT);
  pinMode(A5, OUTPUT);
  digitalWrite(A5, LOW);
  delay(1);
}

void loop() {
  short value = analogRead(A0);
  digitalWrite(A5, (value > triggerThreshold) ? HIGH : LOW);
  delayMicroseconds(10000);// 10ms;
}

Note the triggerThreshold setting in the code. If you want more sensitivity, try changing the 10 to a 5. I just tried it, and it becomes extremely sensitive, yet it still appears to reliably stay off when I don't touch it. Naturally if you use large plates for touching, electrostatic in the air could set it off, so you may need to change this number to be higher to make it less sensitive, depending on your setup.


How do I receive more that 64 bytes with Arduino I am using QtSerialPort to send and receive data from Arduino. I am sending more than 64 bytes (125, 220, more), I receive the data with Arduino, and trying to sending back the same data, but Arduino sending only 64 bytes in its response. Then I am thinking that the problem is with Arduino buffer. I am trying to clear the data but without result.

Here is my Arduino code:

void loop() {
    if (Serial.available() > 0) {
        int i = 0;
        delay(500);
        int size = Serial.available();
        while (i < size)
            buffer[i++] = Serial.read();

        Serial.print(buffer);
        //delay(500);
        int j = 0;
        while (j < size)
            buffer[j++] = '\0';
        //while (Serial.available()) Serial.read(); I tried it
        //Serial.flush();   Also tried it, but nothing.
    }
}

Instead of blocking the loop for 500 ms, you should be actively
reading the data as it comes. Otherwise the internal buffer of the
Serial object will overflow after only 64 bytes are received.

Here is an example that copies the incoming bytes into a larger buffer
(256 bytes) and, upon receiving an end-of-line character, echoes
back the whole line.

void loop() {
    static char buffer[256];
    static size_t pos;              // position of next write

    while (Serial.available() && pos < sizeof buffer - 1) {

        // Read incoming byte.
        char c = Serial.read();
        buffer[pos++] = c;

        // Echo received message.
        if (c == '\n') {            // \n means "end of message"
            buffer[pos] = '\0';     // terminate the buffer
            Serial.print(buffer);   // send echo
            pos = 0;                // reset to start of buffer
        }
    }
}


How to put arduino in sleep mode? I need to put arduino in sleep mode. I did not find the library avr/sleep.h . From where to download it.

avr/sleep.h is part of the compiler. You don't need to download it.

There are other libraries that act as a wrapper to it to make life easier:

https://github.com/lowpowerlab/lowpower
https://github.com/rocketscream/Low-Power


Arduino Firebase ESP8266 Connection I am working on a project that needs data to be stored in cloud db so that I can access the data in a mobile application. For database I have considered Firebase. I am following the following link. But when i try to install the libraries i am getting No such file or directory found errors for memory, queue, Firebase.h, vector, functional, utilities (not all but different packages shows different errors). I tried downloading different packages from github. But still had the errors. Where can I find the correct working program? Thanks in advance.

The usual Firebase library for esp8266 is https://github.com/FirebaseExtended/firebase-arduino.

And there is some new Firebase library in Library Manager in IDE. The "More info" link leads to https://github.com/mobizt/Firebase-ESP8266


Cant upload arduino code when ESP8266-01 module is connected I'm using this tutorial to connect my ESP8266-01 WiFi Module to Arduino UNO with Arduino IDE v. 1.8.13.

It works and the module can connect to my WiFi.
However, when I try to upload my code, it says:
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x30
What could be the problem, since when I remove the reset pin it uploads the code, but now the WiFi goes down.

Your problem is that there are two ways of wiring your ESP-01 module to the Arduino:

Wired so the PC has access to it and the Arduino is effectively disabled, and
Wired so the Arduino has access to it

You are wired in configuration 1 at the moment whereby the Arduino is effectively turned off and the USB connection goes direct to the ESP-01. When you try and upload code to the Arduino it's the ESP-01 that the computer is talking to, not the Arduino.
You need to wire it in configuration 2. In this configuration the TX/RX pins of the ESP-01 connect to any two pins of the Arduino except pins 0 and 1, and the RESET pin is not connected to anything. Then you can't talk to the ESP-01 through the serial monitor - instead you have to write code for the Arduino that uses SoftwareSerial to communicate for you.
There are many many tutorials online about communicating between the Arduino and the ESP-01.


How to connect Arduino to headphone jack? I would like to connect a headphone jack to my Arduino and make it as an output. I mean I would simply send some simple beeps.

I know that there is a breadboard friendly headphone jack, but I don't know how to wire it. I really don't know if I can simply connect the Arduino to the headphone jack, or I will need some resistors, etc. Will I need some voltage measurements?

Also, can I do this simply by connecting the parts of the jack ( right, left, GND) to the Arduino?

So could you please help me with this?

This project connects the headphones directly to a digital pin.  Here is the schematic:

I would, however, be more cautious and add a limiting resistor.  The output of an Arduino pin should be limited to 20mA as stated here. So, using

  V=I*R

  5 = 0.02 * R

  R = 5 / 0.02

  R = 250ohms

So I would add a ~250ohm resistor in series with the head phone.  Especially if I were debugging my code.  That is, in case I accidentally left the output pin high for an extended period of time.

The head phones should have some DC resistance.  If the sound is not loud enough you might measure that DC resistance of the head phones and subtract it from the 250 ohm resistance calculated above and use a limiting resistor of that value instead.


Where can I find out how to make a hex file for arduino firmware? I have followed this tutorial on flashing my Arduino R3 to turn it into a "USB keyboard", but the article doesn't explain how the hex works, it's just for granted. Where can I learn about how to make my own hex file so that I can learn how to make my Arduino mimic any USB device?

The HEX file is simply a translated version of the AVR executable, which is in turn a translated version of AVR source code.

There are many tools available for turning (compiling) AVR source code into an AVR executable, including but not limited to the Arduino IDE, Ino, AVR-GCC, and Atmel Studio. Note that all four tools will compile the code the same way, since AVR-GCC is used under the hood by the other three.

avr-g++ -mmcu=atmega328 source.cc -o executable

Once you've compiled the code, you can use avr-objcopy to extract the appropriate sections from the executable into HEX files for programming into the flash and EEPROM.

avr-objcopy -j .text -j .data -O ihex executable executable.hex

You can then use AVRDUDE to upload the various HEX files to the target device.

avrdude -c arduino -P /dev/ttyUSB0 -b 19200 -p m328 -U flash:w:executable.hex:i

Note that the USB libraries in Arduino/Ino and AVR LibC are limited; you will need to use Atmel Studio if you want full USB capabilities.


Recording of sensor results but only retain the last 3 sets of data I'm doing a radiation-seeking robot, which will find the source of the radiation autonomously. But in this case, my robot will spin 180 degrees to detect the nearest source of radiation and 1 set of data recorded is considered for every 180 degree turn. However I think it is not possible to store all of the data in the Arduino due to a storage problem.

Therefore is there any function in Arduino that can only record the last 3 sets of data from the sensor? For example, after it has recorded 3 sets of data, the fourth set data could be recorded by overwriting the first set of data. I would be really grateful if anyone could help me with this.

PS if possible I don't want to install an SD card in my Arduino.

It depends how big the data is... if one data set is 100 bytes, you can spend 300 bytes of internal SRAM memory.

What you also can do if the memory usage is too big, is to add external SRAM, like the 32K256 which has 32 kb (kilobyte) SRAM or the 23LC1024 which has 128 kb SRAM.

To loop through the data sets you can easily use a so called 'ring buffer'.

You allocate 3 sets of data (like 3 arrays of a byte array), and an index. the index you increase after every use like:

index = (index + 1) % 3

External SRAM normally uses SPI to communicate with, and you can read/write it by a single byte, multiple bytes or page (typically 128 to 512 bytes). You cannot directly store variables in it, but you have to manually keep track where you store what ... for 3 data sets this will be relatively easy. You can even calculate (beforehand) the number of data sets that can be stored and cycle through them as needed.


strtok() command with Serial communicaton After i take char* variable from serial communication, i use strtok to split variables with " ". But when i do that it acts like there is " " after every character. i dont know why. How can i fix this ?

void setup() {
  Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
  char* a = "The quick brown fox jumped over the lazy dog.";
  char* c = a3;
  char* b;
  b = strtok(c, " ");
  while(b != NULL){
        Serial.println(b);
        b = strtok(NULL, " ");
      }
}
void loop() {
}

outcome :

The
quick
brown
...

this parse code works perfectly. until i take it from serialports. Serial code here. like this :

..

#include <SoftwareSerial.h>
#define bRSerial 9600
#define bRmY 9600

char vD[45];
int i = 0;

SoftwareSerial mySerial(10, 11); // RX, TX

void setup() {
  Serial.begin(bRSerial);
  while (!Serial) {
    ;
  }
  mySerial.begin(bRmY);
}
void loop() {
if (mySerial.available()) {
    //Serial.write(mySerial.read());
    vD[i]=mySerial.read();
    i++;
    if(i=46){
      char* a = vD;
      char* b;

      b = strtok(a, " ");
      while(b != NULL){
        Serial.println(b);
        b = strtok(NULL, " ");
      }
      i=0;
    }
  }
}

...outcome

T
h
e
q
u
i
c
k
b
r
o
w
...

so isthere a way to fix this ? i need to get it from serial and parse with " ". THANK YOU SO MUCH.

only a syntax typo. the condition should be if ( i == 46 ) {

if this is not only a strtok test, the you do not need strtok. read in char c, and if c == ' ', print vD and reset i to 0

and I do not see where you set the terminating 0 of vD a.k.a. a


Button state changes despite not being connected? I have written some code to test buttons that I want to use

const int buttonPin1 = 1;
const int buttonPin2 = 2;
const int buttonPin3 = 3;
const int buttonPin4 = 4;
const int buttonPin5 = 5;
const int buttonPin6 = 6;

int buttonState1 = 0;
int buttonState2 = 0;
int buttonState3 = 0;
int buttonState4 = 0;
int buttonState5 = 0;
int buttonState6 = 0;

void setup() {
  Serial.begin(9600);
  pinMode(buttonPin1, INPUT_PULLUP);
  pinMode(buttonPin2, INPUT_PULLUP);
  pinMode(buttonPin3, INPUT_PULLUP);
  pinMode(buttonPin4, INPUT_PULLUP);
  pinMode(buttonPin5, INPUT_PULLUP);
  pinMode(buttonPin6, INPUT_PULLUP);
}

void loop() {
  buttonState1 = digitalRead(buttonPin1);
  buttonState2 = digitalRead(buttonPin2);
  buttonState3 = digitalRead(buttonPin3);
  buttonState4 = digitalRead(buttonPin4);
  buttonState5 = digitalRead(buttonPin5);
  buttonState6 = digitalRead(buttonPin6);

  if (buttonState1 == HIGH) {
    Serial.println("button1 press");
  }
  if (buttonState2 == HIGH){
    Serial.println("button2 press");
  }
  else if (buttonState3 == HIGH){
    Serial.println("button3 press");
  }
  else if (buttonState4 == HIGH){
    Serial.println("button4 press");
  }
  else if (buttonState5 == HIGH){
    Serial.println("button5 press");
  }
  else if (buttonState6 == HIGH){
    Serial.println("button6 press");
  }
  else{

  }
}

I have tried with the buttonPins being A0-A5 as well, and whenever I try to run the code, it always spams out that button 5 and button 2 are being pressed, despite me not pressing them, as well as when I remove the buttons entirely, and pull out all the wires from it, it still prints it out. Even when I re-run the code. How can I fix this?

You are setting button pins with INPUT_PULLUP mode, which activates internal resistor connected to supply voltage. In this way, your input pins are in state HIGH if disconnected or if button is not pressed.

To fix this, you need to compare your button state with LOW. Also, make sure that one side of your buttons is connected to ground. Then, pressing the button will connect the button to ground and will bring your button pin to LOW.


Managing configurations via EEPROM by writing it with the hex file I've been looking into I2C bootloaders for an ATTINY coprocessor on a board I'm developing, and I ran into a bit of a snag. I have the need to detect what board the main processor's code is running on, since there are a number of write-only peripherals I can't probe for presence or configuration (WS2812-series LEDs and a SSD1306 screen, among a few others), and I was going to manage that via a configuration blob stored on the ATTINY.

Unfortunately, this was coded into the firmware, and pushing out any sort of update for the coprocessor would then require that I build, label, and provide each version, and then have the user choose the correct one.

So, the solution would seemingly be EEPROM, since that can be set to persist over programming attempts (there's even a fuse setting to keep it, although in the other case how the AVR knows if it's been programmed [in the era of bootloaders] I'm not sure).

The issue is now that I need a way to set the EEPROM configuration when I create the original program, and then have future updates not touch it. The existing way is that I add a stub to my code that checks if there's a config and sets it (unfortunately per-unique-board-design, so I'd need lots of different copies again) and then never touches it again. Future firmwares could then just not include any stub at all.

However, this annoys me, especially since if something goes wrong it could mess up the EEPROM.

Does anyone know of a way to use a ICSP programmer to set EEPROM, ideally as part of the firmware upload?

I am using a usbasp with PlatformIO to do the chip programming, so I should have enough access on the first burning to change the EEPROM. Does anyone know how I could add in an EEPROM configuration to go with the flash one?

Some thoughts I have had:

Somehow modify/append the hex file to include data that goes to EEPROM and then burn it
Add a script to PlatformIO that lets me edit/compile/upload/whatever to EEPROM (I do not speak Python, so I'd need help)
Use an existing feature of PlatformIO/the build process/the AVR toolchain to set an EEPROM configuration (I have to suspect there is one, but Googling does not seem to have pointed one out)
Somehow do this with AVRDude

AVRDUDE can program EEPROM. I usually do this as part of the firmware burn - the operator can pick which config block should go into the board while running the programming cycle. In some cases the EEPROM info is even generated programmatically during the cycle to contain dynamic info like unit serial number and commision date.

Here is an example command line that will program the file filename.hex into EEPROM...

avrdude -c stk500v2 -P COM6 -p atmega328p -U eeprom:w:filename.hex:i

The AVRDUDE write command (U) has many options to do almost anything you want...

-U memtype:op:filename[:format]
Perform a memory operation. Multiple ‘-U’ options can be specified in order to operate on multiple memories on the same command-line invocation. The memtype field specifies the memory type to operate on. Use the ‘-v’ option on the command line or the part command from terminal mode to display all the memory types supported by a particular device. Typically, a device’s memory configuration at least contains the memory types flash and eeprom. All memory types currently known are:
(...)
MEMTYPE:
eeprom
The EEPROM of the device.
(...)

OP:
w
read the specified file and write it to the specified device memory

(...)

FILENAME:
The filename field indicates the name of the file to read or write. The format field is optional and contains the format of the file to read or write. Possible values are:

i
Intel Hex

s
Motorola S-record

r
raw binary; little-endian byte order, in the case of the flash ROM data

e
ELF (Executable and Linkable Format), the final output file from the linker; currently only accepted as an input file

m
immediate mode; actual byte values specified on the command line, separated by commas or spaces in place of the filename field of the ‘-U’ option. This is useful for programming fuse bytes without having to create a single-byte file or enter terminal mode. If the number specified begins with 0x, it is treated as a hex value. If the number otherwise begins with a leading zero (0) it is treated as octal. Otherwise, the value is treated as decimal.

a
auto detect; valid for input only, and only if the input is not provided at stdin.

d
decimal; this and the following formats are only valid on output. They generate one line of output for the respective memory section, forming a comma-separated list of the values. This can be particularly useful for subsequent processing, like for fuse bit settings.

h
hexadecimal; each value will get the string 0x prepended.

o
octal; each value will get a 0 prepended unless it is less than 8 in which case it gets no prefix.

b
binary; each value will get the string 0b prepended.

The default is to use auto detection for input files, and raw binary format for output files.

Note that if filename contains a colon, the format field is no longer optional since the filename part following the colon would otherwise be misinterpreted as format.

As an abbreviation, the form -U filename is equivalent to specifying -U flash:w:filename:a. This will only work if filename does not have a colon in it.

Any of these files types can be used depending on what kind of data you are writing to the EEPROM and how it is being generated.

More info here...
https://www.pololu.com/docs/0J67/5.8


Use of two external power sources for a power cell - charger I have a SparkFun Power Cell - LiPo Charger/Booster and want to use the external 5V charge capability. Now my question:

Can I directly hook up a DC jack (for a 5V power supply) and an inductive charging circuit to the external charge pins of the Sparkfun Power Cell LiPo Charger Module or should I use a slide switch so that either the power supply via the dc jack or the inductive charging module can power the Sparkfun Power Cell LiPo Charger? I prefer the first option, but I have concerns that the inductive charging module is damaged when for example the power supply is hooked up...

Have anybody experience with an similar setup?
Thank you in advance for your answers.

A switch would be the best way of preventing damage, but you could also use diodes to prevent power flowing back to the PSU or Inductive circuit.

I tried something similar once using transistors to prevent both circuits operating at the same time, but never managed to get it to work.  You could practice any solutions on a breadboard with some LEDs.


ESP32 Hardware Serial Flow control and full espressif/arduino-esp32 support I have a similar issue. I want to use the ESP32 with RS485.
I have used the Arduino  and this works well assigning pins, but it seems not to allow full use of the UART.

I see the new uarts in the ESP32 can support the direction control (RTS) of the direction pin and there is actually a hardware RS485 mode.
See the repository that the board package is based on:
https://github.com/espressif/arduino-esp32

Then
https://github.com/espressif/arduino-esp32/tree/master/tools/sdk/include/driver/driver
uart.h

This shows we can actually have full hardware flow control, so no more guessing delays for controlling the DIR lines or getting interrupts when the send buffer is empty in order to know when to switch back to receive.

I found using board manager this did not all get installed, so I followed some tutorials on how to install it manually.
The board either doesn't appear at all, or I can't reference "uart.h".

Any ideas or examples?
Thanks,
Mark

your example was of great help solving the problem of driving RTS properly, thanks a lot!
I found a small bug in the code example, the data buffer is allocated in the loop() function instead of setup() and as a result, eventually the memory leak will fill-up all available memory.
Ciao!
Alessandro


SH1106 - Transferring long buffer via SPI I am using an SH1106 and am creating my own driver for it. Nearly everything is doing great with about 2/3ms send time using transfer16. I did notice however that I can use transfer with a buffer and length to give a 1ms display time; something that'd be extremely useful.

For reference before here is the datasheet:
http://support.technologicalarts.ca/docs/Components/OLED13-SPI/SH1106.pdf

So the working solution is this:

SPI.beginTransaction(settings);
//
for (int page = 0; page < 8; page++)
{
    digitalWrite(DC, LOW);
    SPI.transfer(0xB0 + page);
    SPI.transfer(0x02);
    SPI.transfer(0x10);
    digitalWrite(DC, HIGH);

    for (int column = 0; column < 128; column += 2)
        SPI.transfer16(buffer[(page * 128) + column]);
}
digitalWrite(DC, LOW);
//
SPI.endTransaction();

This for each of the 8 pages writes the 128 bytes 2 at a time. I want to write the 128 bytes in a single call. This would be something like this:

SPI.transfer(buffer + (page * 128), 128);

This however sort of inverts the display. It literally turns every pixel on for some reason and I can't figure out why. I am just using a few bytes set to 255 for testing and with the original method this works perfect.

Am I using the call wrong? Is there a limit to the buffer size I could use, I haven't really seen anything about that at the moment. I tried changed the pointer arithmetic but wasn't successful. I tried moving the 128 bytes into a temporary location and use that but still nothing.

Obviously this isn't major and maybe I could somehow improve the transfer in other ways but if you have any advice I'd love to have it

----- EDIT -----

I have had some luck now with using the transfer with buffer method when I changed the page datatype to a uint8_t. It also caused a few more issues however and I am not sure what is causing them.

Firstly with a fast display rate the display inverts itself once again with all pixels on.
With a delay between display calls, it works! But after a few seconds those pixels slowly go away, something I have never experienced before.

Here is the edited code:

SPI.beginTransaction(settings);
//
for (uint8_t page = 0; page < 8; page++)
{
    SPI.transfer(0xB0 + page);
    SPI.transfer(0x02);
    SPI.transfer(0x10);

    digitalWrite(DC, HIGH);
    SPI.transfer(buffer + (page * 128), 128);
    digitalWrite(DC, LOW);
}
//
SPI.endTransaction();

It's hard to explain whats actually happening. But without a large delay between the calls of the buffer transfer method the screen freaks out and will maybe invert completely if it's too often. Even with the large delay the pixels randomly vanish over time, something I have never actually seen.

The 2 byte send method doesn't have any of these problems. No delay will work fine.

You seem to have understood the following but just for clarification:

transfer16(uint16_t word), as the name implies, shifts 16bits/2bytes instead of just 8bits/1byte like transfer(uint8_t byte).

transfer(uint8_t* buffer, unsigned int size) on the other hand takes a pointer and the amount of bytes to shift.

Now to pointer arithmetic. Operations on pointer variables are dependent on their explicit data type(as well as processor architecture!). Therefore, in our case, a +1 on uint8_t* val will advance the pointer by 8bits.
+1 on uint32_t* val will do so by 4bytes/32bits.

Check buffer's data type

It should be any of char, unsigned char, uint8_t, int8_t


How to "break" a function we made? This is code about a keypad lock. The user can unlock the device by entering the secret code. To lock it again they press "#" or "*".

I want to let the green LED turn on for about 0.5 seconds then return to the first line of the loop: char key = keypad.getKey();.

The problem is that this code makes the green LED turn on forever after we enter the correct secret code or until we enter "#" or "*".

void loop() {
  char key = keypad.getKey();
  if (key=='*'||key=='#') {
    position = 0;
    setLocked(true);
  }
  if (key==secretCode[position]) {
    position ++;
  }
  if (position ==3) {
    setLocked(false);
  }
  delay(100);
}

void setLocked(int locked) {
  if (locked) {
    digitalWrite(redpin, HIGH);
    digitalWrite(greenpin, LOW);
  } else {
    digitalWrite(redpin, LOW);
    digitalWrite(greenpin, HIGH);
    delay(500);
  }
}

I may be missing something, but couldn't you just modify your setLocked function?

void setLocked(int locked) {
  if (locked) {
    digitalWrite(redpin, HIGH);
    digitalWrite(greenpin, LOW);
  } else {
    digitalWrite(redpin, LOW);
    digitalWrite(greenpin, HIGH);
    delay(500);
    digitalWrite(redpin, HIGH);
    digitalWrite(greenpin, LOW);
  }
  return;
}


ESP8266 working as station while in AP mode I'm programming an ESP8266 via the Arduino IDE with Arduino libraries.  I explicitly set the WiFi mode to WIFI_AP, but then, as described below, I'm still able to use it as both AP and station.  That leaves me unclear what's meant by the three modes available (WIFI_AP, WIFI_STA, and WIFI_AP_STA) since it seems that I've set to WIFI_AP explicitly but am getting behavior consistent with WIFI_AP_STA.

I have read various documents online about these modes. I think I'm clear on the conceptual difference between them.  What concerns / confuses me is that the actual behavior does not appear to match the specified behavior.

More detail:

Near the beginning of my setup function, I have this code

WiFi.mode(WIFI_AP);
WiFi.softAP(ssid, key);

server.begin();

where ssid and key are strings defined with appropriate values, and server is a global variable of type WiFiServer that has been initialized outside of setup.  When run, I see the network with the given name on my phone and can connect to it with the given password.  I can then browse to the IP address assigned by the ESP8266 and set the webpage sent by the server that's been defined in code.  So far so good.

At some point later, inside my loop, a condition triggers the ESP8266 to connect to my router.  Specifically, I have this sequence of code that runs once that trigger occurs:

WiFi.disconnect();
WiFi.begin(router_ssid, router_key);
auto status = WiFi.status();
while ( (status != WL_CONNECTED) && (status != WL_CONNECT_FAILED) ) {
    delay(500);
    status = WiFi.status();
}

As before, router_ssid and router_key are variables declared elsewhere with the proper values for my router.  I can verify from subsequent print statements, that the connection succeeds and get the IP address as assigned by my router. It is clear that the new IP is assigned by the router because it is on the subnet used by my router, which is different than the subnet the ESP8266 is defining in AP mode.

The ESP8266 is configured to serve a small webpage, as noted above. I can now reach that page using my phone, which is connected directly to the ESP8266 via the IP address assigned initially by the ESP8266 in AP mode, and I can also reach the same page from my laptop (connect to my router) using the IP address assigned by my router.  It would seem that I'm effectively in "AP+STA" mode now, despite having explicitly set to "AP" mode at the beginning.

So what's happening here?  Did I automatically switch to "AP+STA" mode when I called WiFi.begin?  If yes, what's the point (if any) of calling WiFi.mode?  If no, then why am I able to operate as if in "AP+STA" mode given the explicit setting of "AP" mode?

WiFi.begin() is a function of the ESP8266WiFiSTAClass. It changes the WiFi mode for you to STA or AP+STA based on the current mode.

begin functions are in ESP8266WiFiSTA

enableSTA function is in class ESP8266WiFiGeneric


Connection between ATTiny85 and RaspberryPi3 with nRF24L01+ I'm hoping someone can help me since I've been struggling with this all weekend. I've got 2 nRF24L01+ breakout cards and I'm trying to send data from a ATTiny85 to a Raspberry Pi 3.

My setup is (the attiny85 breadboard has a 3.3V power supply):

And the code I'm testing is for the ATTiny85:

#define CE_PIN 3
#define CSN_PIN 4

#include "RF24.h"

RF24 radio(CE_PIN, CSN_PIN);

const byte addr[6] = "00001";
int count = 0;

void setup() {
  radio.begin();
  radio.openWritingPipe(addr);
  radio.setPALevel(RF24_PA_MIN);
  radio.stopListening();
}

void loop(void){
  radio.write( &count, sizeof(count) );
  count++;
  delay(1000);
}

And for the Raspberry Pi 3:

#include <cstdlib>
#include <iostream>
#include <sstream>
#include <string>
#include <unistd.h>
#include <RF24/RF24.h>

using namespace std;

// Setup for GPIO 22 CE and CE0 CSN with SPI Speed @ 8Mhz
RF24 radio(RPI_V2_GPIO_P1_22, RPI_V2_GPIO_P1_24, BCM2835_SPI_SPEED_8MHZ);

// Radio pipe addresses for the 2 nodes to communicate.
const uint8_t addr[6] = "00001";

int main(int argc, char** argv){
  radio.begin();
  radio.setPALevel(RF24_PA_MIN);
  radio.openReadingPipe(1, addr);
  radio.startListening();

  // Dump the configuration of the rf unit for debugging
  radio.printDetails();

  int count = 0;

  while (1)
  {
    while ( radio.available() )
    {
      radio.read( &count, sizeof(count) );
      printf("Count: %d\n", count);
    }
    sleep(1);
  }

  return 0;
}

As Mikael Patel pointed out, my MOSI and MISO pins were switched.

On the pinout for the ATtiny85, the MOSI and MISO pins are for when the chip is a slave (i.e. programming). DO and DI and used for output as SPI master.


How to generate musical notes using an uno without using tone() function? Can anyone share the embedded c language code for it? I also want to know how can we make it without functions like digitalwrite

Yes, that's easy enough to do. I wrote a library to do that, as described here.

Basically you could make a class like this:

class TonePlayer
  {
  // addresses of output ports - NULL if not applicable
  volatile byte * const timerRegA_;
  volatile byte * const timerRegB_;
  volatile byte * const timerOCRH_;
  volatile byte * const timerOCRL_;
  volatile byte * const timerTCNTH_;
  volatile byte * const timerTCNTL_;

  public:
    // constructor
    TonePlayer (
          // ports
          volatile byte & timerRegA,
          volatile byte & timerRegB,
          volatile byte & timerOCRH,
          volatile byte & timerOCRL,
          volatile byte & timerTCNTH,
          volatile byte & timerTCNTL)
       :
         timerRegA_  (&timerRegA),
         timerRegB_  (&timerRegB),
         timerOCRH_  (&timerOCRH),
         timerOCRL_  (&timerOCRL),
         timerTCNTH_ (&timerTCNTH),
         timerTCNTL_ (&timerTCNTH)
  { }

    void tone (const unsigned int Hz);
    void noTone ();

  };  // end of TonePlayer

Then implement the two functions like this:

void TonePlayer::tone (const unsigned int Hz)
{
  // it takes two toggles for one "cycle"
  unsigned long ocr = F_CPU / Hz / 2;
  byte prescaler = _BV (CS10);  // start with prescaler of 1  (bits are the same for all timers)

  // too large? prescale it
  if (ocr > 0xFFFF)
    {
    prescaler |= _BV (CS11);    // now prescaler of 64
    ocr /= 64;
    }

  // stop timer
  *timerRegA_ = 0;
  *timerRegB_ = 0;

  // reset counter
  *timerTCNTH_ = 0;
  *timerTCNTL_ = 0;

  // what to count up to
  *timerOCRH_ = highByte (ocr);
  *timerOCRL_ = lowByte (ocr);

  *timerRegA_ = _BV (COM1A0);             // toggle output pin
  *timerRegB_ = _BV (WGM12) | prescaler;  // CTC
  }  // end of TonePlayer::tone

void TonePlayer::noTone ()
  {
  // stop timer
  *timerRegA_ = 0;
  *timerRegB_ = 0;
  } // end of TonePlayer::noTone

And now call it:

TonePlayer tone1 (TCCR1A, TCCR1B, OCR1AH, OCR1AL, TCNT1H, TCNT1L);  // pin D9 (Uno), D11 (Mega)

void setup()
  {
  pinMode (9, OUTPUT);  // output pin is fixed (OC1A)

  tone1.tone (220);  // 220 Hz
  delay (500);
  tone1.noTone ();

  tone1.tone (440);
  delay (500);
  tone1.noTone ();

  tone1.tone (880);
  delay (500);
  tone1.noTone ();
  }

void loop() { }

In this example you plug your speaker into D9 (digital pin 9) on your Uno, with the other pin going to ground. Since this plays tones using the hardware timers you can do other things in your loop without affecting the tones.


Can I control a cellphone's lcd (+touch screen)? I had an Xperia txt pro just laying around and tried to revive it. I burned it like an idiot using 5v in the battery pins by accident :/
So I decided to read it apart and got to the lcd, can I use my Arduino Mega to control it? Bc I have no idea how to use it.

These are the pins

No. For two reasons:

You will struggle to find the pinout of the TFT (or even identify the model). It will have most likely been custom made for the phone.
The Arduino doesn't have a GPU to drive it. Arduinos need a TFT with built in GPU since they lack the resources to drive one directly.


Arduino constant clock output I am controlling an ADC with my Arduino Uno. I would like the clock of the ADC to be the same frequency of the Arduino.
Is there any way that I can have a constant clock output from one of the Arduino pin ?

Thanks,

Liam

This outputs 8 MHz on pin 9:

#ifdef __AVR_ATmega2560__
  const byte CLOCKOUT = 11;  // Mega 2560
#else
  const byte CLOCKOUT = 9;   // Uno, Duemilanove, etc.
#endif

void setup ()
  {
  // set up 8 MHz timer on CLOCKOUT (OC1A)
  pinMode (CLOCKOUT, OUTPUT);
  // set up Timer 1
  TCCR1A = bit (COM1A0);  // toggle OC1A on Compare Match
  TCCR1B = bit (WGM12) | bit (CS10);   // CTC, no prescaling
  OCR1A =  0;       // output every cycle
  }  // end of setup

void loop ()
  {
  // whatever
  }  // end of loop

  How can add a prescaler?

You change the prescaler bits. You can look at the datasheet or my cheat sheet here:

You may not need a prescaler, depending on the frequency. Change OCR1A to some number between 0 and 65535 to slow it down.

Edit by Edgar: I tested the OCR1A values with an oscilloscope. At the end of this answer are the frequencies.

  you use TCR1A, COM1A0 and similar variables. Are these always present and implicitly defined when running code on the ATmega

Registers like TCCR1A and so on are defined in files which are automatically included by the Arduino IDE. If you use another toolchain they may be also automatically included. The start point is:

#define <avr/io.h>

Inside that file it checks your processor type (from a symbol passed to the compiler) and then includes an appropriate sub-file. Inside those files are defines which relate the register names to their address in the address-space of that particular chip. For example:

#define TCCR1A _SFR_MEM8(0x80)

The _SFR_MEM8 basically generates a pointer to a volatile address (because it might change without the compiler knowing it) and then dereferences that variable.

Notice that the number 0x80 in that define agrees with the number shown on my chart.

Underneath that define in the appropriate file are also the bit positions for the bits in that register, like this:

#define TCCR1A _SFR_MEM8(0x80)
#define WGM10 0
#define WGM11 1
#define COM1B0 4
#define COM1B1 5
#define COM1A0 6
#define COM1A1 7

  Secondly, do I correctly understand that the output pin is defined in TCR1A, Output A and Output B, to be on Digital Pin 9 and 10 respectively?

Yes, in effect. The datasheet says that if you set the appropriate bits in TCCR1A (note the spelling) then OC1A (board pin 9 on the Uno) or OC1B (board pin 10 on the Uno) will be unchanged/toggled/cleared/set depending on the bits. You can find these names on the datasheet for the Atmega328P (and other devices) and then use the Arduino schematic to find which processor pins are connected to which board pins.

Atmega328P datasheet snippet:

Uno datasheet snippet:

  Why do you set it to "Toggle" rather than "Set"?

Because every time the counter matches I want to flip the pin. That is, on/off/on/off etc.

  What does CTC stand for?

Clear Timer on Compare. What this means is that (unlike other modes) once the compare match is made, the timer is cleared, thus it starts counting up from zero again.

Edit by Edgar: OCR1A values and frequencies

Value, MHz
 0 8.00
 1 4.00
 2 2.67
 3 2.00
 4 1.60
 5 1.33
 6 1.14
 7 1.00
 8 0.889
 9 0.800
10 0.727
11 0.667
12 0.615
13 0.571
14 0.533
15 0.500


Voltage divider and NodeMCU inputs Some sensors give as output a voltage between 0 and 5V. The analog inputs of the NodeMCU require voltages between 0 and 3.3V. I plan to make a voltage divider with two resistors like in this link for compatibility.

To provide the desired voltage the quotient of the values of the resistances is fixed (approx. 1/2 for this case). However, the absolute values of the resistances are not.

Q: How to choose those absolute values? Which are the criteria and why?

I have a good background in electromagnetism but I know very few about electronic Engineering.

I think that low values must work, e.g. 1Ω and 2Ω (and surely greater values). But I am unsure of VERY high resistance values because I suspect that there should be some current intensity requirements.

Thank you.

As @Majenko commented, the A0 input has a fixed voltage divider (see NodeMCU Schematics) that connects the A0 input to a 220kOhm resistor, then to the ADC pin of the ESP8266, then to ground via a 100kOhm resistor.

This effectively fixes the resistor values that can be used to scale the input of the NodeMCU. For a 0-5.0V input range (with sufficiently low impedance) you need to scale the ADC pin from 0-1.0V by adding a ~180kOhm resistor between the 5V output and the A0 input of the NodeMCU, creating a 400kOhm-> ADC -> 100kOhm divider like this:

simulate this circuit – Schematic created using CircuitLab


Getting enum name from enum instance Hello Arduino Stack Exchange,
I have an an enum instance called state:
enum States
{
  SLEEP,
  AWAKE,
  CRAZY
} state;
States state = SLEEP;

I would like to convert the value of state to a String so I can serially print it using Serial.println().
Currently, when I type String(state), I get a value 0, 1, etc.  I suppose this corresponds with the index of the enum's key.
How can I get it to return "SLEEP", "AWAKE", etc.?

You can print the value as it is:
Serial.println(state);

This will print the the ordering number of the enum, but you can specify the value as any number or char.
enum States
{
  SLEEP = 'S',
  AWAKE = 'A',
  CRAZY = 'C'
};

Now if you print it with cast to char Serial.println((char) state); it will print a character, which in my opinion is much better then some number.
If you want to convert the enum values identifiers to strings you can do it with a preprocessor macro.
enum States
{
  SLEEP,
  AWAKE,
  CRAZY
} state;

#define IDNAME(name) #name
const char* stateNames[] = {IDNAME(SLEEP), IDNAME(AWAKE), IDNAME(CRAZY)};

I don't think this is better then to print the char values. To do a pretty print it is better to use descriptions.
const char* stateStr[] = {"Sleep", "Awake", "Undefined"};
Serial.println(stateStr[state]);


non asssign variable using by for in loop() can remeber last value. what happen here? I modify this code from my friend and it look strange.
void setup() {
    Serial.begin(115200);
    Serial.println("reset");
}
void loop() {
    for (int d; d <= 32767; d++) {
      Serial.println(d);
      delay (1000);
    }
}

for some reason when you press reset, the variable will keep counting from last value as shown.

this not gonna happen when you put these block in setup()
I know that not good idea to use varible in for loop without assigned the value, but I belived it must have a interesting reason for this.
For my hypothesis, the variable value just allocate with same address in memory. when this code run in setup() some how the complier detect this situation and assign 0 as initial value. but when in the loop() some how the compiler don't assign new value to the memory address and it get old value from last time the program was run before resetted. I still need further explanation.

I think you missed a compiler warning (I did, too!) - notice that you are using 'd' uninitialized. On each re-entry to the loop() function, loop()'s stack will be in the same place in memory. The for-loop doesn't initialize 'd', but the boot loader did zero RAM for your first run. 'd' happens to occupy the same memory location on each entry to loop(), so the old value (just before reset) is still in place. Since the for-loop didn't re-initialize it... :)
The fix is:
for (int d=0; d <= 32767; d++) {

Update:
That begs the question: Why did your run fail as expected, while my run appeared to execute normally? My guess is different bootloaders, one that does, and one that doesn't, initialize SRAM on a reset that doesn't result in an upload.


Can't turn off fan using PWM and analogWrite(x, 0) I'm trying to make PWM Signal Generator with Arduino Uno.
I'm trying to control 230V 50hz "NRG118" combi boiler fan.  The fan powered by AC and have 3pins for PWM control. "vcc,gnd,pwm" Wired them to arduino "5v, GND, 11" pins.
I can control the card on the arduino "0to100% with a simple code below but I can't turn it off.
I tried digitalWrite nothing changed. Tried different pins 5-6-9-11 nothing changed. Tried to wire gnd+vcc to outsource powersuply nothing changed.
Also I have a simple PWM generator "HW-723 XY-LPWM PWM Signal Generator Module". The "HW-753" can control the fan without any other component but it may have builtin special component like a NPN but im not sure about it.
In description I found this and maybe its a requirement but I have no idea about electronic components:
"The PWM output pin on the microcontroller drives an NPN MMBT3904 type transistor which in turn drives the PWM output pin of the module.  The transistor has a series 1K resistor tied to VIN+, so the PWM signal will swing between ground and the module supply voltage on the VIN+ pin."
With the HW-753; at startup the fan is not running but when I wire to my arduino it starts with 100% power and when i set "analogWrite(x, 0)" dutycycle reducing but fan still running at %1 speed and I read 0.07volt with multimeter on "PWM+GND" pins.
Most people can not run, I cant stop.... It's killing me people...
What am I doing wrong?
void setup() {
  pinMode(6, OUTPUT);
}
void loop() { //the code only for test. Using loop is dumb.
  //digitalWrite(6, LOW);
   analogWrite(6, 0);
   delay(5000);
}

If you are working with the AC motor, then it is probably works even PWM cable is not attached. In this case there is no reason to use "analogWrite(PIN, 0)".  It will not work.
"An external resistor divider connected to the VMIN input sets the minimum fan speed by fixing the minimum PWM duty cycle (1.25V to 2.65V = 0% to 100%, typical).  It depends on controler card manufacturer. check datasheet"
If you cant find datasheet like me then check how others do. There is diagram of "HW-753 Signal Generator Module" below. As you can see between VIN+ and PWM there is 1k Resistor and both wired to an NPN, also the mid leg of NPN passing 1k resistor while going to pwm to protect the card. Also 3rd leg is wired to gnd. So it is not the same thing I was doing before. If you work with AC then you must always consider that and just forget what people say. Do not drown like me. I hope it will helps someone.


Mega 2560 & smoking/burning 5v requlator, probable cause? Problem: board seriously fried.
Desired outcome: measures to take in future.

Background:
This project has been running for about a week on the 2560, and previously for a few weeks on an UNO clone. Board switch a result of program size/expansion.  It sits on a shelf with others of the same ilk.  Nothing is touched unless I need to plug in USB cable for update.
The Arduino is a clone, connected to DS3231, LCD1602 via I2C Serial Interface board, LCD2004 also via 12C SIB, SD card adapter, HC-12 wireless, 5 leds [normally off, used to flag specific conditions, each in series with 470 ohm resistor.
The unit receives data from another Arduino and logs to the SD, updating the two LCD displays.

Steps leading to failure:
Plugged in USB cable [no other physical changes, nothing else touched, power jack remained connected]. went to Arduino s/w to make minor changes, would not upload to Arduino.  While scratching my head, smelled something burning, then saw smoke coming from the shelf.

Post failure:
Board seriously scorched around 5v regulator, can provide photo, but seems unnecessary.
Visual wiring inspection revealed no obvious problems.
Input to power jack measured at 10.06v.
Replaced with new Arduino 2560 clone, matching connection for connection, connected USB but not power port [just in case of ?, seen ancedotal posts of possible conflict; a clone after all].  Uploaded my modified program, and all works fine. Disconnected USB, reconnected power jack and all still fine, 16 hours in.
Also searched internet for possible problems related to such a failure, but found nothing to suggest probable cause.

Seeking:
Words of wisdom from others far more knowledgeable and experienced than I.
Could the dual connection of USB and power jack, be the root cause?  Never experienced this with UNO clones.

I do not want to put more boards at risk in the future.

They are using the same SOT223 LDO as every other product.  These have a very low limit of output current when run from an input voltage such as 12V.  If you replace the LDO with a switching regulator, you can eliminate the waste heat regardless of the output current (Except for the 5V to 3.3V secondary LDO which is a constant).  The PDF linked below shows a comparison between the LDO and drop in switcher.  Not that the switcher performance at 1900mA is equivalent to the LDO at 250mA... at 250mA the switcher temperature rise would only be 8.5C.

https://www.sugarsync.com/pf/D3258881_07979653_7526812


How can I play audio from an SD card? What is the best / simplest way to play audio files from an SD card?

I'm currently working on a sound board, where each button plays a different sound. But I have yet to find the right combination of shields / hardware to do this efficiently.

Is there a shield that supports this directly (SD card -> speaker)? Note that I also need additional pinheads for my buttons to connect to. I think I will be using the Arduino Mega for that purpose.

There are several audio products/shields.  Because you mention "speakers", the first one listed can come with an on-board amplifier to drive speakers directly.  Most shields just give line-out to drive a pre-amp.

Adafruit Music maker shield plays MP3/WAV/OGG from microSD http://www.adafruit.com/products/1788
Adafruit Wave shield plays WAV files on SD card http://www.adafruit.com/products/94
SparkFun MP3 trigger board supports 256 tracks and a serial protocol for running individual tracks. https://www.sparkfun.com/products/11029
SparkFun MP3 shield board plays MP3/WAV/OGG https://www.sparkfun.com/products/10628


Suggest me a power source for my Arduino UNO project I am working on a Project with:

1 Arduino UNO
5 micro 9g servos (Only one Working at a time)
2 small LED bulbs
1 MicroSD reader module
1 Speaker

Can I power my Arduino UNO with a common 9v Battery?

I also have in mind to use an external power supply for servos... but what to use?

Please suggest me a perfect power supply system

Unfortunately, the perfect power supply system doesn't exist yet. However, powering an Arduino is simple.  You have to main options 9V for standard "full size" Arduinos (such as the UNO that you mention), although you could go for the low voltage 3.3V options.
Covering just the 9V option, from the Power section of Arduino Uno:

Power
The Arduino Uno can be powered via the USB connection or with an
external power supply. The power source is selected automatically.
External (non-USB) power can come either from an AC-to-DC adapter
(wall-wart) or battery. The adapter can be connected by plugging a
2.1mm center-positive plug into the board's power jack. Leads from a battery can be inserted in the Gnd and Vin pin headers of the POWER
connector.
The board can operate on an external supply of 6 to 20 volts. If
supplied with less than 7V, however, the 5V pin may supply less than
five volts and the board may be unstable. If using more than 12V, the
voltage regulator may overheat and damage the board. The recommended
range is 7 to 12 volts.

You should probably also take a look at Power Supplies, in particular the section on Batteries and cells, also from the following section Voltage conversion and regulation, it states:

In a very simple scenario, you connect a disposable 9v battery
(probably one of the (approx) 4cm x 2.5cm x 1.5cm units with two snap
connectors on one end) to your Arduino, and the Arduino's built in
voltage regulator takes care of reducing the voltage to a consistent
5v or 3.3v, depending on the sort of Arduino you have.

So you have a couple of choices regarding 9V, either the P9 cell

or a pack that holds six 1.5V AA or AAA batteries.
You may find this link, How to run an Arduino (clone) on (AA) batteries for over a year – part 2, an interesting read. Here the chap uses four AA batteries, which only gives 6V, to power an UNO:

I have just highlighted some information, you should take the time to read the links fully, and google for more information.

Regarding the servo motors, more current may be required. You can use the same four AA battery pack, thusly:

but the capacity of the batteries may leave something to be desired, especially if you use rechargeable batteries (which in today's eco-concious world, you should), so you may require something more hefty. A quick google will show you the options available.
Addendum
The video Flite Test : RC Planes for Beginners: Batteries and Safety - Beginner Series - Ep. 7 is an extremely useful video tutorial about LiPO batteries for RC projects.


Powering Arduino and LED strips from one adapter My project has my Arduino controlling 10 led strips. I'm going with a plan by @gre_gor that is posted here: Setting 10 RGB Strips Independently from Single Arduino
...where each strip is controlled by an STM32 driver.

I'm packing all electronics into a tight space and will need to have the power adapter external with just the cable coming in.

I need power both to the arduino and directly to the stm32's.

Question: can I simply split the 12V power cable to send power to both the led strips and the arduino? Or is there something I should worry about?

Powering an Arduino and LED strips is no different to powering your TV, satellite receiver, DVD player, etc all from one socket in the wall.

Connect all the grounds (-) together, and connect all the powers (+) together.

All you need to worry about is that the total current draw of all the devices combined doesn't exceed the amount of current that the power supply can provide (oh, and that they all operate at the same voltage, of course).


ov7670 + Sd Card + arduino I have three devices for making a motion activated security camera system:

this is the camera : LINK  OV 7670
this is the SD Card module: LINK
and a basic motion Sensor: PIR with 3 pin

I have an Arduino UNO and an Arduino Mega 2560.

I can connect the SD card and sensor, they work fine but I cannot connect the camera as there are not enough pins for it on UNO.

Is there a chance to connect all of them without any additional device?

I saw some working project with additional device (arducam) but I do not have much money to spend on this project.

This camera module requires the use of additional hardware, as the camera and Arduino operating frequencies differ, which can result in loss of synchronization and changes to the image, and other connection problems.

Thus, we must use an integrated circuit intermediary, making the connection between the camera and the Arduino. The function of this chip is to receive the camera information, store them and then send them to the Arduino using the digital doors, much faster than if we used the serial communication.

An example of an integrated circuit that could be used is AL422, suitable for treating a video signal, which also is embedded in some OV7670 modules.

Looking like the connection pins behave in 7670, your module should be equal to it. So spare pins to be able to make other necessary connections.

Would better check the connection through the datasheets:

7670 datasheet

AL422 datasheet

An example of project

But to answer your question; You'll need to purchase a piece more if you don't have AL442.

Regards,


Arduino Mega 2560 not recognized/overloaded I pulled my Arduino set out of storage yesterday and was very upset to find that it is not working for some reason.  Before I explain the problem, let me explain the situation.

Hardware (all DFRobot):

Arduino Mega 2560

Arduino Mega 2560 4x-platform breakout board

GPIO Expansion Shield V1.0

I/O Expansion Shield V7.1

8 Channel 5V Relay Board

4 LED/Resistor set up

1 digital speaker

1 digital humidity/temperature tester

7 analog chemical air chemical testers

The whole project:

LED Portion:

Relay Portion:

Sensor Portion:

Pin Connections:

In this 4th photo, the two analog pin sets in use right in front are the ones I remove in order to gain control again.  if those are plugged in then it doesnt work.  It has nothing to do with those pins specifically, If I remove any two it works again, those ones are just easiest to remove to get it to work:

Explanation of project:

This is basically a test station, where I can hook up what ever I want and see how it works and then move onto another peripheral piece of hardware and make them interact.  I went with the 4x-platform breakout board as to maximize I/O space.  Once a project is done, I Velcro band them together as to not get them confused and move on.

Explanation of problem:

When I plugged the Arduino into my PC the first time, the lights came on the Arduino and then after about 15 seconds it powered down and the lights went off.  My PC did recognize it while it was powered up and the port option under tools in the Arduino IDE was available and I could select the port.  After the power down and problems I realized something must be up.

I considered the fact that maybe the Velcro was constricting the wires and causing them to short circuit through the rubber insulation, but couldn't find any info on that online.

After this I decided to cut the PC out of the equation and try just plugging it into the wall, 1st, via USB to 5V1A wall charger, it stayed on for a few seconds and then turned off, 2nd with a 5V2A wall charger, same scenario, 3rd via the barrel jack with the same wall chargers, with no success.

I undid all of the wire bundles to rule out a short circuit, which it did.  I then found out after much trial an error that if I removed any 2 of any analog or digital wires, the lights would stay on and it would work.

Now, with two cables removed so it did not lose power, I plugged it into my PC and am now able to program it again and see it in the port in the IDE, but as soon as I plug in another 2 analog or digital peripheral devices it will lose all power and stop working.

I also tried plugging my DFRobot Beetle micro-controller in with the same USB cable and it worked perfectly.  I also tried resetting the micro-controller, to no avail.

Conclusions so far:

A short between rubber insulation at 5v is extremely unlikely

one would think that if a mega board was designed to have so many I/O pins you could actually connect to all of them with out any problem.

Since this happened on both the PC and wall charger scenarios, and the problem seems to be associated when disconnecting any 2 sensors, the problem is most likely at the micro-controller level.

Questions:

are all the peripheral devices draining the board so much that the USB port on the PC or wall chargers cant handle it?

How do I provide enough power to the board if this is the problem?

Or is this simply faulty board?

If it is a faulty board, what causes this and how do you avoid it?

Just to clarify, looming the wires together into bundles is OK right?

Finally, any help would be really appreciated, this is the first time this has happened and it sucks.

First off, that is one heck of a rig.  I'm impressed to the point of "I gotta get me one of those."

Bundling your wires shouldn't have the kind of impact you are seeing, unless there are bare wires touching.  You might get induction interference, but not a total shut down.

From what I can see here, it looks like there's so much stuff connected to the Arduino that it's probably starving it for power.  You should look into using power rails for Gnd and +5v.

You will also need to check if you are supplying it with enough amps, too.  Your computer's USB port only supplies 0.5A, unless it happens to be USB3, then it's 0.9A.  Even your 5V1A PSU might not be enough.  Consider finding a 2-5 amp wall wart to do some more testing with.  There are usually spec sheets with components, so you'll need to add all the power draw for all the components, including the Arduino, and make sure you have more than enough to meet that calculated power draw.  Exceeding it by at least 10-20% is usually considered good practice, even for a test rig.

Consider powering your rig's new power rails with the extra PSU even when the Arduino is plugged into your computer.  As long as you make sure you aren't trying to take power from the computer and the PSU at the same time with the same component, you should be fine.  (Don't cross the streams.)

There could be a short or feedback loop somewhere in your sensors that's causing the extra drain.  There are so many wires here that it'd be easy to hook up something backwards.  Along with the number of wires, the bundling doesn't let SE-us help you track that down.

You might want to look at the direction your pins are facing.  It was an odd situation for me, but having two of the metal clips facing each other was enough for a short.  In your "Relay Portion:" pic, they are all facing the same way, which is good.  See if there are places where that's not the case and fix it.  Like I said, it was an odd situation, but it's a phantom problem you can avoid.


Listen for USB "TX signal received" response on RX Is there a usb signal I can send on TX that will generate a response from the computer on the RX only if the computer is active/not a wall usb power supply? I'm trying to use the Remote library when a button is pressed and sometimes it won't work because the computer is off/asleep/etc and in those instances I would like the arduino to behave differently but because I have no way of knowing if the USB power is coming from the wall or passively from a computer that's off or actively from a computer that's on, I can't know what behavior to take.

To be clear about the application in mind: Right now I have a device that sends keyboard signals to my computer using a modified version of Stefan Jones' modified USBAPI.h and HID.cpp files. It works fine but if you restart the computer you have to manually unplug and replug in the arduino to get it to work again. This is necessary every restart, is rather annoying, and adds unnecessary wear to the connector. This is also necessary if the arduino is connected before the OS has loaded. Additionally there are some LEDs on the device (not talking about the diagnostic lights on the arduino itself) that stay lit up at night even when the computer is off. If I could detect when the computer is off/unconnected it would be trivial to fix this.

If an MCU which has a built in USB interface (such as the ATmega32u4 on a Leondardo) is properly configured and connected to an operating USB host, it will receive a "Start of Frame" packet every millisecond.  I'm not very familiar with the details of the USB engine on that particular chip, but generally you can detect this as an interrupt, or as a change in a peripheral status register bit.

Going a step further, in the Arduino API an if (Serial) test will determine if the board is connected to a host which is in an active CDC-ACM "serial" session with it, ie, one that has a serial terminal or other program talking to it.  Again, this only applies to those that implement USB within the chip on which the sketch is running.

Chances are your problems can be fixed by enabling the AVR watchdog timer at one of its longer limits and resetting it in the USB ISR found in USBCore.cpp Then if the the USB goes down (ie, the usual every millisecond SoF interrupt fails to happen for several seconds) your Arduino will reset.  In the simple case, it will keep resetting as long as it has power and the USB is down, but you can put some startup logic to wait for the USB while resetting the watchdog if that bothers you.  See for comparative example the implementation details behind the if (serial) and create something similar for your chosen USB mode.


Using interrupts for two MCP23017 I am creating a simple shield with two i2c MCP23017 chips. Each MCP23017 has two interrupt pins, but the Arduino Uno only has two interrupt pins (pin 2 and pin 3).

The way I understand it, interrupts are there to tell the Arduino something has changed, so it can then poll the MCP23017 for the latest pin reads.

How can I connect the 4 interrupt pins to my Arduinos 2 pins?

The MCP23017 (and it's sister the SPI-based MCP23S17) can have their interrupt pins set to "mirror" mode. In this mode both pins are internally joined so when an interrupt occurs on any port both pins activate.  This is done using the MIRROR bit of the IOCON register.  Using this will turn your 4 interrupt pins into just 2, one for each Arduino INT pin.

Should you want to add more in the future, or if you find you want to use one of the interrupt pins on the Arduino for something else, there is also the ODR bit in the IOCON register. This sets the interrupt pins to be open drain, which means that all of them can be wired together into just one INT pin on the Arduino. Add a pullup (or enable the internal pullup) and you have have many IO expanders on one INT pin. Of course, that then means that you have to poll all the expanders to find which of them triggered the interrupt, so could slow things down somewhat depending on how you are using it.


Take an Arduino or Teensy prototype to Mass production - Loading software onto microcontroller I am developing an educational product that I would like to mass produce. I am not sure of the quantity yet, but I imagine we will make a few hundred PCBs at least to begin

I spoke with an electrical engineering about how to take an Arduino prototype to mass production, and he warned me that the code written in the Arduino IDE cannot be fused onto the processor. (He used the term "fuse", although I don't see this elsewhere in the forum. is this the right term?)

He said that I would probably have to take each product, and load the Arduino code on manually, plugging in each one to a computer and upload like one would when prototyping. Also, he said the other option would be to recode my Arduino sketch from scratch using an AVR code.

Can someone shed some light on this for me? How can I take Arduino prototyping code and use it in mass production?

Arduino code and AVR code is essentially the same, at least once compiled it is. The only real difference is the existence of the bootloader, and that is not essential.

For quantities of a hundred or so it is probably most cost effective to manually program them via an ISP connector to the board. For larger quantities Atmel provide a mass programming service to pre-program the chips, but that costs money so the more you have done at once the cheaper it is per chip. I am not sure on Atmel's procedure off hand but others I have used just take either a .elf or .hex file which the Arduino IDE is perfectly capable of producing.

Either way you should design in an ISP connector on your board so the firmware can be upgraded in the future if needed.


Arduino digitalWrite not working I am trying to control this OWI Robotic Arm using the Arduino's digital outputs (I am using pins 12 & 13).

If I wire up the wires to ground and 5V it goes one way, if I switch the wires, it goes the other way. However when I have the pins wired up to the digital pins, it does not work, but the on-board LED does blink.

The code:

int a = 12;
int b = 13;

void setup() {
  // put your setup code here, to run once:
  pinMode(a, OUTPUT);
  pinMode(b, OUTPUT);
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  //up
  digitalWrite(a, LOW);
  digitalWrite(b, HIGH);
  digitalWrite(LED_BUILTIN, HIGH);
  delay(500);
  //down
  digitalWrite(b, LOW);
  digitalWrite(a, HIGH);
  digitalWrite(LED_BUILTIN, LOW);
  delay(500);
}

The problem you are seeing here is that the Arduino can provide nowhere near as much current through I/O pins as it can power. Quoting from the Arduino website:

  DC Current per I/O Pin: 40 mA

This means that each pin can power maybe a couple of LEDs, and that's it. Additionally, motors provide "back-EMF": When opening (cutting power) an inductive load (e.g. a motor), the current wants to keep going. This will damage whatever just opened unless protection is used. So, I wouldn't be surprised if you damaged your Arduino by attempting to drive a motor with it.

So, what can you do? Use an H-Bridge. This circuit will allow you to easily control a motor & its direction. Many circuits can be found online, but an easy solution is a cheap L298N module, which can be as cheap as $3 a piece. This will safely & easily control the arm. Connecting your Arduino with the following circuit & using your existing sketch will make it work.

simulate this circuit – Schematic created using CircuitLab