Issue sharing MISO with multiple RC522 RFID Readers so for about the last 8.5 hours (almost non-stop) I have been trying to figure out one issue and I have exhausted every search I could possibly think of.

I'm building a puzzle that requires 5 RFID readers on the 1 Arduino, but for the sake of testing i've only been using 2.

Both readers work independantly, I can read out the UIDs of the little cards, which is all I need to do, but as soon as I make them share the MISO line, it simply stops printing anything out. I have no idea why.

Both readers have a common external 3.3v power supply and ground, they share all other lines but have an individual Slave Select. For testing I put both of their MISO cables into a breadboard which then leads into the Arduino on PIN 12, but it will only print out the UID when only ONE cable is plugged into the breadboard.

So is there something special I need to do to make this work? Is there a reason why the readers sharing a MISO line would break it? Even if i don't initialise one of them, just for the fact that it's plugged in still breaks it. I have tried setting one to HIGH and one to LOW, both to LOW, both to HIGH, nothing changes it.

Also, something else kind of confusing to me, it's meant to be active LOW to activate the SS, but when only 1 is plugged into the MISO line, it doesn't seem to matter which state it's in, it always prints...

I did a little bit of testing on my sketch just a moment ago and realised that when both are plugged into the MISO, the sketch will not progress past this line (which is also the first line in the loop)

if ( ! mfrc522_2.PICC_IsNewCardPresent())
        return;

I know everything else is working because it works when there is nothing else plugged into the MISO line, but I need it to work when all the others are plugged in too.

Please please please, if you have any idea, let me know.

I'm using the MFRC522 Library

EDIT:

This is basically the setup i'm using:

I'm not using any voltage translators or shifters, everything is 5v from the arduino except for the power to the readers which is coming from an external 3.3v supply like mentions previously.

I'm pretty certain that this is the datasheet for the RC522 i'm using, though i'm not sure if it's V1 or V2, but given the differences between them I don't think it matters:

http://www.nxp.com/documents/data_sheet/MFRC522.pdf

I don't know if they are able to share MISO lines like someone below said, I just assumed I could?

I am joining this conversation VERY late, however maybe my answer can help someone who is just now looking into this.
I was able to get SEVEN RC522 readers working on one Arduino! My solution was very similar to your idea, except instead of the SS pin, I used the MISO pin.

If you look into how the pins work, all of them are outputs going from the master (Arduino) to the slaves (RC522), EXCEPT for the MISO pin which is an input going from the slaves to the master.
So I gave each RC522 scanner it's own MISO pin on the Arduino, and the rest of the pins were shared with all the scanners.
To get it working with the code, the simplest solution I found was to initialize a new RFID using the corresponding MISO pin each time I wanted to read from one of the RC522s.
This worked for the Arduino because you can set several of the digital pins as MISOs, however I haven't figured out how to get this working on a Raspberry Pi yet (without using a multiplexer) because the Pi has a few specific pins that are used for MISO.
I was using the old Sunfounder library. At the bottom of this page (http://wiki.sunfounder.cc/index.php?title=Mifare_RC522_Module_RFID_Reader), if you download the "RFID-RC522_test_experiment" zip file it will have the library included. Just copy and paste the RFID1 folder into your Arduino Library folder. Here is a simple tutorial for that library: https://www.sunfounder.com/learn/RFID_kit_V1_for_Arduino/lesson-29-rfid-entrance-guard-system-rfid-kit-v1-0-for-arduino.html
Here is some example code. It is pretty ugly but it worked.
void checkRFID(int i){
  if(i==0){
    rfid.begin(2,4,5,7,3,6);
  }
  if(i==1){
    rfid.begin(2,4,5,8,3,6);
  }
  if(i==2){
    rfid.begin(2,4,5,9,3,6);
  }
  if(i==3){
    rfid.begin(2,4,5,10,3,6);
  }
  if(i==4){
    rfid.begin(2,4,5,11,3,6);
  }
  if(i==5){
    rfid.begin(2,4,5,12,3,6);
  }
  if(i==6){
    rfid.begin(2,4,5,13,3,6);
  }
  delay(100);
  rfid.init();
  uchar status;
  uchar str[MAX_LEN];
  // Search card, return card types
  status = rfid.request(PICC_REQIDL, str);
  if (status != MI_OK)
  {
    return;
  }
  // Show card type
  rfid.showCardType(str);
  //Prevent conflict, return the 4 bytes Serial number of the card
  status = rfid.anticoll(str);
  if (status == MI_OK)
  {
    memcpy(serNum, str, 5);
    rfid.showCardID(serNum);//show the card ID
    Serial.println();
    Serial.println();
  }
  delay(100);
  rfid.halt(); //command the card into sleep mode
}


How to identify Arduino Mini Pro 5v vs 3.3v I have many Arduino Mini Pro, every from different seller.
Few are 3.3v and most 5v.

I had to clean table for Xmas and now I do not have any idea how to identify 3.3v Arduinos.

They do not have any marks. I bought them on ebay.

I know 3.3v has 8mhz clock but only one my arduino has big crystal with 16.000-30.

Consideration (go down for the actual solution)

If you have a lot of different China-Arduino-clones, the easiest way will be to just test it. The cloned Arduinos use a lot of different voltage regulators and often you won't even be able to find datasheets for them on Google.

Someone here provided an Arduino sketch which helps you identify the frequency with which the Atmel is running and the comments say "it is the safest method". But why? It is complicated (you need to connect the USB-TTL-converter to each of the different Arduinos and sometimes they have different pinouts, so it's error-prone - you could easily fry your Arduino if you connect the wires to the wrong pins)...

Solution

I think the safest way is just connecting a voltage in the range of 6V-12V to the RAW-pin and measuring the (regulated) output of the VCC-pin.

There is no reason why this would kill your Arduino (in case your Arduino isn't broken - which would be good to know anyway; and of course you shouldn't short anything).

I've done a short sketch of how you should connect your Arduino Pro Mini:

RAW <---> 6V-12V
VCC <---> multimeter (5V = 5V Arduino, 3.3V = 3.3V Arduino)
One GND pins to the GND of the power source and one GND pins to the GND of the multimeter (you can take any of the Arduino pins labeled with GND)

Don't worry if your Arduino looks a little bit different, just look for the pin labels. For instance, one of my 5V Arduino Pro Minis looks like this, but also has RAW-, VCC- and GND-labels (just one of the GND pins is at a different position, make sure you check your Arduino pin-labels):

Alternative

You don't want to use the method above for some reasons? Then you need sharp eyes and some luck that the following list includes you components (some of these are collected from the other posts, some of them from my Arduinos):

3.3V:

Voltage regulators: KB33, S20K, F34V, L0RA, L0RB
Oscillators: 80e., 80'0

5V:

Voltage regulators: KB50, L05, L0UA, L0UB
Oscillators: R160JAC6s, 16.000-30, A1, A'N, A'a

(no limit or warranty for these details...)

More Suggestions

Some of the Arduino Pro Minis come with MHz and V markings on the back. In my case, none of these were checked. Make sure you check them as your new Arduinos arrive, so you won't have any problems identifying them later!


Why does the Arduino Due have a native and USB programming port? According to the schematics, the Arduino Due has two USB inputs:

Native
Programming

Why is this? And when would I use the different ports?

Either port can be used for programming, but the native USB port lets you do other things:

  It also enables the Due to emulate a USB mouse or keyboard to an attached computer. To
  use these features, see the Mouse and Keyboard library reference pages.

  The Native USB port can also act as a USB host for connected
  peripherals such as mice, keyboards, and smartphones. To use these
  features, see the USBHost reference pages. http://arduino.cc/en/Main/arduinoBoardDue

So you can use the Due to interface with USB devices or connect it to your computer and have it act like a USB device.


HC-05 module short circuit I have bought a HC05 bluetooth module and I think I accidentally short circuited it. Is there any way to change the voltage regulator or methods to reuse it again?

I suppose you're referring to the HC05 module, already soldered on a board, with the 6-pin header. The regulator is on that board.

Online you'll find several versions of that board, therefore you should check the schematics, to find which you need to mount. For instance, on some board, a R1114-33 is used.

Changing the regulator is not the hardest task on earth, however, other components are very close to it (capacitors).

Still there are 2 things to consider:

Is it worthy to change the regulator? That module will cost few
bucks.
As you can see from the datasheet, the regulator is short-circuit protected (yes, it does not mean that it will be indestructible). I think, instead, you destroyed one of the two ICs of the bluetooth module soldered on board. And those one, beside of being quite difficult to find and expensive in small quantity, they are very hard do replace.


Publish chipid to mqtt using ESP32-CAM I have been trying to push the data of temp, humidity, and pressure from a sensor to MQTT using ESP 32Cam, and was able to do using the following code:

pressure = bme.readPressure();

//Convert the value to a char array
char preString[16];
dtostrf(pressure, 1, 2, preString);
Serial.print("Pressure: ");
Serial.println(preString);
client.publish("esp32/pressure", preString);

When I started off with the following code for getting the mac address:

chipid=ESP.getEfuseMac();//The chip ID is essentially its MAC address(length: 6 bytes).
Serial.printf("ESP32 Chip ID = %04X",(uint16_t)(chipid>>32));//print High 2 bytes
Serial.printf("%08X\n",(uint32_t)chipid);//print Low 4bytes.

But when I tried to publish the Chip id, that I was getting on the serial monitor, to the MQTT, an error came up with this:

call of overloaded 'String(uint64_t)' is ambiguous

Here's my code that I tried:

char macValue[16];
String(ESP.getEfuseMac()).toCharArray(macValue,16);
client.publish("esp32/ChipID", macValue);

You would be better off formatting it nicely instead of relying on String...

char macValue[17]; // Don't forget one byte for the terminating NULL...
uint64_t mac = ESP.getEFuseMac();
sprintf(macValue, "%016x", mac);
client.publish("esp32/ChipID", macValue);

However, I'm not certain that sprintf can cope with a 64 bit value like that directly. If not, you can split it:

char macValue[17]; // Don't forget one byte for the terminating NULL...
uint64_t mac = ESP.getEFuseMac();
uint32_t hi = mac >> 32;
uint32_t lo = mac;
sprintf(macValue, "%08x%08x", hi, lo);
client.publish("esp32/ChipID", macValue);


How to split in string I want to split this:

char* value = "12;32;blue";
or
string value = "12;32;blue";

into this vars:

TV = 12;
AR = 32;
LED = "blue";

is it possible?

Scan function should do the job.

int tv, ar;
char color[10];
sscanf(value, "%d;%d;%s", &tv, &ar, color);


Arduino UNO not working? Recently I assembled my Shapeoko machine, we used Grbl shield with an Uno for the same.

For 1-2 weeks everything worked perfectly then once when I tried to work the machine, the serial communication was not working. I tried to replace the 16 MHz oscillator because I thought the problem might be with the oscillator since the LEDs were not blinking but they were lighting up.

Maybe the 5v regulator? Hard to say without the symptoms.


Need help on Arduino as ISP If I use an Arduino board to bootload a new chip, is it still possible to use the microcontroller on the board for another project, or it will only be for bootloading new chips.

There are more ways to flash a bootloader to new AVR chip. To which you refer? If you replace the chip on Uno to burn a bootloader to it with a programmer, then it is very unclear what you are asking, because the original chip is not involved in this process.

If you ask about ArduinoISP sketch, then simply it is a sketch. You upload it as any other sketch and replace it with any other sketch.


Sonar and servo stop working when usb cable unplugged I am using the following components to build simple motobot:

Arduino Uno
Arduino motor shield,
servo,
sonar HC-SR04,
magician chessis,
DC adapter with 4 AA batteries.

All works fine while USB cable is plugged. As soon as I unplug USB cable servo and sonar stop working, although motors connected to motor shield continue rolling.

From what I read around internet motor shield operates with 7-12V voltage. I need 5V for sonar and servo. So they both are connected to 5V pin on the shield board.

How could I overcome this issue?

Sonar modules are notorious for pulling so much instantaneous power during their brief pulses that they often reset the processor, causing the Arduino to start all over from the beginning.

Do you have any way of knowing whether your program is executing more-or-less normally, or if your program in the Arduino is getting reset?
If not, you need better debugging tools.

(tangential rant about debugging tools)

Many people debug by sprinkling their code with print(F()) statements that get sent to a LCD screen or a serial port.
Other people debug by sprinking their code with statements that turn on and off a series of LEDs of various colors, or at least a single LED with a (hopefully easy-to-decode) blink code.
Some kinds of problems are much easier to track down with an oscilloscope.

dealing with high-current pulses

My best guess is that the sonar is pulling very brief high-current pulses from the battery, which causes the battery voltage to droop low enough to reset the Arduino.
When the USB cable is plugged in, (I'm guessing that) the additional power supplied by the USB cable somehow keeps the Arduino from resetting.

Many sonar modules (very briefly) pull 1 A or 2 A, far more than a USB cable or a handful of AA batteries can supply.

There are many ways to solve that problem, but if I were you I would first see if that is really the problem in this case.
Possibly the quickest way to tell is:

Use at least 2 separate battery packs.
Hook all the grounds of all the battery packs and all the devices together.
hook the positive power of one battery pack to the Arduino and nothing else.
Hook the power lead of all the other devices to some other battery pack (ideally a different battery pack for each device).

Then run the test again.
This should give you a clue as to whether the problem is the Arduino seeing power-supply droop (which separate battery packs should "fix"), or something else.

If the problem really is power supply droop, there are a variety of ways to fix it:

(a) Many people recommend: use a large 1000 uF capacitor directly across the power pins of the sonar, and a 10 Ohm or 100 Ohm resistor between the battery positive and that capacitor. (a) (b) (c) (d) (e) (f)
(b) Use a large capacitor directly across the power pins of the Arduino, and a diode from the battery to that capacitor so that normally the diode allows the battery to charge the capacitor, but when the sonar or whatever briefly drags the battery voltage to a low level, the diode blocks the sonar from pulling energy "backwards" out of that capacitor, and the capacitor is large enough to run the Arduino during the sonar pulse.
(c) Get a dedicated "logic" battery array to power the Arduino and a few LEDs, etc., and a separate (often much larger) "dirty power" battery array to power the sonar, motors, etc.


Splitting a float into bytes for storage in FRAM (like EEPROM) I'm trying to write floats to I2C FRAM (like I2C EEPROM) but without result. I tried with this function but I lose all number after the decimal. Thank's for replying.

This for writing:

float floatNumber = 123.123;
byte floatPt1 = 0;
byte floatPt2 = 0;
byte floatPt3 = 0;
byte floatPt4 = 0;
byte b1 = (floatNumber);
byte b2 = (floatNumber >> 8);
byte b3 = (floatNumber >> 16);
byte b4 = (floatNumber >> 24);

This is for reading:

long floatRicomposto = 0;
floatPt1 = fram.read8(3);
floatPt2 = fram.read8(4);
floatPt3 = fram.read8(5);
floatPt4 = fram.read8(6);
//float RECOMPOSITION
floatRicomposto = (uint32_t) floatPt1 <<  0
  | (uint32_t) floatPt2 <<  8
  | (uint32_t) floatPt3 << 16
  | (uint32_t) floatPt4 << 24;

I solved it with the use of UNION:

//---------------------------------------------------------
union Scomp_float {
  // si utilizza union x float
  float temp;
  char byte_s[4];
} S_float;

//---------------------------------------------------------
//-------------------------FLOAT--------------------------------
float mioFlo = 123456.29;
byte f0 = 0;  // contengono i byte del float
byte f1 = 0;
byte f2 = 0;
byte f3 = 0;
S_float.temp = mioFlo;
f0 = S_float.byte_s[0];
f1 = S_float.byte_s[1];
f2 = S_float.byte_s[2];
f3 = S_float.byte_s[3];
Serial.println(f0);
Serial.println(f1);
Serial.println(f2);
Serial.println(f3);
fram.writeEnable(true);
fram.write8(7, f0);
fram.writeEnable(false);
fram.writeEnable(true);
fram.write8(8, f1);
fram.writeEnable(false);
fram.writeEnable(true);
fram.write8(9, f2);
fram.writeEnable(false);
fram.writeEnable(true);
fram.write8(10, f3);
fram.writeEnable(false);
S_float.byte_s[0] = fram.read8(7); // si ricompone il float
S_float.byte_s[1] = fram.read8(8);
S_float.byte_s[2] = fram.read8(9);
S_float.byte_s[3] = fram.read8(10);
float masterFloat = S_float.temp;
Serial.println(masterFloat);
//-------------------------FLOAT--------------------------------


Decoding RF receiver signals By using the following draft i decode the signals from an RF receiver

#define CH1 2
#define CH2 3
#define CH3 4
#define CH4 5
#define CH5 6
#define CH6 7

int ch1Time, ch2Time, ch3Time, ch4Time, ch5Time, ch6Time = 0;
void channels()
{
  TCNT1 = 0;
  ch1Time = 0; ch2Time = 0; ch3Time = 0; ch4Time = 0; ch5Time = 0; ch6Time = 0;

  while ((PIND & ((1 << CH1) | (1 << CH2) | (1 << CH3) | (1 << CH4) | (1 << CH5) | (1 << CH6))))
  {
    if (PIND & (1 << CH1))
      ch1Time = TCNT1;

    if (PIND & (1 << CH2))
      ch2Time = TCNT1;

    if (PIND & (1 << CH3))
      ch3Time = TCNT1;

    if (PIND & (1 << CH4))
      ch4Time = TCNT1;

    if (PIND & (1 << CH5))
      ch5Time = TCNT1;

    if (PIND & (1 << CH6))
      ch6Time = TCNT1;
  }
}

The issue is that i need also to use the 6 PWM's of the nano board.
So i thought of moving the channels 1-6 to the analog pins like so..

#define CH1 A0
#define CH2 A1
#define CH3 A2
#define CH4 A3
#define CH5 A4
#define CH6 A5

while ((PINC & ((1 << CH1) | (1 << CH2) | (1 << CH3) | (1 << CH4) | (1 << CH5) | (1 << CH6))))
  {
    if (PINC & (1 << CH1))
      ch1Time = TCNT1;
etc...

but it simply does not work. Any thoughts please?

I see two immediate problems:

The macros A0-A5 are the numbers 14 to 19, not the numbers 0 to 5 - so you're looking at (1 << 14) for CH1 not (1 << 0).
The analog pins are port C not port B, so you need to use PINC not PINB.
Your ch?Time variables should be volatile.


How to Create a water screen with solenoid valve in arduino I want to make a water screen. I will create character with solenoid valve. Sometimes sequential valve will pass to water, sometimes not pass.

And I will create some shape or character.

But I don't know how can I create this character with Arduino.

Do you have any good idea ? Can you help me ?

You can refer to this page for the generic actuation (iow Arduino board + relays shield + power supply for the valves), but that leaves one problem open: timing.

To draw something on a wall of water, you need to make sure that the water flows with a known, constant speed (unless your wall is very tall, I would ignore the effect of gravity, if the initial speed is high enough).

Maybe it can be achieved without this extra step, but to play it safe, I'd also add a pump that feeds all the valves.

This will ensure that you will have a known pressure/speed of the water, thus being able to calculate the timing of the valves.

You can use one of the relays to control also the pump.
Notice also that most likely an arduino UNO/Nano or equivalent will not be sufficient, as you will get relatively few lines.

An ArduinoMega2560 or DUE have far more GPIOs.


Initializing variables of a function By playing with some examples I found the following construct:

void Show(int nav = 0) // -1 top, 1 bottom

and I wondered what effect it has to initialize the handover parameters in the function declarations, I never noticed such an construct consciously.

So I made a small demo:

#include <M5Stack.h> //necessary for my board
  int a;
  int b;
  int c;

int addFunction(int x = 3, int y = 3){
  int result;
  result = x + y;
  return result;
}

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

  // testcase 1
  a = 1;
  b = 2;
  c = addFunction(a, b);
  Serial.println("testcase 1:");
  Serial.println((String)a + " + " + b + " = " + c);

   // testcase 2
  a = 1;
  b = 2;
  c = addFunction();
  Serial.println("testcase 2:");
  Serial.println((String)a + " + " + b + " = " + c);

   // testcase 3
  a = 1;
  b = 2;
  c = addFunction(a);
  Serial.println("testcase 3:");
  Serial.println((String)a + " + " + b + " = " + c);
}

void loop() {
}

The output was:

So I learnd:

if you hand over parameters, the initialization is ignored, if you call the function without handing over paramters, the functions works with the init values.
if you handover only one parameter it will be assigned to the first in the declaration.

Question:

Is there a syntax possible to only call the function with the second parameter, so that for the first paramter the intialized value of the declaration is used? Spoken for this example with a = 1, b = 2 you only handover b and the expected result would be 5.

This is (unfortunately) not an Arduino question. It is actually about the syntax of C++ which is a rather complex language.

The mechanism you have discovered is called default arguments. The function prototype or definition may contain the default values of the arguments. As this is a list the default values are restricted from right to left. It is not possible to use a default parameter for argument to the left of a given argument. The order is strictly right to left.

f(int x = 0, int y = 1, int z = 2)

f(1,2,3) binds x = 1, y = 2, z = 3
f(1,2) equals f(1,2,2) binds x = 1, y = 2, z = 2
f(1) equals f(1,1,2) binds x = 1, y = 1, z = 2
f() equals f(0,1,2) binds x = 0, y = 1, z = 2

There is a syntax for struct initialization (aka aggregate initialization) in C++ that allows naming of struct field values. This type of naming is not allowed for function calls.

Please read https://en.cppreference.com/w/cpp/language/default_arguments, https://en.cppreference.com/w/cpp/language/aggregate_initialization and https://en.cppreference.com/w/cpp/utility/functional/bind for more details. And a good C++ book.

There are languages that allow default arguments and named parameters e.g. C#, Python, Ruby and Smalltalk. Please see https://en.wikipedia.org/wiki/Named_parameter.

Cheers!

(Update)

Below is a rewrite of @VE7JRO Add function class using cast operator to perform the evaluation:

class Add
{
public:
  Add(int x, int y) : m_x(x), m_y(y) {}
  operator int() { return m_x + m_y; }
  void x(int x) { m_x = x; }
  void y(int y) { m_y = y; }
  int print(Print& outp) {
    int res;
    res = outp.print(F("Add(x="));
    res += outp.print(m_x);
    res += outp.print(F(",y="));
    res += outp.print(m_y);
    res += outp.print(F(")"));
    return res;
  }
private:
  int m_x, m_y;
};

Add func(1,2);

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

  func.print(Serial);
  Serial.print(F("="));
  Serial.println(func);

  func.x(12);
  func.print(Serial);
  Serial.print(F("="));
  Serial.println(func);

  func.y(13);
  func.print(Serial);
  Serial.print(F("="));
  Serial.println(func);
}

void loop() {
}


How can I handle micros() double rollover? I know that I can handle a single rollover with subtraction:

if (micros() - lastTime > period) {
  lastTime = micros();
  ...
}

But how it can be handled if this is not true or it is not checked for more than 70 minutes (without using uint64_t)?

If you want to measure times longer than 70 minutes with
micros(), you will have to use uint64_t, and there is nothing
wrong with that.

  The code needs to run with as little interruptions as possible [...]

You don't need to do the 64-bit arithmetic within the ISR. You could
very well implement an interrupt-driven 32-bit version, and then extend
it to 64 bits in non-interrupt context. Example:

// Your ISR-based implementation.
uint32_t micros32();

// Extend to 64 bits.
uint64_t micros64() {
    static uint32_t low32, high32;
    uint32_t new_low32 = micros32();
    if (new_low32 < low32) high32++;
    low32 = new_low32;
    return (uint64_t) high32 << 32 | low32;
}

This should work as long as you call micros64() often enough.
Presumably, you will have something like
if (micros64() - lastTime > period) { ... }
within your loop, so this should be no issue as long as you never block
your loop.

Actually, you can push this idea even further. If you can guarantee that
micros64() will be called at least once every 65.5 ms, then you
could have your ISR increment only a 16-bit counter.


I2C Temperature Sensor Communication Issue I'm currently learning I2C and having some issues displaying the correct temperature in the serial monitor.

I am using an Arduino Uno and an SI7021 temperature sensor from Sparkfun; here's the datasheet I'm looking at.

The datasheet says that its device address is 0x40 and the temperature register is 0xF3 (maybe I am looking at this wrong?). However when I print the result to the screen it reads -1 degrees F.

Here's my code:

// SparkFun Si7021 Humidity and Temperature Sensor
#include <SparkFun_Si7021_Breakout_Library.h>
#include <Wire.h>

//Weather sensor slave address
int WeatherAddress = 0x40;

#define Temperature_Register_DATA 0xF3

//initialize humidity and temperature variables
float humidity = 0;
float tempf = 0;

//create a sensor from the Weather library
Weather temp_rh_sensor;

void setup() {
  Serial.begin(9600);
  //create wire object
  Wire.begin();
  //begin weather sensor
  temp_rh_sensor.begin();
}

void loop() {
  //begin transmission to weather sensor
  Wire.beginTransmission(WeatherAddress);
  //ask particular register for data (temperature register)
  Wire.write(Temperature_Register_DATA);
  Wire.endTransmission();
  //request the transmitted single byte from the register
  Wire.requestFrom(Temperature_Register_DATA, 1);
  if(Wire.available() <= 1) {
    tempf = Wire.read();
  }
  Serial.print("Temp: ");
  Serial.print(tempf);
  Serial.println("F, ");
  delay(1000);
}

Wire.requestFrom(Temperature_Register_DATA, 1);

This should have the WeatherAddress as parameter instead of the register.

Wire.requestFrom(WeatherAddress, 1);


Difference between /dev/ttyACM0 and /dev/ttyS0 (Arduino IDE ports under Linux) I use the Arduino IDE to upload sketches to my Arduino Uno. My OS is Linux Ubuntu 14.04 LTS. The Arduino IDE has two ports by default for communication with the Arduino Uno:

/dev/ttyACM0
/dev/ttyS0

What is the difference between these two ports ?
What does "ACM0" and "S0" mean ?
Are there configuration files somewhere in the OS folder structure that describe the parameters of these ports ?

I know that when I select /dev/ttyACM0, I am able to send data to my Arduino Uno. However it does not work when I select /dev/ttyS0.

I just want to better understand what these ports are exactly.

/dev/ttyACM0 is a USB communication device (CDC) of sub-type "abstract control model" (ACM). That is what the Arduino is.

/dev/ttyS0 is a hardware serial port - the (typically) 9-pin D connector on the back of your computer.

If you want to use /dev/ttyS0 (why would you?!) you will require a special cable that converts the RS-232 voltage signals from the 9-pin D connector into the right TTL level signals for the Ardiuno and wire it in to the right pins on the board.


Custom ISR triggering function/value Is there a way to write a custom function which would be the mode/reason to trigger an interrupt. I have an analog joystick connected to my arduino analog pin. It reads a value of 689 on one end and 0 on the other and around 480 in the center. I would like to trigger an interrupt based on these value changes i.e an interrupt when it  more then 600 and another when less then 10. None of the pre-defined modes RISING,HIGH,LOW,FALLING,CHANGE are working satisfactorily.

No. Interrupts are hardware. You cannot "create" interrupts in software.

The closes there is to what you are after is the Analog Comparator (see section 27 of the datasheet).

The analog comparator allows you to trigger an interrupt if a voltage is above (or below) a reference voltage which is up to you to provide.

For anything more complex you would need to use external comparators to trigger on different voltage levels which then trigger external INT pins on the ATMega.


Arduino IDE installation Problems When installing the IDE there are many "Unable to open *.DLL", errors. I check "ignore errors" and the IDE installed. Now when selecting the correct port and  board the blink sketch is uploaded and several ATK 500 errors result. I have uninstalled and reinstalled the IDE several time, with repeated results.

You should check to make sure that your Java installation is up to date. It would also be best to make sure that you're bit types between the Java environment and the Arduino IDE are the same(32bit with 32bit, 64bit with 64bit). If this does not work, you should post your actual errors so we can help more :)


Two serials can't work on the same speed I have a device which sits on pins 10/11 of Arduino UNO. I am trying to send commands from my PC using Arduino to relay my commands to the device via Serial.

The problem is that if I use speed 9600 both for device and USB communication, then my commands gets damaged. Some letters are replaced by strange symbols, etc. The device uses 9600 baud rate.

If I change speed of the PC communication to 4800 (or any speed other than 9600), everything is fine. But I have to use different speeds for the communication.

I am not comfortable with the workaround, because I don't understand what's going on. Could somebody explain why the same serial port speeds causes problems?

Here is my code:

#include <SoftwareSerial.h>

#define rxPin 11
#define txPin 10

SoftwareSerial mySerial =  SoftwareSerial(rxPin, txPin);

 void setup()
 {
   digitalWrite(4,HIGH); // 1 - disable
   mySerial.begin(9600);
   Serial.begin(19200);
   while (!Serial) {;}  // wait for serial port to connect. Needed for native USB port only
   Serial.println("Begin");
 }

 void loop()
 {
  if (mySerial.available())
  {
    char c = mySerial.read();
    Serial.write(c);
  }
  if (Serial.available())
  {
    char c = Serial.read();
    mySerial.write(c);
  }
 }

I spent some time playing with your code and it seems your code actually loops the serial therefore if they are both set at 9600 as example and you print what the other one is sending like in your code you end up in a loop if you want to read what your serial is sending it is better put that values in a variable and send it

if you load your code you will get the following message in the arduino IDE once you try to connect to the serial monitor:

Error opening serial port 'COM8'. (Port busy),

your port is busy because the one serial port is reading the other all the time

one more thing I would use the following if you want to repeat a serial port:

  if (mySerial.available())
  {
    //char c = mySerial.read();
    Serial.write(mySerial.read());
  }

Hope this hels you


Most compact method of powering Arduino from wall socket There are a lot of methods to power an Arduino from a large range of voltages:

USB cable from PC or from a phone charger or an USB hub
step down converters
step up converters
switching power supply
batteries (connected to the power jack or USB or to Vin)

What I can't seem to find is a small 220V-5V converter. I'd like to put an Arduino in the wall, under a light switch, so size matters.

The last resort option is to open a 5V phone charger and replace the metal prongs that go in a socket with two wires, and replace the USB socket with another pair of wires that go the Arduino board, but still, an Arduino Pro Mini or an Arduino Nano is smaller than the phone charger.

I can suggest you to try this : AC DC Step Down Converter

It is as small as the Apple's tiny cube, and it can be placed inside of a wall easily. (I'm personally using this with an arduino micro)


Speed controller for Ceiling Fan 220V AC 100W I would like to use ESP32 to speed control my AC ceiling fan which is 220V AC 100 W.

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

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

This is the link to Speed controller available on Amazon.

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

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

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

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


How to blink 2 led strips without delay Hi all I use 2 sensors and 2 led strips. I want to let both led strips light up without interrupting each other while reading the different values from the inputs. But Arduino still pauses when one lights up, the other one needs to wait for the time to pass, either one misses reading the value when one is processing the output.

I know delay(wait); makes it block out the coming data, but it lets the strips light up for 6 seconds. If I remove it, the strips will light one 1 second only. What should I do? Thanks so much!

#include <Adafruit_NeoPixel.h>
#define PIN 6
int ledFadeTime = 7;
Adafruit_NeoPixel strip3 = Adafruit_NeoPixel(60, 9, NEO_GRB +NEO_KHZ800);//led pin
Adafruit_NeoPixel strip4 = Adafruit_NeoPixel(60, 7, NEO_GRB + NEO_KHZ800);//led pin
const int sensorPin3 = A2;//motion sensor
const int sensorPin4 = A3; //flash sensor

unsigned long strip3OnTime;
unsigned long strip4OnTime;
bool strip3On;
bool strip4On;
unsigned long previousMillis = 0;
const long interval = 1000;

void setup() {

  Serial.begin(9600);
  strip3.begin();
  strip3.show();
  strip4.begin();
  strip4.show();

  strip3On = false;
  strip4On = false;
}

void loop(){
 int Val3 = analogRead (sensorPin3); // sensor val
 int Val4 = analogRead (sensorPin4);

 Serial.print(Val3);
 Serial.print(" ");
 Serial.println(Val4);

   if (Val3>70) {
     rgbFadeInAndOut3(0, 0, 255, ledFadeTime);
     //analogWrite(strip3, HIGH);
     strip3On = true;
     strip3OnTime = millis();
   }
   if (Val4>70) {
     rgbFadeInAndOut4(0, 0, 255, ledFadeTime);
     //analogWrite(strip4, HIGH);
     strip4On = true;
     strip4OnTime = millis();
   }

   if(strip3On)
     if(millis() - strip3OnTime > 7000) {
       rgbFadeInAndOut3(0, 0, 1, 5000);
       strip3On = false;
     }
   if(strip4On)
     if(millis() - strip4OnTime > 7000) {
       rgbFadeInAndOut4(0, 0, 1, 5000);
       strip4On = false;
     }
 }

 void rgbFadeInAndOut3(uint8_t red, uint8_t green, uint8_t blue, uint8_t wait) {
   unsigned long currentMillis = millis();
   if (currentMillis - previousMillis >= interval){
     previousMillis = currentMillis;

   for(uint8_t b = 0; b <255; b++) {
      for(uint8_t i=0; i < strip3.numPixels(); i++) {
         strip3.setPixelColor(i, red * b/255, green * b/255, blue * b/255);
       }
      strip3.show();
     delay(wait);
   };

   for(uint8_t b=255; b > 0; b--) {
      for(uint8_t i = 0; i < strip4.numPixels(); i++) {
         strip3.setPixelColor(i, red * b/255, green * b/255, blue * b/255);
      }
      strip3.show();
      delay(wait);
   };
 };
 }
 void rgbFadeInAndOut4(uint8_t red, uint8_t green, uint8_t blue, uint8_t wait) {
    unsigned long currentMillis = millis();
    if (currentMillis - previousMillis >= interval){
     previousMillis = currentMillis;

   for(uint8_t b = 0; b <255; b++) {
      for(uint8_t i=0; i < strip4.numPixels(); i++) {
         strip4.setPixelColor(i, red * b/255, green * b/255, blue * b/255);
      }
      strip4.show();
      delay(wait);
   };

   for(uint8_t b=255; b > 0; b--) {
      for(uint8_t i = 0; i < strip4.numPixels(); i++) {
         strip4.setPixelColor(i, red * b/255, green * b/255, blue * b/255);
      }
      strip4.show();
      delay(wait);
   };
 };
 }

Very simple. It takes only 3 steps.

Blink an led stripe with no delay.
Blink two led stripes, using the code developed in step 1.
Enjoy your blinking let stripes.

edit: since you seem to be struggling, here is one (of countless) way(s) to do #1 above.

//blinky_ledx2.ino

//blink two led strips independently

//blinky rate
#define LED_DLY         100     //duration for led1, in ms
#define LED             12      //led to be blinked

int led = 13;

//run user routine, non-blocking
void NB_run(void (*func_ptr)(void)) {
    static uint32_t millis_next=0;                          //next match point

    if (millis() >= millis_next) {                          //time is up
        millis_next += LED_DLY;                             //advance match-up time
        func_ptr();                                         //execute user function
    }
}

//blinky example
void blinky1(void) {
    //blink LED
    digitalWrite(LED, !digitalRead(LED));
}

void setup() {
    // put your setup code here, to run once:
    pinMode(led, OUTPUT);
    pinMode(LED, OUTPUT);                                   //LED as output
}

void loop() {
    NB_run(blinky1);                                        //run blinky1 at set intervals for LED
    digitalWrite(led, !digitalRead(led));                   //blink led
}

the heart of this is NB_run() -> it executes func_ptr() once the set time has been reached. otherwise, it returns without doing anything, as shown in the example below.

D13 is blinked constantly in the main loop, while D12 is blinked based on LED_DLY, in a non-blocking fashion.

I purposely wrote NB_run() so that it needs additional "parameterization" to run multiple tasks - what you have here is the basis of a generic framework for a rudimentary pseudo multi-tasker. it is not difficult at all for you to extend the code to run 2 stripes.

good luck.

edit2: it was pointed out to me, quite correctly, that something like this can be done via rtos. true, but a typical rtos has lots of overhead and requires a more substantial hardware to support.

one exception is macro-based rtos, like protothread. in that particular implementation, you will see that there is little gain in terms of code complexity, but some stylistically.

here is an implementation of running two tasks concurrently via protothread, only code for one task is shown, however.

//thread 1
PT_THREAD(protothread1(struct pt *pt, uint32_t pr)) {
    static uint32_t time_next=0;        //time for the next blinking

    PT_BEGIN(pt);
    while (1) {
        PT_WAIT_UNTIL(pt, millis() > time_next);
        time_next += pr;                //advance time to the next match up point
        toggleLED(LED1);                //run user task - blink led1
    }
    PT_END(pt);
}

void loop() {
    protothread1(&pt1, LED1_DLY);       //running thread1
    protothread2(&pt2, LED2_DLY);       //running thread2

}

you can see that it retains largely the code structure presented earlier.

here is the outcome of that code, blinking D12/D13 at different rates.


About Arrays in Arduino I have a question about arrays in Arduino. Sorry for my bad English.
I want to put numbers in an array, and I think the code below works properly.

However, it doesn't work and corrupted numbers show up in the Serial monitor. Even delay(1000) doesn't work.

If I change ND_MAC[i]=128; to "ND_MAC[i]=126;", it works properly. So I'm wondering if this array is char type, but I designate int to array.
How to solve it?

int ND_MAC[7];
char i=0;
void setup() {
  Serial.begin(9600);
}
void loop() {
  for(i=0;i<8;i++){
    ND_MAC[i]=128;
    Serial.print(ND_MAC[i],HEX);
  }
  Serial.println();
  delay(1000);
}

For an array of size 7, the indexes start from 0 (ND_MAC[0]) and end at 6 (ND_MAC[6]) as @MikaelPatel commented.

So the solution to your issue would be changing the condition in for loop to

for(i=0;i<7;i++) //Changed 8 in your code to 7

Here, the loop iterates from i = 0 to 1 < 7 (i.e., till 6)
and it should work. :)


Sending and receiving custom messages with Ardulink I am sending custom code to Arduino with this ardulink command:

{        ArduinoControl.link.sendCustomMessage("oled");
}

Code from standard Ardulink sketch CustomMessagesChipKit.ino:

{
  if (stringComplete) {
    if(inputString.startsWith("alp://")) {
    // OK is a message I know (this is general code you can reuse)
      boolean msgRecognized = true;
      if(inputString.substring(6,10) == "cust") { // Custom Message
        // here you can write your own code.
        int separatorPosition = inputString.indexOf('/', 11 );
        int messageIdPosition = inputString.indexOf('?', 11 );
        String customId = inputString.substring(11,separatorPosition);
        String value = inputString.substring(separatorPosition + 1, messageIdPosition);
        if(customId == "oled") {
            //Clear the virtual buffer
            lcd.noBacklight();
            analogWrite(9,100);
            digitalWrite(13, HIGH);
            lcd.clear();
            lcd.setCursor(0,0);
            lcd.print("jkhgvjgv");
        } else {
          msgRecognized = false;
          // this sketch doesn't know other messages in this case command is ko (not ok)
        }
      } else {
        msgRecognized = false;
        // this sketch doesn't know other messages in this case command is ko (not ok)
      }
      // Prepare reply message if caller supply a message id (this is general code you can reuse)
      int idPosition = inputString.indexOf("?id=");
      if(idPosition != -1) {
        String id = inputString.substring(idPosition + 4);
        // print the reply
        Serial.print("alp://rply/");
        if(msgRecognized) { // this sketch doesn't know other messages in this case command is ko (not ok)
          Serial.print("ok?id=");
        } else {
          Serial.print("ko?id=");
        }
        Serial.print(id);
        Serial.write(255); // End of Message
        Serial.flush();
      }
    }
    // clear the string:
    inputString = "";
    stringComplete = false;
  }}

As a result the LED on pin 13 is turning on after message from java program. But that is all. LCD or or LED on PWM 9 pin are not reacting at all.

Also I could not understand how to send an answer back from Arduino to Ardulink. Can you please show me an example? I would love to send and print data in Java program from  DHT11 sensor in response. I know about RawDataListener and I read the whole Ardulink site, but I did not understand that. I a newbie in programming.

When i replace

{String customId = inputString.substring(11,separatorPosition);}

with

{String customId = inputString.substring(11,15);}

than everything works. What can it be?

you can read a complete (real project) example about how to receive messages from Arduino with Ardulink from here: https://github.com/openQCM

In general you can use a listener (digital, analog, and raw) to receive messages from Arduino. A raw listener receive all messages received from Arduino, so you need to implement code to filter the messages you are interested in. Digital and Analog listeners receive events from digital and analog PINs.

The sketch in your question isn't the original sketch you can find in Ardulink distribution. That sketch was written to manage the OLED on the ChipKit shield I have. You have modified the sketch to manage your LCD.

Actually you can send successfully messages from an Ardulink based application (as Ardulink Console) to Arduino since LED on PIN 13 is turned on. So the problem maybe just on your sketch.

To FIX analogWrite on PIN 9 try to set the PIN as OUTPUT with this statement:
pinMode(9, OUTPUT);

I cannot help you with lcd library that I don't know.

If you need for some help don't hesitate to write to me.


Knowing the Arduino memory capacity I am using Arduino uno. My data is storing into EEPROM whenever i run my program, it will store multiple data depend on the loop. For my program it calculate 10 sample in 0.1 sec, so 100 sample in 1 sec. How can i know how much memory i can run?

I have added this code to my program it display 895.

#include <Arduino.h>
int freeRam () {
  extern int __heap_start, *__brkval;
  int v;
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}
void setup(){
Serial.begin(9600);
Serial.println(freeRam());}
void loop(){}

The freeRam() method you are suggesting calculates the "space" between the heap and the stack, thus it returns the free SRAM.

There is no way to calculate free remaining EEPROM (if that is what you are asking), since it just contains some arbitrary data at arbitrary locations. Get the EEPROM capacity from the device data sheet and make sure to write within its boundaries.


Is it possible to use WiFi and Bluetooth / BLE in the same ESP32 project? @Majenko's answer works like a charm. I did have to make some changes as follows:

Per Majenko, you need to change the Tools > Partition scheme.  I used "No OTA (Large APP) as he suggested and it is now working.

However, the Partition Scheme option under Tools was not available for either of my devices (Huzzah32 or NodeMCU-32s).  I changed my board type (Tools > Board) to "ESP32 Dev Module" and several additional options appeared under Tools, including Partition Scheme.

Original Question: I am not able to use both the WiFi.h and BLE libraries at the same time.  Even the most minimal projects run out of memory during compile.  Am I doing something wrong?   I get identical results with both an Adafruit Huzzah32 and a NodeMCU-32S.

Does anyone know of a workaround, or barring that a suggested alternate board? A Raspberry pi zero W seems like overkill and the power consumption is ugly, so I don't want to do that unless I really have to.

#include <WiFi.h>
#include <BLEDevice.h>

void setup() {
  WiFi.mode(WIFI_MODE_STA);             // use a WiFi function
  BLEDevice::init("Minimal BLE WiFi");  // use a BLE function
}

void loop() { }

The error I get is

  Arduino: 1.8.9 (Mac OS X), Board: "NodeMCU-32S, 80MHz, 921600"

  Build options changed, rebuilding all Sketch uses 1443898 bytes (110%)
  of program storage space. Maximum is 1310720 bytes.

  Global variables use 60208 bytes (18%) of dynamic memory, leaving
  267472 bytes for local variables. Maximum is 327680 bytes. Sketch too
  big; see http://www.arduino.cc/en/Guide/Troubleshooting#size for tips
  on reducing it. Error compiling for board NodeMCU-32S.

Yes. Select a partition scheme that gives you more room. For example "No OTA (Large APP)" gives you 3MB of program space.


Compiler doesn't like function code I am getting this error from the Visual Studio compiler (I use the Visual Studio add-in Visual Micro for Arduino).

  ModelRailroadCrossingSignalController.ino:In function 'void loop()
  ModelRailroadCrossingSignalController.ino:210:15: error: too few arguments to function 'Adafruit_VS1053_FilePlayer onSignalSound(Adafruit_VS1053_FilePlayer, const char*)
  :onSignalSound()
  ModelRailroadCrossingSignalController.ino:note  declared here
  :Adafruit_VS1053_FilePlayer onSignalSound(Adafruit_VS1053_FilePlayer mp, const char* fileName) {
  Error compiling project sources

Here is the function and loop (all the defines and instances left out for brevity, they aren't the issue

void loop() {
// put your main code here, to run repeatedly

signalEntrySensor = checkEntrySensor();
if (signalEntrySensor == true) {
    if (crossingSignalInOperation == false)
    {
        Adafruit_VS1053_FilePlayer mp = onSignalSound(musicPlayer,"Trainxng.mp3");  //all other functions are called in the sound routine?
        if (debugMode)
        {
            Serial.println("Sound byte called");
        }
        while (mp.playingMusic) {
            // file is now playing in the 'background' so now's a good time
            // to do something else
            offRoadPower();
            lowerSignalArms();
            onSignalSound();
            startSignalFlashers();
            crossingSignalInOperation = true;
        }
    }
}

Adafruit_VS1053_FilePlayer onSignalSound(Adafruit_VS1053_FilePlayer mp, const char* fileName) {
// Play the train crossing sound file
if (debugMode)
{
    Serial.println(F("Playing track - "));
    Serial.print(fileName);
}
//all sound files are on the micro sd card on the music player shield
if (!mp.startPlayingFile(fileName)) {
    Serial.println(F("Could not open file "));
    Serial.print(fileName);
    while (1);
}
return mp;  }

I'm a C# guy, not ever using C++ until now, but this code should certainly work, not sure why the function is not compiling.

The clue is in the error...

  too few arguments to function 'Adafruit_VS1053_FilePlayer onSignalSound(Adafruit_VS1053_FilePlayer, const char*)

You have defined the function as this:

Adafruit_VS1053_FilePlayer onSignalSound(Adafruit_VS1053_FilePlayer mp, const char* fileName) {

And yet you then try and call it like this:

onSignalSound();

Spot the mismatch?

I suspect you don't want to be calling that function there since it seems to be in a bit where the sound has already been started.


Two devices on one UART/Serial I'm using an Arduino Mega which has 4 RX/TX UARTS/serials.
3 RX's of them I use for MIDI In
2 TX's of them I use for MIDI Out (maybe later a DMX out too)

One I use currently for debugging. On the other hand, in the future I want:

Using an ESP8266 WIFI which also seems to use an UART (both RX/TX)

Of course I can remove the debugging RX/TX, but maybe some more additions are needed and for the first RX/TX I need to remove the RX each time I upload (so I rather leave it for debugging).

I was wondering, is it possible to share an UART if I don't use the WIFI module and MIDI port at the same time?

It's certainly possible to multiplex a UART port, yes, though you will need extra hardware to do it. You will need:

A multiplexer to select between the two RX lines and feed the right one to the Arduino's RX pin
A demultiplexer to select which of the devices to send the Arduino's TX pin to.

"Analog" (de)multiplexers (e.g., CD4052) may be the simplest option since they can work in both directions. Another alternative would be combinations of tri-state buffers and glue logic to control them.


Basic if endif not working and I'm puzzled I got this small code I'm trying things on for like an hour.

int receivers = 0;
#if defined(PPM_RECEIVER)
  receivers++;
#endif

And I just cannot get it working, It keeps returning a "'receivers' does not name a type" on line 4.

You can't use commands like receivers++ outside of a function.  That is runtime executable code, and has to be run from inside a function. Global scope doesn't get executed in the same way as code in a function.


HX711 - Inconsistent Readings simulate this circuit – Schematic created using CircuitLab

Wiring is based on the scheme presented below -

(Reference: https://electronics.stackexchange.com/a/174580)

I am using Arduino Mega 2560, HX711 and four load cells to build a weighing scale but having a hard time calibrate the unit. I have tried different libraries and calibration schemes but none of them seem to help. I have found that the raw values corresponding to any given weight (including zero load) are not consistent. Firstly, the readings do not settle even after 10 minutes, and even if I take an average, the next time I put the same weight, I get an entirely different reading making the last average useless. I am seeing errors of the order of +/- 30 lbs when I put a known weight.

I first thought that maybe my load cells are the root cause but when hooked them up directly to Arduino and read the voltage across the bridge, I read stable constant values. Verified the voltage readings with a Voltmeter. (Yes, their resolution is not as good as HX711 but at least they are stable and consistent). I get the voltage reading close to my hand calculations.

Next, I tried testing the HX711 in different ways. In one test, I created a full-bridge using resistors other than load cells, forced the bridge out of balance but cannot read anything other than 16777215. Next, I wanted to see if the board is reacting to any voltage at all, so, I removed the bridge and did not connect anything to E+ and E- pins but supplied known voltages from a DC power supply (from 0 to 4.5V) to the A+ and A- (GND) pins. Now, it is reading only 8388607, no matter what voltage I supply. If I supply +5V or +3.3V from Arduino to the A+ and A- (GND) pins instead of DC Power supply, it then only reads 16777215.

I don't know how to interpret this behavior. How can I resolve the issue and bring the error down? Thanks for your help.

I have included the schematic below. All four Load Cells (LCs) are 3-wired (White, Black & Red). Resistance between W & B wires is around 1980 ohms while that between R & W or R & B is around 990 ohms. SO I connected the four LCs in the manner shown in the schematic. Wire colors have been labelled.

Code:

Code is pretty straightforward as I am simply reading raw values from the HX711 using the following HX711 library - github.com/queuetue/Q2-HX711-Arduino-Library.git

#include <Q2HX711.h>

const byte hx711_data_pin = 4;
const byte hx711_clock_pin = 8;

Q2HX711 hx711(hx711_data_pin, hx711_clock_pin);

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

void loop()
{
  Serial.println(hx711.read());
  delay(500);
}

Here is is a picture of how I have seen the sensors connected.  Is this how your is?


Use of additional i/o ports in Arduino Mega I'm a newbie in Arduino and I bought an Arduino Mega instead of the Uno. I want to know what the so-called additional i/o pins do. Are they the same with PWM and SPI? What can they do?

Additional I/O pins means more inputs and outputs. Therefore, you can have more signals. There are also some more specialized pins. For example, there are more PWM pins, more TX and RX pins for serial communication and more analog read pins.


How to use ESP8266 for wireless communication? I saw many tutorial explaining how to program ESP8266 but Specifically I didn't get any tutorials explaining how to use with Arduino or any other Microcontroller for Wireless Communication. I had a doubt how could I use it with Arduino for Serial Communication such that I could use with my handset ( using Blynk ) and with my PC.

I'm not very clear on what you are asking but I think you are saying how do you connect an ESP8266 to an Arduino so the Arduino has wireless(WIFI) access.

I'm sure there are tutorials out there so I won't go in to detail (also I don't know the details), but hopefully you will get some better terms to search with.

The basic idea is you connect the serial connection of the ESP8266 to the serial of the Arduino (via a level shifter and connect Tx to Rx).  You then write a series of AT commands to configure the ESP8266 so that what ever is receives over the serial it sends to a TCP endpoint via WIFI (and what it receives is sent to serial).

You can program the ESP via the Arduino IDE, so you could write a 'smarter' version that did all the setup for you, etc.  In fact since the ESP8266 is a faster processor with more RAM you could do a lot more on it.

If you are using an UNO or Nano you might want to look at the software serial library to let you keep the main serial port for debug messages.  If you are using a Mega then you can use one of the secondary serial ports.


How Master and Slave concept works with Bluetooth? From what I understand the master has primary control over the slaves and communicates with them. A master must always be present as well, and can be connected to (up to) 7 slaves.

Question

If I have 2 arduinos with Bluetooth communicating with each other
from within a radius of 80 meters or less, which arduino do I set as
the master and which do I set as the slave? (what dictates which one should be set as master, etc.)

I want both arduinos to be able to transmit data to one-another (where neither has privilege over the other), so in my mind this is more like two slaves communicating. Both devices have the same controls on them and will effect the other devices the exact same way.

How does the communication process work exactly, and how should more
arduinos be addressed if they are to be added with similar
privileges?

Well, master/slave concept for Bluetooth resides on the protocol, not in the communications. On few words, this means Bluetooth Master is who has the ability to initiate connection with a peripheral (or slave), but onces connected both master and slave basically can interchange information without restriction (limited by application). If your bluetooth module or implementation has a SPP (serial port profile https://developer.bluetooth.org/TechnologyOverview/Pages/SPP.aspx) once the master finds and connect to the slave, information can flow in both ways like a chat (actually, chat application is the most common usage example of bluetooth modules)


Floating-point without FPU Since a Floating Point Unit (FPU) is not present in Arduino Uno, I wanted to know how float operations are performed. If it is simulated as integer operations, I want to know how exactly the simulation is done.

As I said in my comment, all float operations are implemented in
software. As a simple test, I compiled the following program:

volatile float x, y, z;

int main(void)
{
    z = x + y;
    return 0;
}

The compiler translated the sum operation into a call to __addsf3.
This function extends its arguments to flt40_t format (non-standard 40
bits float), calls __addsf3x to do the 40-bit addition, then calls
__fp_round to convert the result into the standard float format.
__addsf3x also makes a few library calls of its own. In the end, the
addition pulled the following functions into the compiled program:
__subsf3, __addsf3, __addsf3x, __fp_inf, __fp_nan,
__fp_pscA, __fp_pscB, __fp_round, __fp_split3, __fp_splitA,
__fp_zero and __fp_szero.

All these functions are provided by the avr-libc. You can find them in
the libm/fplib directory. See for example the files:

addsf3.S
addsf3x.S
fp_round.S


making power harmonics analyser which will measure the amplitudes of the fundamental and its multiples (like 50hz, 100hz, 150hz,200 hz,...) there are) i have been  intendng to make a power frequency harmonics analyser which will measure the amplitudes of the fundamental and its multiples (like 50hz, 100hz, 150hz,200 hz,...) there are examples for making spectrum analyser with fft library's here is the example for the kosome made fft library

   #include <arduinoFFT.h>

   #define SAMPLES 128             //Must be a power of 2
   #define SAMPLING_FREQUENCY 1000 //Hz, must be less than 10000 due to ADC

   arduinoFFT FFT = arduinoFFT();

   unsigned int sampling_period_us;
   unsigned long microseconds;

   double vReal[SAMPLES];
   double vImag[SAMPLES];

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

        sampling_period_us = round(1000000*(1.0/SAMPLING_FREQUENCY));
   }

   void loop() {

        /*SAMPLING*/
        for(int i=0; i<SAMPLES; i++)
        {
            microseconds = micros();    //Overflows after around 70 minutes!

            vReal[i] = analogRead(0);
            vImag[i] = 0;

            while(micros() < (microseconds + sampling_period_us)){
            }
        }

        /*FFT*/
        FFT.Windowing(vReal, SAMPLES, FFT_WIN_TYP_HAMMING, FFT_FORWARD);
        FFT.Compute(vReal, vImag, SAMPLES, FFT_FORWARD);
        FFT.ComplexToMagnitude(vReal, vImag, SAMPLES);
        double peak = FFT.MajorPeak(vReal, SAMPLES, SAMPLING_FREQUENCY);

        /*PRINT RESULTS*/
        //Serial.println(peak);     //Print out what frequency is the most dominant.

        for(int i=0; i<(SAMPLES/2); i++)
        {
            /*View all these three lines in serial terminal to see which frequencies has which amplitudes*/

            //Serial.print((i * 1.0 * SAMPLING_FREQUENCY) / SAMPLES, 1);
            //Serial.print(" ");
            Serial.println(vReal[i], 1);    //View only this line in serial plotter to visualize the bins
        }

        //delay(1000);  //Repeat the process every second OR:
        while(1);       //Run code once
   }

how can i seperate the amplitudes for particular frequencies like amplitude of 50hz = ?, 150hz = ? and store them in other variables

The general idea of your code looks OK, but consider using a hardware timer rather than the for loop for data acquisition.  The sampling rate will be much more accurate and uniform because you eliminate (possibly cumulative) errors in timing.  See this post for an example.

Do you know how the FFT.MajorPeak function works?  If it simply finds the frequency of the largest point in the magnitude spectrum, this may not be a good measure of the 50 Hz peak etc.  Instead, consider taking the area under the curve around the frequency of interest f_0, say f_0 - 2 Hz to f_0 + 2 Hz.  The same code should be usable to measure the spectral power around any of the harmonics.

Also note that the mains electricity frequency is not exactly 50 Hz / 60 Hz.  The short-term variation is around plus/minus 1 Hz.  The above approach will also help make reliable readings.


Integrating an analog signal using Arduino Mega 2560 The sample code is this:

Sample code for Edgar Bonet

I have questions. I need to integrate the analog sine wave of 60 Hz, this signal described in the next picture, adding an offset near 2.5 V, because I can damage the Arduino board with the negative signal cycle. Internally on the Arduino board, I remove this offset, multiplying by 2, and subtracting 1.

V1=analogRead(A0)*2/1023.0-1.0;

The sampling period must be at least fs=300 Hz, T=1/fs and V1 is the signal I need integrate.

What modifications can I make to Edgar Bonet's code?

V1=analogRead(A0)*2/1023.0-1.0;

This will give you the voltage across R1 in units of 2.5 V. I do
not know whether you care or not about the units but, if you want the
voltage in volts, then:

the voltage at the Arduino input is analogRead(A0) * (5.0/1024)
to get the voltage across R1, you have to subtract 2.5 V
to get the voltage at the output of the transformer, you have to
multiply by 11.

This could be written as

float V = (analogRead(A0) * (5.0/1024) - 2.5) * 11;

but, in order to minimize the number of floating point operations, you
can simplify it to

float V = analogRead(A0) * (55.0/1024) - 27.5;

You could then integrate the voltage by running it through a function
like this:

static float integral(float x)
{
    static float y;                         // last filter output
    static uint32_t last_sample;            // last time sampled
    uint32_t now = micros();
    float dt = (now - last_sample) * 1e-6;  // step time in seconds
    last_sample = now;
    y += x * dt;
    return y;
}

Now, there is an issue with this approach: the average voltage at the
input of the Arduino is not going to be exactly 2.5 V, because
your resistors R3 and R4 will not have identical resistance. Then the
output of the integral will slowly drift and eventually become
unreasonably large.

One way to mitigate this drift problem is to measure this average using
the same Arduino running the same program: disconnect the mains, see how
the output of the program drifts, and measure the drift rate. Then you
subtract the drift rate from the 27.5 in the code, and fine tune until
there is no drift at all. There is, however, the risk that some time
later it will drift again, due to components changing behavior as the
temperature changes.

A better option would probably be to not integrate, but instead use a
first-order low-pass filter. Such a filter behaves like an integrator
for any signal faster than its cutoff frequency but, unlike a simple
integrator, it has a finite gain at zero frequency. You can turn the
integrator into a low-pass filter simply by changing the line
y += x * dt; into

y += (x - y/tau) * dt;

where tau is the time constant of the filter.


Cannot connect to mBot after using Arduino IDE Today I bought an mBot (from Makeblock) the one that uses 2.4G serial connection. After assembling it, I connected to it using mBlock (software based of Scratch) and I could control it using keyboard triggers. Then I went in Arduino IDE and used it to run some scripts on the mBot.

Next I tried to switch back to mBlock software, but now it cannot connect to the mBot anymore. Whatever Scratch-like scrips I build, they don't run anymore in mBlock.

Did I miss anything? Is there anything I can do so I can start using mBlock again?

I received some really good piece of advice on the official forum and it solved my problem, it now works:

  When you go back to using the mBlock (Scratch) environment you will
  need to reload the firmware (Upgrade firmware from the Connect menu
  item). At least that’s what I’ve had to do. Oh, and make sure that you
  have shut down the Arduino environment to release the serial port.


Using SPI without driving MISO I am developing an application where an Arduino Pro Mini communicates with a 12-bit ADC over SPI. The communication is one-way, meaning that the ADC will only send data back to the Arduino, not receive any. The MOSI pin is therefore not required in my application, only SCK and MISO.

I wish to know if there is a way to have the Arduino SPI library ignore the MOSI pin, and controlling the clock pin directly. The ADC requires 16 clock cycles to perform one conversion, sending the data back on the last 12 clock cycles. The way I have implemented it is by using SPI.transfer16() to get 16 clock cycles, and storing the return value in a 16bit variable. The downside to this is that the MOSI pin is driven, and I can therefore not use it for other purposes. I would very much like to be able to generate 16 clock cycles without the need for driving MOSI. Any ideas?

In microcontrollers, the GPIO pins have a multiplexer to select what the pin is used for.  When you use the Arduino SPI library, the initialization function will set the multiplexer to MOSI for that pin.  You should be able to run your own initialization for that pin and overwrite whatever the SPI initialization function did.  Just make sure to call your initialization after SPI.begin().  This is the simplest solution.

If that doesn't work for some reason then you can dig into the source code for the Arduino SPI library.  This isn't too hard either.

Bitbanging is the hardest solution and shouldn't be necessary for your application.


Do I need capacitors for these LEDs? I have 5 of these NeoPixel LED's.

For these particular LED's, they recommend "use of a 0.1 μF capacitor between + and ground".

Here's what I've got:

The blue's are 100 μF and the little brown ones are...I have no idea. Both were just in this starter kit. Maybe 100 pF?

So, a few questions around this...

Are these actually necessary and why?
Is there any harm in using much higher capacitors than recommended?

The capacitors are called decoupling capacitors and are used to provide current at very short notice.

The LEDs, when not fully on or fully off, switch rapidly on and off.  This switching needs current to be provided very rapidly at short notice, and batteries and power supplies aren't good at that - so you have the capacitors to act as a little reservoir of power that the LEDs can dip into.

The size of the capacitor (capacitance) can have an effect on how effective they are.  Bigger capacitors respond slower than smaller ones, but store more energy. So you need the capacitor to be small enough for it to respond fast enough. But if you have it too small it won't store enough energy to give to the LEDs and they will be unable to do their job.

0.1µF (or 100nF), aka "104" capacitors are usually reckoned to be a good rule-of-thumb value to use since they are small enough to respond rapidly and yet large enough to store enough power for most small high speed fluctuations.  The exact value though doesn't matter that much, however I would be wary about going below that, and going too high can be troublesome for other reasons as well as their slow response (google: "Inrush Current"). So you don't want to go too high. Around the 0.1µF to 1µF area is where you want to be, with maybe a 10µF for every group of 5 or so LEDs.

I would say 100µF is way too high to have on every LED, but maybe one of those on the breadboard where the power is fed in would be useful to provide a reservoir for larger low frequency demands from the rest of the board.


AVRdude does not read the FUSE byte values correctly I am exploring the ATmega328p MCU via a standard Arduino UNO, with the help of avr-gcc toolchain and AVRdude (All in the WINAVR package). I have successfully programmed the board a few times with it. However, when I try to read the fuse values via AVRdude, I get 0x0 for lfuse, hfuse and efuse.
I am using the following command (or its variants) to read:
avrdude -c arduino -p ATMEGA328p -P com3 -b 115200 -v -F -U hfuse:r:hi_fuse_val.hex:h
Following is the output I get:
avrdude.exe: safemode: lfuse reads as 0
avrdude.exe: safemode: hfuse reads as 0
avrdude.exe: safemode: efuse reads as 0
avrdude.exe: safemode: lfuse reads as 0
avrdude.exe: safemode: hfuse reads as 0
avrdude.exe: safemode: efuse reads as 0

The file hi_fuse_val.hex also has 0 written to it.What am I doing wrong?

A couple of things.  That you can't change fuses from the bootloader and that optiboot can't report fuse values correctly, even if you change them.
No self-programming of fuses
A bootloader can't write fuses, at all.  The chip just doesn't allow self-programming of fuses.  If you want to change fuses, you'd need to resort to external programming (usually using the ISP protocol) with an AVR programmer (or another Arduino set up to behave as one).
Optiboot and reading fuses
Optiboot doesn't report fuses, at least not as compiled for UNO.
The "arduino" bootloader protocol used by the avrdude -c arduino option is a modified version of the STK500(v1) protocol.  The are two commands there that would need to be implemented to read fuses, Cmnd_STK_READ_FUSE and Cmnd_STK_READ_FUSE_EXT.  They have corresponding definitions in the AVR Arduino core's copy of optiboot source.  But the places where they would be implemented in the series of if-elses are absent.  Unlike writing fuses, reading fuses is possible from AVR code.  So it's not a limitation of the chip, the code to do it just isn't there.
Sidenote: You may notice that there are also definitions for commands that write FUSES.  These exist for STK500v1 programmers rather than bootloaders, which can implement these to support writing fuses.
For what it's worth optiboot doesn't actually read the signature of the chip either.  It just reports whatever values have been baked in at compile time.  Both this and the not-reading-fuses above are probably done to keep optiboot as small as possible, which is its goal.
In any case, if you do change your fuses using a programmer, expect optiboot to continue reporting them as zero.
Current fuse values
If you're curious about your actual fuses values, you run sketch that reads them and prints them over serial by using #include <avr/boot.h> and
Serial.print('E');
Serial.print(':');
Serial.println(boot_lock_fuse_bits_get(GET_EXTENDED_FUSE_BITS), HEX);

Serial.print('H');
Serial.print(':');
Serial.println(boot_lock_fuse_bits_get(GET_HIGH_FUSE_BITS), HEX);

Serial.print('L');
Serial.print(':');
Serial.println(boot_lock_fuse_bits_get(GET_LOW_FUSE_BITS), HEX);


A simple login page on Arduino Uno I'm trying to setup home automation system controlled with webpage stored in SD card of Arduino, I was thinking if it was possible to set a login page, only combination of correct user id & password will be able to access the control page.

I have a page about a tiny web server for the Arduino Uno or similar boards. It simply isn't true that you can't make one, or that a much more powerful processor would be better. There are some limitations imposed by small amounts of RAM, but the library described there decodes incoming HTTP information "on the fly" so it can handle a reasonably large page.

You could put the data to be display into PROGMEM (more information here) or onto an SD card as someone suggested.

The login and password could be stored in EEPROM.


Arduino Uno + MSD-11-EM stepdriver + NEMA 17 I am working on Arduino code for stepper motor rotations control. I want to rotate a stepper for only 4 rotations.

The code is working fine but that will run only once as I have put that in setup().

I want to know if there will be any reverse current flowing in the circuit that would damage the Arduino or stepper. What if I want to run the stepper in the loop()? I tried but that will force the stepper to run continuously.

How can I run stepper for only 4 rotations and then stop?

I want to run it in loop().

Below is the code I am using:

#include <Stepper.h>

const int stepsPerRevolution = 2100;
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

void setup() {
  // set the speed at 60 rpm:
  myStepper.setSpeed(110);
  // initialize the serial port:
  Serial.begin(9600);
  for(int i=0;i<25;i++) {
    Serial.println("Anti-clockwise");
    myStepper.step(stepsPerRevolution);
    delay(50);
  }
}

In loop add flag to change after what you desired plus a statement to check the flag.
Code below (assuming what is in for() being enough to do 4 revolutions):

#include <Stepper.h>

const int stepsPerRevolution = 2100;
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);
bool flag = true;

void setup() {
 // set the speed at 60 rpm:
 myStepper.setSpeed(110);
 // initialize the serial port:
 Serial.begin(9600);
}

void loop {
 if (flag) {
   for(int i=0;i<25;i++) {
     Serial.println("Anti-clockwise");
     myStepper.step(stepsPerRevolution);
     delay(50);
   }
   flag = false;
 }
}

This solution gives you a flexibility to add a pushbutton to change flag and do another 4 revolutions.


Intermittent jittering servo I'm controlling a Hitech HS-625MG servo from a 10k slider via a Nano. For a while the motion tracks the slider position even when moved quickly.

Then, for no reason I can find, it will stop following smoothly & only move in jittery steps & then move as expected again!

The code is cut & paste from the pot-servo example..

#include <Servo.h>

Servo myservo_1;  // create servo object to control a servo

int potpin_1 = A0;  // analog pin used to connect the potentiometer

int val_1;    // variable to read the value from the analog pin

void setup() {
  myservo_1.attach(7);  // attaches the servo on pin 9 to the servo object
}

void loop() {
  val_1 = analogRead(potpin_1);             // reads the value of the potentiometer (value between 0 and 1023)

  val_1 = map(val_1, 0, 1023, 0, 180);      // scale it to use it with the servo (value between 0 and 180)

  myservo_1.write(val_1);                   // sets the servo position according to the scaled value

  delay(15);                                // waits for the servo to get there
                                            // have tried values ranging from 5 to 25 same behaviour
}

YouTube vid of the behaviour

Anyone seen this kinda thing before?

EDIT: That is the full code listing & here's the circuit diagram, the same as the knob example frome the Servo examples page except the servo is not being powered by the Nano but is sharing the same power supply. (sorry not next to it at the moment)

A servo motor requires a lot of current.

Many have problems when using a servo motor. Sometimes it works a few seconds and then it starts to jitter or it moves a little and then stops or it does nothing and makes a small click noise.

The problem is that servo motors requires a lot of current. Even the small servo motors can require a peak current of 0.5 A. Larger, stronger, and faster servo motors can easily request a peak of a few Amps.

To find the maximum current for the servo motor, look at the stall current of the servo motor.
When a servo starts to turn, it needs a short peak current. That peak current can be near the stall current.

Don't buy a "strong" and "fast" servo motor.
That may sound appealing, but it is better to start with a humble and timid servo motor.
The servo motors have a DC motor with gears inside. Because of the gears it is already strong.

Use a power supply of 5V with enough Amps to be able to supply the stall current of the servo motor.
Use that power supply to power the servo motor (the red wire).
Connect the GND of the power supply to the GND of the servo motor (the black wire) and the GND of the Arduino board.

The 5V pin of the Arduino board can not supply enough power for a servo motor.
It is in the official Arduino examples, but many run into problems with not enough power.


Arduino with interrupts enters in a locking state I am quite noobish with using the interrupts on Arduino and I am facing a strange problem. I am using an Arduino Pro Mini, a light sensor and an RTC module(DS3231) which has set 2 alarms, one at sunrise and one at the sunset. Each time the DST triggers the alarm, the interrupt routine (here onAlarm()) blocks the state of Arduino and nothing happens form there. Is there anything wrong with the code I write?
The code bellow is a little bit simplified, I just let the method calls, not the whole declarations of them.
#include <avr/sleep.h>//this AVR library contains the methods that controls the sleep modes
#include <avr/power.h>
#include <DS3232RTC.h>  //RTC Library https://github.com/JChristensen/DS3232RTC

#define ldrInterruptPin  2
#define DS2331interruptPin 3

void setup() {

  Serial.begin(9600);//Start Serial Comunication
  Wire.begin();

  //_____________________setup DS3231 interrupts_________
  pinMode(DS2331interruptPin, INPUT_PULLUP);
  digitalWrite(DS2331interruptPin, HIGH);
  attachInterrupt(digitalPinToInterrupt(DS2331interruptPin), onAlarm, FALLING);

  //_____________________setup LD235R interrupts_________
  pinMode(ldrInterruptPin, INPUT);
  digitalWrite(ldrInterruptPin, HIGH);
  attachInterrupt(digitalPinToInterrupt(ldrInterruptPin), irq1, RISING);

  resetDS3231Alarms();

  time_t t = RTC.get();
  setUpAlarms();
}

void loop() {
 //read the light sensor vlaues
}

Adn this is the onAlarm function:
  void onAlarm() {
  Serial.println("ALARM");
  formatTime(timestamp, RTC.get());
  if (RTC.alarm(ALARM_1))
  {
    Serial << F("SLEEP alarm at ") << timestamp << endl;
    goToSleep();
  }
  else if (RTC.alarm(ALARM_2))
  {
    Serial << F("WakeUP Alarm at ") << timestamp << endl;

    Serial.println("Time to Wake up......!");
    sleep_disable();
    Serial.println("I woke up!!!");
    attachInterrupt(digitalPinToInterrupt(ldrInterruptPin), irq1, RISING);
  }
  //update the sleep and wakeup times based on curreent day
  setUpAlarms();
};

resetAlarms()
void resetDS3231Alarms() {
  // initialize the alarms to known values, clear the alarm flags, clear the alarm interrupt flags
  RTC.setAlarm(ALM1_MATCH_DATE, 0, 0, 0, 1);
  RTC.setAlarm(ALM2_MATCH_DATE, 0, 0, 0, 1);
  RTC.alarm(ALARM_1);
  RTC.alarm(ALARM_2);
  RTC.alarmInterrupt(ALARM_1, false);
  RTC.alarmInterrupt(ALARM_2, false);
  RTC.squareWave(SQWAVE_NONE);
}

Every time an alarm occurs, the code blocks and outputs exactly what is in the serial monitor capture bellow:
It just prints "AL" form the Serial.println("ALARM"); and nothing happens from there

Does anyone know what causes this issue and how can it be solved?

When the AVR processor goes to sleep, the only way it can wake up is
by an interrupt. If it goes to sleep with interrupts disabled, then it
will never wake up.
Interrupt routines are by default non-interruptible: the first thing the
processor does when servicing an interrupt is to disable further
interrupts. Your onAlarm() function is thus running with interrupts
disabled. If it goes to sleep, it will lock the processor.
A quick and dirty fix would be to call interrupts() right before going
to sleep. I would not recommend that though, as you will end up piling
interrupt contexts one over another. The proper fix would be to trim
down your interrupt  service routines to the bare minimum that must be
done immediately, and handle everything else in regular code, within
loop(). In this particular case, setting a volatile bool might well
be the only thing you really need to do. Your loop() would test that
bool and take care of everything else.


Send data using Arduino GSM shield GET/POST/PUT? I am trying to modifiy the Arduino GSM library Xively example to geeknesia.com. The serial said "successconnecting.." but I didn't get any value change in the website. Did I make a mistake with this code?

//Project Name Test sensor
#include <GSM.h>

#define PINNUMBER ""

//APIkey untuk Geeknesia
#define APIKEY  "c3ce75cc23386ca4ca663c0ed11653c5"
#define GPRS_APN       "xlunlimited"
#define GPRS_LOGIN     ""
#define GPRS_PASSWORD  ""

GSMClient client;
GPRS gprs;
GSM gsmAccess;
GSMServer server(80);

char IPserver[]="geeknesia.com";
unsigned long lastConnectionTime = 0;
boolean lastConnected = false;
const unsigned long postingInterval = 10*1000;
int ldr1;
char ldr1_ar[10];

void setup() {
   Serial.begin(9600);
   boolean notConnected = true;
   Serial.println("try to connect...");
   while (notConnected) {
    if ((gsmAccess.begin(PINNUMBER) == GSM_READY) &
        (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD) == GPRS_READY))
      notConnected = false;
    else {
      Serial.println("can't connect");
      delay(1000);
    }
  }
  Serial.println("connected");
}

void sendData(int thisData) {
  if (client.connect(IPserver, 80)) {
    Serial.println("connecting...");
    client.print("GET /api/data?api_key=c3ce75cc23386ca4ca663c******&attributes={");
    client.print("\"ldr1\":" + String(ldr1));
    client.print("}");
    client.print("\r\n\r\n");
    client.print("Content-Length: ");
    int thisLength = 8 + getLength(thisData);
    client.println(thisLength);
    client.println("Connection: close");
    client.println();
    //client.print("cahaya,");
    client.println(thisData);
  } else {
    Serial.println("connection failed");
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
  }
  lastConnectionTime = millis();
}

int getLength(int someValue) {
  int digits = 1;
  int dividend = someValue /10;
  while (dividend > 0) {
    dividend = dividend /10;
    digits++;
  }
  return digits;
}

void loop() {
  ldr1 = analogRead(A0);
  //sendData(ldr1);
  if (client.available()) {
     char c = client.read();
     Serial.print(c);
  }
  if (!client.connected() && lastConnected) {
    client.stop();
  }
  if(!client.connected() && ((millis() - lastConnectionTime) > postingInterval)) {
    sendData(ldr1);
  }
  lastConnected = client.connected();
}

Your GET request is ill-formed. Based on your server's API docs, it should look like this instead:

Serial.println("connecting...");
client.print("GET /api/data?api_key=c3ce75cc23386ca4ca663c******&attributes={");
client.print("\"ldr1\":" + String(ldr1));
client.print("}");
client.println(" HTTP/1.1");
client.println("Host: api.geeknesia.com");
client.println();

While it is technically not illegal to have a body in a GET request, according to the HTTP 1.1 specs, the body should have no effect on the server's response i.e. it should be basically meaningless. Your server's API docs indicate that a body isn't needed/supported when you send data with GET, as is the case with most other servers.

You should consider replacing Arduino Strings with C char arrays; they're a lot safer and reliable.


ino.hex vs ino.with_bootloader.hex I'm working on a Android App able to update the content of my Arduinos. Start to work (reset the Arduino, communicate with STK500 protocol, get id of ATmega and so on).
But I face a question about the two hex files produced by the compiler.
Some FAQ, forum... give replies about the two, explaining: "the ino.hex file has only the code and the other as the code + the code of the bootloader".
After having a look at the hex files, that's true: you can find in the "with_bootloader" the code of the bootloader.

The "why" gives the following answer: "that's because when the bootloader receive the code, it erases the flash so the installed bootloader destroy itself. So if you send without bootloader, you will not have a bootloader any more in the Arduino".

Problems:

1) In that case, in order to change the bootloader why use an ISP? Just add the HEX code of your new bootloader in the main HEX file, send it with AVRDUDE and that's all...
2) When you use the Arduino IDE with AVRDUDE in Verbose mode you'll see AVRDUDE send the file....
without the bootloader!

So the question is: when you want to update the content of the flash, sending "manually" the data using STK500 protocol, do you need to send the "ino.hex" or the "ino.with_bootloader.hex" file? And why?

If flashing with AVR In System Programing (ISP) the bootloader is not needed. Only the flashing over Serial needs a bootloader.

The ISP erases the flash including the bootloader. To be able to use the serial flashing after ISP, the hex with_bootloader can be used.

I flash AVR over WiFi with esp8266's core AVRISP library and I use the hex with_bootloader to have the option of flashing later over USB.

Your Android app will use the serial flashing utilizing the bootloader. The bootloader doesn't delete itself. So you should use the hex WITHOUT bootloader.


Arduino Uno + USB Host Shield + Motor Shield We have an obstacle avoiding robot, and we decided to upgrade it by controlling it with a PS3 controller, so I am asking if above the Arduino UNO we can attach the USB host and above the Host attach the motor shield where the motors are connected to?

You need to check the I/O used by each shield to make sure there is no conflicts.


Standalone ATMEGA328: Verification mismatch on random byte on -subsequent- uploads only I have an Arduino Pro Mini as an ISP programmer with the ArduinoISP sketch running on it (19200 baud), and an addition in boards.txt that has a 'Standalone ATMEGA328 8MHz Internal' entry that specifies 8MHz and a bootloader file, along with some other things.

I'm trying to upload a simple blink sketch to an ATMEGA328 (not 328p, though the issue persists with that board as well) with no external components (internal clock)

The Problem

I can flash the bootloader no problem. I can also upload code the first time just fine. The problem is when I try to upload any different code after the first time, it gives a verification mismatch error at a seemingly random byte, complaining that 0xsomebody != 0xsomeotherbyte (also seemingly always different). This usually causes the sketch the stop working, and the LED to behave erratically.

IDE Verbose Outputs

Verbose output for burning the bootloader

Verbose output for first upload of simple sketch: basically Blink.ino

Verbose output for second upload of modified sketch: changed first delay to 1200 (side note: uploading an identical sketch doesn't give the verification mismatch error)

Verbose output for sufficiently different sketch (four digital writes, ie heartbeat example)

The Sketch

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

void loop() {
  digitalWrite(6, HIGH);
  delay(1100);
  digitalWrite(6, LOW);
  delay(400);
}

Bootloader Files

This is the boards.txt entry that I'm using:

##############################################################

atmega328bb.name=ATmega328 on a breadboard (8 MHz internal clock)

atmega328bb.upload.protocol=arduino
atmega328bb.upload.maximum_size=30720
atmega328bb.upload.speed=19200

atmega328bb.bootloader.low_fuses=0xE2
atmega328bb.bootloader.high_fuses=0xDA
atmega328bb.bootloader.extended_fuses=0x05

atmega328bb.bootloader.file=atmega/ATmegaBOOT_168_atmega328_pro_8MHz.hex
atmega328bb.bootloader.unlock_bits=0x3F
atmega328bb.bootloader.lock_bits=0x0F

atmega328bb.build.mcu=atmega328
atmega328bb.build.f_cpu=8000000L
atmega328bb.build.core=arduino:arduino
atmega328bb.build.variant=arduino:standard

atmega328bb.bootloader.tool=arduino:avrdude
atmega328bb.upload.tool=arduino:avrdude

I've added this entry to Users/me/Local/Arduino/packages/arduino/hardware/avr/1.6.17 as well as Program Files(x86)/hardware/arduino/avr

Here's the HEX file for the bootloader incase that's useful as well

The Programmer

Here's a schematic of the programmer:

The solder jumper 'CAP1' is soldered closed.

And the connections to the ATMEGA328

simulate this circuit – Schematic created using CircuitLab

And lastly, a photo of the setup:

Thanks in advance

I got some help from someone today. I oversaw a small detail when using the Arduino IDE with an ISP programmer: Hold shift when uploading to target the MCU at the end of the line rather than the MCU in the programmer.

So yeah, I hold shift when clicking upload and everything works great now. Sometimes it's the simplest things you'd never expect.


Getting Accurate Velocity Readings From IMU Hi I am currently using a BNO055 for a design project. This sensor outputs a linear acceleration vector corresponding to three (xyz) directions. I am trying to "integrate" the acceleration to get a speed the object it is mounted to is traveling.
I noticed early on that in my speed graph there is large amounts of drift.
I was looking for any guidance someone might have for tuning out the drift some way or filtering options I could use for acceleration data to reduce the drift

The process of integrating acceleration to derive velocity and integrating velocity to derive position are commonly known as dead reckoning.  In this link it is stated:

Dead reckoning is subject to cumulative errors. Advances in
navigational aids that give accurate information on position, in
particular satellite navigation using the Global Positioning System,
have made simple dead reckoning by humans obsolete for most purposes.

It may help to calibrate each of the 3 accelerometers using Earth's gravity as a constant.  Test if each accelerometer is symmetrical providing the same absolute values when pointed toward the Earth as when pointed away from the Earth. If any are not symmetric calculate an appropriate offset.  Next compare the range of each of the 3 accelerometers.  If they are not the same calculate an appropriate magnitude correction factor for maximum and minimum accelerometer ranges.
To find the offset and range correction values look at page 26 of the BNO055 specification sheet.  There you will find a picture of the BNO055 chip which relates to the direction of the X, Y and Z accelerometers.  Position the chip such that the X accelerometer is pointed downwards toward the earth.  Record the raw value.  Now repeat the measurement with the X accelerometer pointing away from the earth.  The absolute value of these two measurements should be the same.  If not, determine the offset needed to correct X accelerometer measurements and incorporate that value into your program.  Repeat this for the Y and Z vectors.
Now compare the maximum - minimum values for the X, Y and Z accelerometers.  These 3 values should be the same.  If not, find a value to multiply the smallest of the three such that it matches the middle value and incorporate that value into your program. Repeat this for the largest of the three values.
It is desired all 3 accelerometers work the same.  If they do not, using the values derived above should adjust the raw values such as the result appears as 3 nearly identical accelerometers.
That said, most accelerometers are very usable with no correction factors.  And it is expected any correction factors to be small.  However, as experienced, when integrating, small errors can accumulate quickly.
Next consider the application in which dead reckoning is to be used.  There may be clues as to the velocity at a given moment which, if used, can reset the assumed velocity to a known value.  For example, if the accelerometer were attached to a runner's foot, it can be assumed the velocity is zero for each foot to ground impact detected.


Problem with Arduuino to breadboard Mega8 I am trying to make an arduino using mega8 mcu. After so much struggling with sync/response/signature  problems and reading the previous questions, finally managed to do it (almost). However I still have some weird problems.

I uploaded the arduinoISP sketch to an Uno for programming the chips: AtMega8A-PU and AtMega8L-8PI (I had a couple of L version from years ago).

For bootloader selected the Mega8 from NG board in IDE 1.8.5 then uploaded to Mega8A-PU
for the L version cloned the ng part in boards.txt and reduced the F_CPU to 8MHz, (same bootloader code) and uploaded to 8l

Now, I'm able to upload sketches to both using a usb-serial breakout board/ avrisp mkII.

my first problem is when I disconnect the converter board neither of the MCUs can start unless I pull up or pull down the RxD pin (#2) which i find accidentally. it seems they both stuck in bootloader part. even if i leave the reset pin floating (using internal pullup) and tie the rxd pin they work fine up on applying power (with like an annoying 15~16s delay). the resistor value I tried 1K and 10K but no difference in operation and delay time. it wont start with rxd open. I couldn't find why?

another question is running the code on mega 8L as reliable as on 8A? (need it for lower V)

More clarification: they both run with Xtals and 22pf caps on breadboard. the 8l also works fine with 16MHz Xtal at 5v.

sketch (I know it's not much of help):

void setup() {
  Serial.begin(19200);
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);
  tone(10,3520);
}

volatile unsigned int i, var = 1;

void loop() {
  digitalWrite(9, HIGH);
  for(i = 0; i < 1500; i++)
                 var += ((var * 3) / 2);
                 // do something (if compiler not wipe it for optimizing :D )
  digitalWrite(9, LOW);
  Serial.println(millis());
}

sample of 8A and (similarly) uno output:

7 11 15 19 23 27 31 35 39 44 48 52 56 60 64 68 72 76 80 84 89 93 97 101 106 110

8L output @ 3.3v @8MHz:

16 24 32 40 51 59 67 75 86 94 102 110

tone() output is the same for all

Appreciate your help

I found here: https://www.arduino.cc/en/Hacking/Bootloader?from=Tutorial.Bootloader

that NG / mega8 bootloader doesn't enable the rx pin internal pullup nor it gets out of the bootloader even if receiving junk data on rx  (which was my case due to leaving it open thus floating). It also has a delay of 6 to 8 seconds intentionally.

Probably I'll use another bootloader since the link to source code on the page was broken or just program the L version without any bootloader and better fuse options.


Attiny84A and IR Sensor I have a GP2Y0A21YK0F Sharp IR Analog Distance Sensor 10-80cm + Cable, Arduino Compatible and its is connected to my Arduino. All works well and I can read the analog data with the following code:

#include <SoftwareSerial.h>
#define RX 2 // receive
#define TX 3 // transmit
#define SEN1 4
SoftwareSerial mySerial =  SoftwareSerial(RX, TX);

void setup()
{

  mySerial.begin(4800);
  mySerial.println("Hello, world?");
}

void loop() // run over and over
{

   int reading = analogRead(SEN1);
   mySerial.println(reading);
   delay(500);
}

When the code runs on the Attiny with the GP2Y0A21YK0F IR Sensor connected, the Attiny84 resets over and over. The Attiny84 and GP2Y0A21YK0F are part of the same circuit e.g. Attiny and GP2Y0A21YK0F share the power and ground rail.

When I disconnect the GP2Y0A21YK0F, the program runs and stops resetting. I was able to reproduce this on an Attiny85 and ATMega328.

The strange thing is, it works fine on the Arduino. Any help is greatly appreciated.

It sounds like the microcontroller is browning out.

IR sensors are notorious for taking a lot of power when they operate; often they will tax a small power supply and cause the voltage to droop low enough to reset/brownout the microcontroller.

Try either putting a fairly beefy capacitor on the power bus, or getting a larger power supply.

Hope this helps!

(edit: I reverted another user's edit to this answer; "droop" is in fact the correct term for what is going on: http://en.wikipedia.org/wiki/Voltage_droop)


Switch on the piezo emitter for a short time I need a short beep for every minute of change. I wrote a separate function. The signal duration should be 50 ms, the rest of the time the emitter connected to the A1 contact should be silent.
A really working sketch is shown below:
uint32_t mysound; // Variable for storing time (duration of the sound signal)
uint32_t myTimer1;
uint32_t t; //Time that always increases
byte seconds; // Seconds
byte minutes; // Minutes
int k = 1;
void setup()
{
  DDRC = B00000010; // Set pin A1 as output
  //      76543210
  Serial.begin(9600);
  myTimer1 = millis();
}

void loop()
{
  t = (millis() - myTimer1) / 1000; // Time in seconds
  seconds = t % 60; // when 60 seconds are reached, it is reset to zero
  minutes = t / 60 % 60; // Counts the minutes and drops to zero when 60 minutes are reached
  Serial.println(seconds);
  if (seconds == 0 && k)
  {
    sound();
  }
  if (seconds > 0) k = 1;
}

void sound()
{
  mysound = millis();
  while (millis() - mysound < 50)
  {
    PORTC = B00000010; // We set high voltage on pin A1 for a time of 50 ms
  }
  k = 0;
  PORTC = B00000000;
}

Your myTimer1 in t = (millis() - myTimer1) / 1000; is not set