mBlock update firmware Total Arduino newbie here.
I was playing with mBlocks, with the Arduino Uno extension enabled. That extension offers you to "update firmware" which I accidentally did. What exactly is this firmware? Is it just a compiled sketch or does it alter stuff like bootloader or reside permanently in the memory?

Usually by Firmware we understand "a program that was prepared by company that produced the hardware and that is necessary for that hardware to work correctly". I suppose that developers of mBlock are smart enough not to allow people to "brick" their Arduino's. I suspect that ether you updated your bootloader (it's also a firmware) to latest version or simply nothing happened. In both cases your device should be operational. Burning a bootloader onto an Arduino is not as hard as it seems so even if you broke something you should be able to fix it.


Write PWM with only 8 bit? (Timer2) I have a problem with the Servo library.

I need to read a PPM signal and create a PWM signal of each channel. The problem is that PPM has a higher resolution than PWM so I want to use the 16 bit Timer1 for reading PPM. However the Servo library that writes the PWM signal also uses Timer1.

Is it possible to generate a PWM signal with 8 bit / Timer2? And has someone made an example, or an explanation about, how to do that?

Yes, Arduino Servo library uses Timer1 (and other ones, depending on Arduino boards) to manage FastPWM via software interrupts. Timer2 is used by tone() function: be careful if you are using that function.

A good example using Timer2 to generate PWM is the Infrared remote library for Arduino. If IR_USE_TIMER2 is defined it will use Timer2. The key code is at IRremote.cpp where the ISR is managed.


need help regarding modification of arduino code https://youtu.be/a7cO0Zcwmvw).Can Anyone help me to remove the LED DISPLAY 16*2 code from the given below code(I just need the TM1637 LED DISPLAY code)
CODE:-
https://drive.google.com/file/d/1hJycJ3VA24xxR94xC54HCzciLk4g_uWx/view?usp=sharing

This looks like the TM1637 DISPLAY:
TM1637Display display(CLK, DIO);

And this is the 16×2 LCD:
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

All interactions with this LCD are handled by this lcd object. If you
want to get rid of it, just remove every single statement that
references this “lcd” object.


Multiple data packets with CIPSEND, associate each with pathway When using a CIPSEND from an Arduino Uno to a ESP8266 connected to the Uno is there a way to associate the data packet sent with a pathway so it can be retrieved at said pathway from the browser?

For example ESP8266WebServer.h has a command like this:

server.on(“/specificArgs”, handleSpecificArg);   //Associate the handler function to the path

where the first argument is the path/filename - what's the equivalent of this using using CIPSEND?

Your "CIPSEND" is already associated with a path.

The sequence is generally:

You configure the ESP8266 as a server, including turning on multiple connections
You browse to the IP
The browser sends a HTTP request including a path. This has a "channel" number associated with it.
You generate a HTTP response and send it to the channel given in 3 using AT+CIPSEND.

The fact that you're sending the response to the browser through the channel that the request came in through "associates" the response with the request.

To do different things depending on the path it's up to you to recognise that path in the request and generate a different response accordingly.


How to measure total energy usage of an arduino board I have a project that I'm currently working on. We have built a green wall, wich consists of plants on a wall

Now, we have a pump situated at the bottom that waters all the plants. There is an arduino board that decides when to put the pump on. Powering it is a solar panel and wind turbine. We want to know how much energy we have saved by using the solar panel and turbine.

Question:

How do I measure the amount of energy, in Wh, used from 00h00 that day? Is there a library? Or is this not possible with Arduino?

Thanks a lot.

To clear up some things

No, the pump is not fueled directly by the Arduino pin. We are using a motor shield.

Yes, there is an accumulator in the circuit. The solar and wind power recharge a battery which in turn powers the components.

I would like to know the entire energy consumed, not just the pump.

In order to calculate the amount of energy you have to calculate the power first.

The relation is

Energy = (Power * Time of usage)

How to calculate the power?

The voltage for each device in the system is constant. What changes is the current withdrawal in each component in the project.
The main thing you have here is the pump and how much does it consume current.
Usually, you will have on the "plate" of the pump the current withdrawal of it.

Say it consumes 2 Amps.
If that is not available there, use a DMM "Digital Multimeter" and connect in series with the pump and measure the amount of current.

If there are any other major/important components in your project just calculate the current withdrawal from them.

Now add up all the currents and say you ended up with 2 Amps.

If all the components are operating at the same voltage, just multiply the total amount of current withdrawal by the voltage.
WHY?
Because:
P(power) = V(voltage)   * I(current)

If not, just find the power of each component.
Add up all the powers of all you components.

Now you will only have to calculate the energy.

E(Energy) = Power * time

Time here refers to how long is your system working?
Is it a full day, couple of hours. IT doesn't matter. Usually to make things easier use time (in terms of hours).

Say your power ended up with 3kW kilo Watt
You've run the system for 2 hours every day
Energy = 3 * 2 = 6 kWh

If you've kept this for a full month.
Energy save in a month = 180kWh.

Just find out how much do the ministry cost for each kWh, and you'll know how much money you've saved!


when i compile this code it always 'sendCommand' was not declare in this scope..plzz help #include <SoftwareSerial.h>
#define DEBUG true

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

void setup() { // Open serial communications and wait for port to open:
  Serial.begin(9600); //for monitoring purposes

  sendCommand("AT+CIFS+RST\r\n", 2000, DEBUG); // reset module
  sendCommand("AT+IPR=115200\r\n", 1000, DEBUG);
  sendCommand("AT+CWMODE=1\r\n", 1000, DEBUG); // configure as access point
  sendCommand("AT+CWJAP=\"ABCDEFG\",\"12345678\"\r\n", 3000, DEBUG); //connect to a network with name ABCDEFG with password 12345678
  delay(1000);
  sendCommand("AT+CIFSR\r\n", 1000, DEBUG); // get ip address
  sendCommand("AT+CIPSTA=\"192.168.43.16\"\r\n", 1000, DEBUG);
  sendCommand("AT+CIPMUX=1\r\n", 1000, DEBUG); // configure for multiple connections
  sendCommand("AT+CIPSERVER=1,6625\r\n", 1000, DEBUG); // turn on server on port 6625
  Serial.println("Server Ready");

}

void loop() { // run over and over
  if (esp8266.available()) {
    if (esp8266.find("+IPD,0,")) {
      delay(10);
      esp8266.find(":");
      delay(10);
      char letter = esp8266.read();
      Serial.print(letter); //for monitoring purposes
      //Gets the value/char from android app
    }

String sendCommand(String command, const int timeout, boolean debug) {
  String response = "";
  esp8266.print(command); // send the read character to the esp8266
  long int time = millis();
  while ((time + timeout) > millis()) {
    while (esp8266.available()) {
      // The esp has data so display its output to the serial window
      char c = esp8266.read(); // read the next character.
      response += c;
    }
  }

  if (debug) {
    Serial.print(response);
  }
  return response;
}

In loop you have three opening braces and one closing brace. This won't end well:

void loop() { // run over and over
  if (esp8266.available()) {
    if (esp8266.find("+IPD,0,")) {
      delay(10);
      esp8266.find(":");
      delay(10);
      char letter = esp8266.read();
      Serial.print(letter); //for monitoring purposes
      //Gets the value/char from android app
    }

Two more closing braces would fix it.


How to run background music while the code for a game is executed I have some background music. If I put it at the top of the void loop(), it'll first play the music and then execute the game code afterwards.

How do I have the code run while the background music is playing?


How to connect a card reader (extracted from printer) to arduino uno I'v got this USB/SD card/CompactFlash reader from an old DELL AIO 926 printer, it's a double sided PCB board and that's all i know about it.
I tried to google it but couldn't find anything relevent, how can i tell what voltage it takes and what each wire does and how to interface it with arduino?

It seems to me that it has two sets of 4 wires (red/orange - black - yellow - white) and an extra blue wire, i'm guessing that the black is for GND, red/orange for VCC, yellow/white for SDA/XDA I2C serial bus data transfer, but no clue what the blue wire does, i could've tested this with arduino but i don't want to risk frying the board by using a wrong voltage. any help would be greately appreciated. thanks.

I can pretty much categorically say you won't get it working.

I have a similar board here with the same SMSC (now owned by Microchip) chip on it.

The interface is USB plus some other signals.  I have managed to identify the USB portion of the interface on mine, but not the other signals.

The SMSC chip has the option of using an external ROM chip to store its program, and Dell love to do that.  So, it has a custom firmware which means it doesn't get recognized by my computer without Dell's specific drivers installed.  So it's useless.

There's a very very slim chance you may get it working with a USB Host Shield, but unlikely - and at the end of the day, what's the point?  It's just an SD card reader.  Wire an SD card socket direct to the Arduino and save yourself both the headaches of trying to work it out and also the massive pointless expense in buying the hardware you'll need to do the interfacing.


How can I use a variable to choose which Serial port to interact with? In my use case I have multiple devices connected to the serial ports of an arduino. Currently I write to them using Serial1.write(), Serial2.write(), etc.

How can I choose the port programmatically, for example:

for(int i = 0; i < numDevices; i++){
  Serial[i].write();
}

You may use an array of pointers to the actual serial ports. For
example, on an Arduino Mega:

const size_t PORTS_COUNT = 4;
const HardwareSerial *ports[PORTS_COUNT] = {
    &Serial, &Serial1, &Serial2, &Serial3
};

void setup() {
    for (size_t i = 0; i < PORTS_COUNT; i++)
        ports[i]->begin(9600);
}


How do I make specific tones with a piezo buzzer? I am using a piezo buzzer and fiddling around with it a little bit. I currently have different tones with delays in between and I have to do a lot of trial and error for the piezo buzzer to play sounds like I want it to. Is there a better way to do this? because at this rate I will be stuck for a while.

I am trying to get the piezo buzzer to make the sound of an alarm. Any suggestion on how I can get it to sound exactly like an alarm or is trial and error the only way?

It's very hard to know from your question what you are having trouble with.  I have a piano and I can hit the keys, but it takes me a long time to hit them in the right order and with the right timings to create a new symphony.

Anyway, if creating the sounds is the problem, have you looked at the Tone library?

Different alarms have different sounds.  I once heard an alarm which sounded like the start of Fuer Elise, so probably the notes were E and D#.  That would make their frequencies about 330Hz and 311Hz:

void loop()
{
    tone(pin, 330, 250);
    delay(300);
    tone(pin, 311, 250);
    delay(300);
}

The sound you linked to sounds to me like it starts on a C, and slides up gradually one octave.  One octave higher is double the frequency, so this code should do that:

void loop()
{
    const int startFreq = 523;  // C5 is 523Hz

    // Start at the given freqency, and increase gradually by
    // one octave (double the frequency)
    for (int freq=startFreq ; freq<= (startFreq*2) ; ++freq)
    {
        tone(pin, freq, 10);
        delay(3);
    }
}


Is possible to process analogue inputs with variation frequencies in MHz? Is it possible for Arduino boards to accurately process analog inputs that vary at MHz frequencies?

If possible, which Arduino board would be most appropriate for such application?

What adjustments would be required for it to handle such rapid analog input variations?

Your typical ATMega-base Arduino cannot sample anywhere near that kind of speed.

It takes 13 clock cycles to sample an analog value on an ATMega chip, and the maximum clock frequency for the ADC is 1MHz. That gives you an absolute maximum sampling speed of 76923 samples per second. That means the highest frequency you can sample is 38461Hz.

There are better chips on the market with higher sampling speeds, but they aren't Arduino. Some can sample at the tens of millions of samples per second allowing you to sample frequencies in the low MHz. Other specialised ADC chips are available that can sample in the Gsps range which are what are used in oscilloscopes and high speed communication (fibre optic) systems etc. Working with these kind of chips needs quite a lot of skill though as the analog signal paths requires special design and consideration.

Also when sampling at those kind of frequencies you need a lot of high-speed memory, which no Arduino can ever even consider the possibility of having.


how to create a specific buffer when there is no buffer message in the data packet? So I'm trying to understand a read method. In this method,

// Read data from buffer
int SoftwareSerial::read()
{
if (!isListening())
  return -1;

// Empty buffer?
if (_receive_buffer_head == _receive_buffer_tail)
  return -1;

// Read from "head"
uint8_t d = _receive_buffer[_receive_buffer_head]; // grab next byte
_receive_buffer_head = (_receive_buffer_head + 1) % _SS_MAX_RX_BUFF;
return d;
}

it looks it receives buffer head. But in the write only a 1 or 0 is being sent as the data packet's header. Nothing else. So how does the arduino know how big of an buffer to create?
also, there is no stop bit being transmitted, so how does it look at a buffer tail? Or is this all created regardless of the transmitter? and then, all the values just get read into the buffer, and then read again from there? Also I don't see a delay in this read method. Wouldn't that cause errors in the data flow? How is that being handled?

That read method just retrieves bytes that have already been received from an internal buffer.

The buffer is pre-allocated to a specific size (64 bytes) and that is how many bytes can be received before you start to lose data as it gets overwritten.  You have to be sure to read your data from the buffer before it overflows.

The function that actually receives each UART bit from the IO port, builds them into bytes, and stores them in the internal buffer, is this one:

void SoftwareSerial::recv()
{

#if GCC_VERSION < 40302
// Work-around for avr-gcc 4.3.0 OSX version bug
// Preserve the registers that the compiler misses
// (courtesy of Arduino forum user *etracer*)
  asm volatile(
    "push r18 \n\t"
    "push r19 \n\t"
    "push r20 \n\t"
    "push r21 \n\t"
    "push r22 \n\t"
    "push r23 \n\t"
    "push r26 \n\t"
    "push r27 \n\t"
    ::);
#endif

  uint8_t d = 0;

  // If RX line is high, then we don't see any start bit
  // so interrupt is probably not for us
  if (_inverse_logic ? rx_pin_read() : !rx_pin_read())
  {
    // Wait approximately 1/2 of a bit width to "center" the sample
    tunedDelay(_rx_delay_centering);
    DebugPulse(_DEBUG_PIN2, 1);

    // Read each of the 8 bits
    for (uint8_t i=0x1; i; i <<= 1)
    {
      tunedDelay(_rx_delay_intrabit);
      DebugPulse(_DEBUG_PIN2, 1);
      uint8_t noti = ~i;
      if (rx_pin_read())
        d |= i;
      else // else clause added to ensure function timing is ~balanced
        d &= noti;
    }

    // skip the stop bit
    tunedDelay(_rx_delay_stopbit);
    DebugPulse(_DEBUG_PIN2, 1);

    if (_inverse_logic)
      d = ~d;

    // if buffer full, set the overflow flag and return
    if ((_receive_buffer_tail + 1) % _SS_MAX_RX_BUFF != _receive_buffer_head)
    {
      // save new data in buffer: tail points to where byte goes
      _receive_buffer[_receive_buffer_tail] = d; // save new byte
      _receive_buffer_tail = (_receive_buffer_tail + 1) % _SS_MAX_RX_BUFF;
    }
    else
    {
#if _DEBUG // for scope: pulse pin as overflow indictator
      DebugPulse(_DEBUG_PIN1, 1);
#endif
      _buffer_overflow = true;
    }
  }

#if GCC_VERSION < 40302
// Work-around for avr-gcc 4.3.0 OSX version bug
// Restore the registers that the compiler misses
  asm volatile(
    "pop r27 \n\t"
    "pop r26 \n\t"
    "pop r23 \n\t"
    "pop r22 \n\t"
    "pop r21 \n\t"
    "pop r20 \n\t"
    "pop r19 \n\t"
    "pop r18 \n\t"
    ::);
#endif
}

To show you how the timing of the routine works, here is a little diagram:


How to transmit Float sensor values via NRF24L01 module? I'm trying to figure out a way to transmit four sensor values: Voltage, Current, Power and consumption but I'm unable to do that.
Yet, my syntax is correct... what am I missing?

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

#define ACS712 A0

int lastData = 0;
int dataSum = 0;
int Count = 0;

float Voltage;
float Current;
float Power;
float kWh;
float Consumption;
String Data;

float vpc = 4.882813; // approx. voltage per count

RF24 radio(9, 10); // CE, CSN
const byte addresses[][6] = {"00001", "00002"};

void setup() {
  Serial.begin(115200);
  pinMode(13, OUTPUT);
  radio.begin();
  radio.openWritingPipe(addresses[1]); // 00001
  radio.openReadingPipe(1, addresses[0]); // 00002
  radio.setPALevel(RF24_PA_MIN);
  radio.startListening();
}

void loop() {

  radio.stopListening();

  if (millis() > lastData + 1) {
    dataSum += sq(analogRead(ACS712) - 512);
    Count++;

    lastData = millis();
  }
  // If statement to make calculations.
  if (Count == 1000) {

    // To get the RMS of the data.
    float mean = dataSum / Count;
    float value = sqrt(mean);

    // To get the Voltage (in volts) consumed.
    float Voltage = value * vpc;

    // To get the Current (in amps) consumed.
    float Current = Voltage / 66;

    // To get the Power (in watts) consumed.
    float Power = Current * 240;

    float kWh = Power / 1000;
    float Consumption = kWh;

    dataSum = 0;
    Count = 0;

    Data += F("\nVoltage: ");
    Data += String(Voltage, 3);
    Data += F("\nCurrent: ");
    Data += String(Current, 3);
    Data += F("\nPower: ");
    Data += String(Power, 3);
    Data += F("\nConsumption: ");
    Data += String(Consumption, 3);
    //Serial.println(Data);

    radio.write(&Data, sizeof(Data));
    if (radio.write(&Data, sizeof(Data)) && true) {
      Serial.println("Sent!");
    } else {
      Serial.println("Failed!");
    };
    delay(10);
  }
}

Simple float transmission:
For TX use
float payload = 0.12345;
radio.write(&payload, sizeof(payload));

For RX use
float payload = 0;
radio.read(&payload, sizeof(payload));


Not sure if programmer or ATMega is burned some time ago i tried doing this with my original arduino uno r3. I guess i had to plug the power cables in wrong order(i think it's called reversing polarity)  because my arduino stoped working. It turns on (the power diode is on) but i cannot upload any sketch on it. I'm thinking about changing the ATMega chip but, before i do that i want to be certain that it's the chip issue ,not the programmer. I have another arduino uno, and i heard that i can upload sketch with it to another uno. So my idea is, if i do this i will be able to say whether it's the programmer or the chip issue. The only problem is that i don't know how to do this and i wasn't able to find any reasonable tutorials online. Please tell me what to do.
Many Thanks,
Jan

The Arduino IDE ships with a built in ArduinoISP sketch, and there is a very detailed tutorial with wiring diagrams etc on the Arduino site.


Data changes when working with classes When I pass an array, and it's len to the constructor of a class. I store the length, and access it later, it's value changes, seemingly at random.

#include "Arduino.h"

#define NUMSENSORS 2
const byte dataPins[] = {A5, A4};

class B {
    public:
        B(byte pin) { _pin = pin; }
        byte getPin() { return _pin; }
    private:
        byte _pin;
};

class A {
    public:
        A(const byte sensorPins[], int len) {
            Serial.print("provided len is: ");
            Serial.println(len);
            _len = len;
            Serial.print("Stored len is: ");
            Serial.println(_len);
            for (int i=0; i<len; i++) { myBarray[i] = new B(sensorPins[i]); }
        }
        B* myBarray[];
        int _len;
        void printLen() {
            Serial.print("Length is: ");
            Serial.println(_len);
        }
};

void setup() {
    Serial.begin(115200);
    A test(dataPins, NUMSENSORS);
    for (uint8_t i=0; i<10; i++) {
        test.printLen();
        delay(100);
    }
}

void loop() {
}

The value of len is fine in the constructor,  but is different when I call it in the function "getLen".

I feel as though it has something to do with pointers. Because if I comment out the for loop in the constructor of A, the value is correct.

Any help would be greatly appreciated, thanks in advance.

Let us do this with a template class and avoid malloc, etc.

#define membersof(x) (sizeof(x) / sizeof(x[0]))

const byte dataPins[] = { A5, A4 };

class B {
public:
  byte getPin() { return (_pin); }
  void setPin(byte pin) { _pin = pin; }
private:
  byte _pin;
};

template<unsigned len>
class A {
public:
  A(const byte sensorPins[]) {
    for (unsigned i = 0; i < len; i++)
      _vec[i].setPin(sensorPins[i]);
  }
  unsigned getLen() { return (len); }
  B* getB(unsigned ix) { return (ix < len ? &_vec[ix] : NULL); }

private:
  B _vec[len];
};

void setup() {
  Serial.begin(115200);
  A<membersof(dataPins)> test(dataPins);
  unsigned len = test.getLen();
  Serial.print(F("test.getLen()="));
  Serial.println(len);
  for (unsigned i = 0; i < len; i++) {
    B* bp = test.getB(i);
    Serial.print(F("test::B["));
    Serial.print(i);
    Serial.print(F("].getPin()="));
    Serial.println(bp->getPin());
  }
}

void loop() {
}

Cheers!


Large(ish) strings failing to send over WiFi101 using WiFiServer I've based a sketch off the vanilla WiFi101 server examples.

If I define a const char array like this:

const char HTML_index[] = "test";

The server works well.  However if I increase the char[] size to about 1,300 bytes the server fails to send a response.  The device (Feather M0 WiFi) doesn't lock up, I can continue to make HTTP requests and the serial console functions correctly, just no HTTP response.  The device and laptop (client) are both on the same WiFi AP so nothing weird there.

First I thought this was a memory issues, but as I'm using newer architecture and IDE using const should ensure the string is in FLASH.

So I then read some threads about buffer limits per response using other libraries: https://github.com/esp8266/Arduino/issues/3205

But again not sure how applicable this is to an ARM based system/ WiFi101 library.

Is there a limiting buffer size etc when sending HTTP data in my setup? Do I need to split the string up into smaller pieces and send multiple responses?  How could I go about debugging this situation?

Edit:
This is the example sketch my code is based off:
https://www.arduino.cc/en/Tutorial/Wifi101SimpleWebServerWiFi

Edit2: ok I think I know what's going on but can't test right now, will post an answer when I do.  I found this thread https://github.com/arduino-libraries/WiFi101/issues/163 which talks about SOCKET_BUFFER_UDP_SIZE.  So I looked through the WiFi101 src and found this:

#ifdef LIMITED_RAM_DEVICE
#define SOCKET_BUFFER_SIZE 64
#else
#define SOCKET_BUFFER_SIZE 1472
#endif

https://github.com/arduino-libraries/WiFi101/blob/master/src/utility/WiFiSocket.cpp

It's likely that my string was actually over 1472 bytes so this makes sense.

Edit3:
Found more references:

https://github.com/arduino-libraries/ArduinoHttpClient/issues/14

https://github.com/arduino-libraries/WiFi101/pull/116

So I take it the 1500 in WINC1500 could mean the buffer size.  Either way looks like there's a hardware buffer limit and responses larger than ~1400 bytes need to be chunked.

As per my notes the WINC1500 has a limit of 1500 bytes per transmission.  But some of this is always taken up by TCP overhead so the payload buffer must be smaller, that's why you see numbers like 1460.

From:
http://ww1.microchip.com/downloads/en/appnotes/atmel-42739-tcp-client-and-server-operation-using-atwinc1500_at14596_applicationnote.pdf

  2.2.2 TCP Packet Size

  A packet is sized as per the lowest MTU (Maximum
  Transmission Unit) on the path, which is typically 1500 bytes (for
  Ethernet) of data including TCP (20 bytes) and IP headers (20 bytes).
  The packet size is defined in main.h as :

#define MAIN_WIFI_M2M_BUFFER_SIZE 1460

  The application then defines a socket buffer of this size in main.c as:

static uint8_t gau8SocketTestBuffer[MAIN_WIFI_M2M_BUFFER_SIZE];

This means that HTTP responses over ~1400 bytes need to be chunked which means split up into multiple calls.

FYI chunked Transfer-Encoding is superseded in HTTP/2:
http://undertow.io/blog/2015/04/27/An-in-depth-overview-of-HTTP2.html

Info on HTTP chunked encoding:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Transfer-Encoding

Transfer-Encoding: chunked

  Data is sent in a series of chunks. The Content-Length header is
  omitted in this case and at the beginning of each chunk you need to
  add the length of the current chunk in hexadecimal format, followed by
  '\r\n' and then the chunk itself, followed by another '\r\n'. The
  terminating chunk is a regular chunk, with the exception that its
  length is zero. It is followed by the trailer, which consists of a
  (possibly empty) sequence of entity header fields.

https://www.httpwatch.com/httpgallery/chunked/

https://gist.github.com/CMCDragonkai/6bfade6431e9ffb7fe88

  Transfer-Encoding

  The use of Transfer-Encoding: chunked is what allows streaming within
  a single request or response. This means that the data is transmitted
  in a chunked manner, and does not impact the representation of the
  content.

  Officially an HTTP client is meant to send a request with a TE header
  field that specifies what kinds of transfer encodings the client is
  willing to accept. This is not always sent, however most servers
  assume that clients can process chunked encodings.

  The chunked transfer encoding makes better use of persistent TCP
  connections, which HTTP 1.1 assumes to be true by default.

  Chunked data is represented in this manner:

4\r\n
Wiki\r\n
5\r\n
pedia\r\n
e\r\n
 in\r\n\r\nchunks.\r\n
0\r\n
\r\n

  Each chunk starts with its byte length expressed as a hexadecimal
  number followed by optional parameters (chunk extension) and a
  terminating CRLF sequence, followed by the chunk data. The final chunk
  is terminated by a CRLF sequence.

  Chunk extensions can be used to indicate a message digest or an
  estimated progress. They are just custom metadata that your layer 7
  receiver needs to parse. There's no standardised format for it.
  Because of this, it's probably better to just add your metadata (if
  any) into the chunk itself for your layer 7.5 application to parse.

  For your application to send out chunked data, you must first send out
  the Transfer-Encoding header, and then you must flush content in
  chunks according to the chunk format. If you don't have an appropriate
  HTTP server that handles this, then you need to implement the syntax
  generator yourself. Sometimes you can use a library to provide an
  abstract interface.

Possible fix on Arduino platforms is to use StreamLib library or roll-your-own chunking system.

Update:  I hacked together a sketch and confirmed this works.  Next issue was the buffer must be null terminated, BUT this is stripped out before transmitted over TCP so the HTTP chunk size is the buffer size -1.


Arduino IDE doesn't find header file I'm trying to start with the SainSmart 4x20 serial LCD, and copied the library to the Arduino library:

So LiquidCrystal_I2C.h is included. But when I try to compile an example sketch it says

  Arduino: 1.7.0 (Windows 7), Board: "Arduino Uno"

  HelloWorld_i2c.pde:2:31: fatal error: LiquidCrystal_I2C.h: No such file or directory

  compilation terminated.

  Error compiling.

Any ideas how to fix this?

I copied the SainSmart library to the IDE's library folder, not noticing that there was already a folder named "LiquidCrystal". Apparently the files added to the existing folder are being ignored.

Renaming the SainSmart library before adding it solves the problem.


Second item in array not gets assigned from struct object, ArduinoJson I got the below code generated this amazing tool.

const size_t capacity = JSON_ARRAY_SIZE(2) + JSON_OBJECT_SIZE(1) + JSON_OBJECT_SIZE(4) + 2*JSON_OBJECT_SIZE(7);
DynamicJsonDocument doc(capacity);

JsonObject config = doc.createNestedObject("config");
config["type"] = "power_plug";
config["chip_id"] = "12345";
config["mac_address"] = "abc";

JsonArray config_attachments = config.createNestedArray("attachments");

JsonObject config_attachments_0 = config_attachments.createNestedObject();
config_attachments_0["name"] = "socket";
config_attachments_0["input_type"] = "toggle_switch";
config_attachments_0["on_state"] = "on";
config_attachments_0["off_state"] = "off";
config_attachments_0["pin_type"] = "output";
config_attachments_0["pin"] = 15;
config_attachments_0["current_state"] = "on";

JsonObject config_attachments_1 = config_attachments.createNestedObject();
config_attachments_1["name"] = "socket_1";
config_attachments_1["input_type"] = "toggle_switch";
config_attachments_1["on_state"] = "on";
config_attachments_1["off_state"] = "off";
config_attachments_1["pin_type"] = "output";
config_attachments_1["pin"] = 12;
config_attachments_1["current_state"] = "off";

serializeJson(doc, Serial);

This prints out the desired json properly. but when amend single line from the second array item, to take the on_state from my struct object d_config,

Serial.println(">>" + d_configs.peripherals[1].current_state);
Serial.println(">>" + d_configs.peripherals[1].on_state);
config_attachments_1["on_state"] = d_configs.peripherals[1].on_state;

the parsing gets quiet unexpected, and some of the keys from serialised string json gets missing. For above case, This gets printed in serial monitor;

>>off
>>on
{"config":{"type":"power_plug","chip_id":"12345","mac_address":"abc","attachments":[{"name":"socket","input_type":"toggle_switch","on_state":"on","off_state":"off","pin_type":"output","pin":15,"current_state":"on"},{"name":"socket_1","input_type":"toggle_switch","on_state":"on","off_state":"off","pin_type":"output","pin":12}]}}

NOTE in the second item of attachments, the key current_state is entirely missing.
When I assign all values from this struct object, the serialised json misses many more keys... and the behaviour is quite unexpected. here is how I have defined my structs;

typedef struct Peripheral{
    String name;
    String input_type;
    String on_state;
    String off_state;
    String pin_type;
    String current_state;
    int pin;
};

typedef struct {
  String type;
  String chip_id;
  String mac_address;
  Peripheral peripherals[10];
} DeviceConfig;

I am not sure if its an issue during serialization or something else... :/
Any help would be highly appreciated :) .

UPDATE When I added three items inside attachments, then the serialized json string is missing some keys for only the last item. Seems like only the last item on the list is having problem getting serialized.

ArduinoJson stores strings differently depending on their types:

for const char*, it saves a pointer;
for other types (char*, String...) it copies the string.

Because ArduinoJson stores the copy of the string in the JsonDocument, you must increase the capacity of the JsonDocument.

In your case, you pass Peripheral::current_state, which is a String, so ArduinoJson makes a copy in the JsonDocument. Increasing capacity by a few bytes should solve the problem.

Note that the ArduinoJson Assistant also computes the number of bytes required to store all the strings. Look for "Additional bytes for strings duplication" on the right panel.


2.8" tft screen arduino all pins used I'm trying to connect a 2.8" display but it uses all the pins. That similar to this post (here: 2.8" TFT Touchscreen Prohibits Access to Unused Pins)

However, they recommend a proto screw shield (show here: http://www.mouser.com/ProductDetail/Adafruit/196/?qs=GURawfaeGuDa14An8N8oeg%3D%3D&gclid=CKjBqd2xpMgCFQiVfgodN5wCbA&kpid=1480459155)

However, how would that work? I'm a bit of a noob -- does anyone have any diagrams of it being connected, etc?

Thanks!

You're confusing the idea of using all the pins to that of plugging into all the pins.

Yes, your shield may well have all the pins on it which then fill all the available holes.  Only some of them will actually be connected to anything on the circuit board though.

The breakout board you link to basically provides a "tee" connection to all the pins, so that you can then get to the pins that, while they may have a lump of metal plugged into them, don't electrically connect to anything at all.

You should look at the schematic for your TFT screen to see exactly which pins are in use and which are there but not wired to anything.


Eeprom write function does not seem to write in more than 100 locations I am trying log my sensor data (1 byte each) on my Arduino Uno Eeprom. I have an ATmega328 on it, so it should allow me to write up to 1Kb on it, however I've tried the Eeprom write command and it does not seem to write to more than 100 locations on it (the first 100 bytes!)

I am using the Eepromex library.

Any thoughts on what's causing this?

Edit:

These are the excerpts from my code related to Eeprom logging:

int addr1 = 0;
int addr2 = 256;

  // Store Data in EEPROM

  EEPROM.write(addr1,FinalMoisture[0]);

    delay(5);

  EEPROM.write(addr2,FinalMoisture[1]);

    delay(5);
  // advance index pointer to the next location.  There are 256 bytes assigned for each sensor in the EEPROM, so go back to 0 when we hit 255/511.

  addr1 = addr1 + 1;

  if (addr1 == 255)
    addr1 = 0;

  //same for addr 2 :

   addr2 = addr2 + 1;

  if (addr2 == 511)
    addr2 = 256;

  // delay until next measurement (msec)
 Sleepy::loseSomeTime(30000);

PS: As mentioned earlier I've included the EepromEx library. Each sensor stores only first 50 locations. Also, I've noticed that if I run a single loop instead of storing data in two locations, I can write 100 straight entries. In any case it seems that the write function is limited to 100?

Could this be a setting in the library? How to disable/modify it? I tried looking at the info on the lib author's postings but didn't help.

Looking at the library at https://github.com/thijse/Arduino-EEPROMEx/blob/master/EEPROMex.cpp it seems they limit the number of writes to 100:

EEPROMClassEx::EEPROMClassEx()
  :  _allowedWrites(100)
{
}

There seems to be a way of changing that:

/**
 * Set global maximum of allowed writes
 */
void EEPROMClassEx::setMaxAllowedWrites(int allowedWrites) {
#ifdef _EEPROMEX_DEBUG
    _allowedWrites = allowedWrites;
#endif
}


NewliquidCrystal example HelloWorld_i2c just flickers I've bought a cheap I2C LCD display (specs in the end of this question).

I can't make it print. I've tested with two displays of same model, so nothing is broken.

I am using the NewliquidCrystal 1.3.4 library, ie not the "normal" LiquidCrystal library. I'm trying with the I2C example called HelloWorld_i2c (link to example code). I've only changed the address from 0x37 to 0x27.

It compiles fine, but the result is only that the display flickers.

What is wrong and how do I fix it?

Super simple example flickers too

Well, this one gives just one blink.

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27);  // Set the LCD I2C address
void setup()
{
  lcd.begin(16,2);               // initialize the lcd
  lcd.home ();                   // go home
  lcd.print("Hello, ARDUINO ");
}
void loop()
{
}

Pictures

In the light it shows that the writing to the display is randomly jumping around.

In the dark, it shows that the background light flickers:

Details about the LCD display

Text on the backside

YwRobot Arduino
QAPASS
LCM1602 IIC V1

Text on the chip

TLPCF85747
HA
T62281
A N 1
I L knM988223

I was able to make the example run as intended, by using a different constructor call:

LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

I am not able to tell you, what these parameters and values mean. However, the documentation for this constructor is shown below (source).

/*!
    @method
    @abstract   Class constructor.
    @discussion Initializes class variables and defines the I2C address of the
    LCD. The constructor does not initialize the LCD.

    @param      lcd_Addr[in] I2C address of the IO expansion module. For I2CLCDextraIO,
    the address can be configured using the on board jumpers.
    @param      En[in] LCD En (Enable) pin connected to the IO extender module
    @param      Rw[in] LCD Rw (Read/write) pin connected to the IO extender module
    @param      Rs[in] LCD Rs (Reset) pin connected to the IO extender module
    @param      d0[in] LCD data 0 pin map on IO extender module
    @param      d1[in] LCD data 1 pin map on IO extender module
    @param      d2[in] LCD data 2 pin map on IO extender module
    @param      d3[in] LCD data 3 pin map on IO extender module
    */
   LiquidCrystal_I2C( uint8_t lcd_Addr, uint8_t En, uint8_t Rw, uint8_t Rs,
                     uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3 )
;


What are the applicable processor for the ATmega32u4? And what are higher versions of ATmega32u4? Can arduino uno smd r3 version handle a Keyboard.h library?  it is not applicable for that arduino?

The Arduino Uno cannot use the Keyboard library. The microcontroller needs to have a native USB interface. The Uno uses the Atmega328p, which does not have one.

You can use the Arduino Micro or Arduino Leonardo for this.

For more experienced hackers: If you need to use the Uno, but still want to use extended USB capabilities (more than USB to Serial), it is possible to reprogram the Atmega32U4 on the Uno, which is only used as USB to Serial adapter chip, but of course has native USB capabilities and could create a HID/Keyboard input on the USB interface. Since that is not a task for beginners, it is not applicable for this question, but should be mentioned for future readers.


Warning when verifying sketch with VS code I use Visual Studio Code to develop for arduino which uses Arduino Studio installed files and needs the installation to work. This works very well.

Annoying is that when verifying a sketch it takes longer than in the Arduino IDE. I suspect the following warning to cause it:

  [Warning] Output path is not specified. Unable to reuse previously
  compiled files. Verify could be slow. See README.

I would like to get rid of the warning and I searched through all README files in the arduino installation folder and I also searched google but haven't found out what its supposed to mean and how to fix it. No readme file mentions that or I overlooked it.

Is there a documentation on how to fix this anywhere?

Thanks to @Majenko I looked some place new:

documented in the arduino plugin of VS Code Arduino Extension there is an option to set an output directory.
Note though that according to this it should not be in the workspace or subfolders.

So in arduino.json settings file add:

"output": "../ArduinoOutput"


ACS712 inacurrate reading. Wild jumping I'm trying to use my 30A ACS712 on my OSD (it has ATMEGA16L).

But it is very unstable, 0 amps goes from 450 to 445, but that isn't that bad, but when I put 10A of current through it jumps from 440 to 380.

I already searched on google and tried to add filter cap between acc and gnd, but it didn't help and acs712 and osd have different power supply than the load.

Any help is welcome.

This is not a simple chip to use.  These parts of the data sheet may help you understand what is happening.  It is internally an analog device and needs clean power.  I would highly recommend you download the Allegro data sheet, it has a lot of information that will help you.  Below is a short section of the data sheet, The first paragraph should give you a hint that the output voltage will be about 2.5V with a 5V unipolar power supply.

"Quiescent output voltage (VIOUT(Q)). The output of the device
when the primary current is zero. For a unipolar supply voltage,
it nominally remains at VCC⁄ 2. Thus, VCC = 5 V translates into
VIOUT(Q) = 2.5 V. Variation in VIOUT(Q) can be attributed to the
resolution of the Allegro linear IC quiescent voltage trim and
thermal drift.

Electrical offset voltage (VOE). The deviation of the device output
from its ideal quiescent value of VCC / 2 due to nonmagnetic
causes. To convert this voltage to amperes, divide by the device
sensitivity, Sens.

Accuracy (ETOT). The accuracy represents the maximum deviation
of the actual output from its ideal value. This is also known
as the total output error. The accuracy is illustrated graphically in
the output voltage versus current chart at right."

I realize this does not answer your question but it does give you a good starting point to resolve your problem.  Hopefully you or a buddy has some analog experience, that will help a lot.  Oh Yes clean power supplies are imperative for this to work.


How do I change fuse bits - not communicating? Currently I'm working on a project using an ATmega 2560 microcontroller card with a 10 MHz crystal. My main goal is to use the Arduino IDE to upload sketches to this chip to run my bread board circuit. In the beginning I had planned to use Atmel Studio to upload Arduino Sketches, but I decided to go with the more direct route. I am using two programmers, the Atmel ICE, and the Atmel AVR ISP MKii.

Anyway, here is my issue. I tried to use the Arduino IDE and the MKii to burn the bootloader to the chip. However, it did not work. It uploaded, but I was at that point no longer able to communicate with the device. When I switched to Atmel Studio, and used the ICE programmer, my chip could not be read and recognized (whereas before it could). I can't even program it. (I had bought two.)

I then figured I would try and read the fuse bits on the other programmer and burn the bootloader using Atmel Studio (since the Arduino IDE has no information on this), and I looked up the proper bits to change and then burned the bootloader. It worked fine, and I then changed the fuse bits which resulted in an error and now I again could talk to the device.

I am guessing that something is going wrong with the suggested fuse bits, but I do not know how to change them or how to fix this. The original fuse bits that I read from the device are listed below (before I messed it up).

I checked my wiring a billion times and it is all perfect. I just need suggestions to fix this mess, thanks.

BODLEVEL = DISABLED
OCDEN = [ ]
JTAGEN = [X]
SPIEN = [X]
WDTON = [ ]
EESAVE = [ ]
BOOTSZ = 4096W_1F000
BOOTRST = [X]
CKDIV8 = [ ]
CKOUT = [ ]
SUT_CKSEL = INTRCOSC_6CK_0MS
EXTENDED = 0xFF (valid)
HIGH = 0x98 (valid)
LOW = 0xC2 (valid)
LB = NO_LOCK
BLB0 = NO_LOCK
BLB1 = NO_LOCK

LOCKBIT = 0xFF (valid)

Detected device
Device name       ATmega2560
Device signature  0x1E9801

If AVR is bricked because of wrong fuses I suppose it's typically non-working external oscillator you need provide signal to particular AVR pin to get programmer working again. Thread related to unbricking http://www.avrfreaks.net/forum/locked-out-atmega-328p-possible-clocklow-fuse-byte-issue.


Understanding USBHID_DESC report Recently Ran the USBHID_DESC program on my Arduino Uno with a USB hub attached to my joystick. I wanted to be able to program my joystick to integrate with my project. Circuits@Home developed the code and have 2 articles dealing with understanding the report. But they are very sparse with details and only have a single example to go off of. Many of the fields that I got returned are not described at all in the tutorial. Further more, attempting to dig through the official documentation from USB.org itself has been extremely overwhelming. I don't really know how to start. Can anyone help me interpret the data fields for this controller?

This is the data that I recieved from the serial monitor:

  Start
  0000: 05 01 09 04 A1 01 09 01 A1 00 09 30 09 31 09 32
  0010: 09 BB 15 80 25 7F 46 FF 00 66 00 00 66 00 00 75
  0020: 08 95 04 81 02 C0 09 39 15 01 25 08 35 00 46 3B
  0030: 01 65 14 75 04 95 01 81 02 05 09 19 01 29 04 15
  0040: 00 25 01 75 01 95 04 81 02 95 08 81 01 05 08 09
  0050: 43 15 00 26 FF 00 35 00 46 FF 00 75 08 95 04 91
  0060: 82 55 00 65 00 55 00 65 00 55 00 C0
  Usage Page Gen Desktop Ctrls(01)
  Usage Game Pad
  Collection Application
  Usage Pointer
  Collection Physical
  Usage X
  Usage Y
  Usage Z
  Usage Undef
  Logical Min(80)
  Logical Max(7F)
  Physical Max(FF00)
  Unit(0000)
  Unit(0000)
  Report Size(08)
  Report Count(04)
  Input(00000010)
  End Collection
  Usage Hat Switch
  Logical Min(01)
  Logical Max(08)
  Physical Min(00)
  Physical Max(3B01)
  Unit(14)
  Report Size(04)
  Report Count(01)
  Input(00000010)
  Usage Page Button(09)
  Usage Min(01)
  Usage Max(04)
  Logical Min(00)
  Logical Max(01)
  Report Size(01)
  Report Count(04)
  Input(00000010)
  Report Count(08)
  Input(00000001)
  Usage Page LEDs(08)
  Usage Slow Blk On Time
  Logical Min(00)
  Logical Max(FF00)
  Physical Min(00)
  Physical Max(FF00)
  Report Size(08)
  Report Count(04)
  Output(10000010)
  Unit Exp(00)
  Unit(00)
  Unit Exp(00)
  Unit(00)
  Unit Exp(00)
  End Collection Game Pad Pointer X Y Z Undef(00)(00)(7F)(00)
  Hat Switch(00)
  Btn0001
  (00) Btn0002
  (00) Btn0003
  (00) Btn0004
  (00)
  (00)(00)(00)(00)(00)(00)(00)(00)
  Slow Blk On Time

It's pretty easy to follow if you indent and break it up right.  Let me add some annotation too:

Usage Page Gen Desktop Ctrls(01)  // Usages describe what the
Usage Game Pad                    // following data is used for.
Collection Application
    Usage Pointer        // Use the settings for a physical
    Collection Physical  // pointing device
        Usage X       // It has four axes -
        Usage Y       // X, Y, Z and some other undefined axis.
        Usage Z
        Usage Undef
        Logical Min(80) // Output the values 0x80 to 0x7F, which when
        Logical Max(7F) // interpeted as signed bytes is -128 to 127.
        Physical Max(FF00) // The input has a range 0 to 255
        Unit(0000)
        Unit(0000)
        Report Size(08)  // The report value is 8 bits long,
        Report Count(04) // and there are 4 of them (one per axis)
        Input(00000010)  // This ends this "input" section.
    End Collection

    Usage Hat Switch // Describing a HAT Switch now.
    Logical Min(01)  // Interpret it as a value between 1 and 8
    Logical Max(08)
    Physical Min(00) // The input to it is between 0 and 0x3B01.
    Physical Max(3B01) // Not sure that value is interpreted properly.
    Unit(14)
    Report Size(04)  // The report has 4 bits in it,
    Report Count(01) // and there is just one of them.
    Input(00000010)  // And end the input section.

    Usage Page Button(09)  // Next come the buttons.
    Usage Min(01)      // These are basically button numbers
    Usage Max(04)      // - there's 4 buttons, 1 through 4.
    Logical Min(00)    // A button is either off (0)
    Logical Max(01)    // or on (1).
    Report Size(01)    // And can only have one state, so size 1.
    Report Count(04)   // There's 4 buttons, so 4 reports.
    Input(00000010)    // And end the input.

    Report Count(08)   // This is a special one. It keeps the settings
    Input(00000001)    // from before (the haven't been changed), but
                       // is just a dummy one to pad out the data to
                       // the right size. Alignment is key.

    Usage Page LEDs(08)    // Now we have 4 LEDs with an
    Usage Slow Blk On Time // 8-bit PWM value. 0-FF which doesn't
    Logical Min(00)        // need interpreting, so 0=0 and FF=FF.
    Logical Max(FF00)
    Physical Min(00)
    Physical Max(FF00)
    Report Size(08)    // As I said, 8 bit,
    Report Count(04)   // and there's 4 of them.
    Output(10000010)   // And it's output.

    Unit Exp(00)   // Now there seems to be a bit of junk.
    Unit(00)
    Unit Exp(00)
    Unit(00)
    Unit Exp(00)
End Collection Game Pad // And the end.

So interpreting that, you get a report sent to you that has:

Byte     Function
0        X Axis 0-255 which you map to -128 to 127
1        Y Axis 0-255 which you map to -128 to 127
2        Z Axis 0-255 which you map to -128 to 127
3        Another Axis 0-255 which you map to -128 to 127
4        Upper 4 bits buttons, lower 4 bits HAT direction
5        Padding byte to make ita multiple of 16 bits long

And you can send a 4 byte report where:

Byte     Function
0        LED 1 PWM
1        LED 2 PWM
2        LED 3 PWM
4        LED 4 PWM

Those "LEDs" could be force feedback motors or vibrators.

Also I suspect there is maybe a small amount of corruption or mis-interpretation of multi-byte values in the output.


Pilot the the reset line by two input I have two input signal that when activated have to restart the ardiuno board so I have to connect them to the RESET pin. As you know the arduino board have only one RESET pin so I can't connect both to the same pin.
I think that a good idea is a circuit that takes the two inputs and activate the RESTART pin when one of the two is active.
Have you any idea to solve that problem?

Thank you.

Just use diode logic.

The resistor is probably not needed because the Arduino has an internal pullup resistor.

This assumes that the two reset inputs are active low

simulate this circuit – Schematic created using CircuitLab


How can I reduce current drawn by micro SD card module? I am using a servo along with a sensor and micro SD card module and speaker in arduino uno in order to play a wav file at certain conditions . But when i run the whole system the sd card module is consuming high current and the servo stops working as the current in that is in order of some micro amps. So please help me to solve the problem.

another good practice might be to add a Transistor to your Systems so that you can physically disconnect parts of your System from the power rail while not in use. this will obviously decrease power consumption...


Error Compiling on raspberry Pi - no error details provided in IDE I've just cracked out my Franzis Arduino Tutorial Kit (Best Xmas Present EVER!) and I'm already stuck on my second program.

I successfully wrote and executed a basic 'blink' program, however when I wrote out the second program provided in the manual I get an 'Error Compiling' when trying to check the syntax or run the program.

I tried the obvious of unplugging the board and plugging it back in but this didn't work. When I search for help most forum posts refer to the error message, however I have no message, just the orange warning bar stating 'Error Compiling'

This is the code;

// Franzis Arduino
// My second Arduino program

int ledPin = 13; //LED is connected with digital pin 13

// The setup routine configures the digital port
// This routine is executed only once at program start!

void setup()
{
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
  Serial.printIn("Our second Arduino program");
  Serial.printIn();
}

// The main program is an infinate loop
void loop()
{
  Serial.print("5 + 188 yields");
  Serial.print(5+188);
  while(true)
  {
    digitalWrite(ledPin, HIGH); // Turn on LED
    delay(2000);                 // Wait for a second
    digitalWrite(ledPin, LOW);   // Turn off LED
    delay(2000);                 // Wait for a second
    continue;
  }
}

And here's a screenshot of the error message (or lack of);

It's not printIn, but println (as in "print line").


SD card initialization failed i use the example sketch of SD card presented in Arduino IDE.
It runs well, but when i reboot my Adruino Mega by the reset button, the SD card initialization fails.
To fix it, i need to remove the SD card, insert it in his socket and reboot the board again. Then, SD card initialization is OK.
How can i update my code to try initialize the SD card until initialization is OK?
Also, can you explain me where come this bug ?

See the example SD card setup on the Arduino Mega:

Serial.print("Initializing SD card...");

  if (!SD.begin(53)) {
    Serial.println("initialization failed!");
    while (1);
  }
  Serial.println("initialization done.");

I just add an external 9V power supply to my Arduino Mega. The SD device is power by arduino 5V pinout.


Need help converting a processing sketch for a robot arm with servo shield I'm currently building a robotic arm. I'm using an Adafruit servo shield, 7 servos, Arduino uno, and a 5V 10A power supply.

I found a program that controls the arm with mouse movement using a processing sketch, Fixbot.

However I'm using the Adafruit servo shield, and I've got no clue how to convert the program. I've found the center points for the servos, so I've managed to make the robot stand upright using my own code.

If someone could give me some pointers as to how to convert from the on-board PWM outputs to the servo shield outputs for the linked program, and how to set servo max/min, I would highly appreciate it.

I use a generic servo shield, and the servo PWM outputs (3 pin inline connector) on the shield are labeled accordingly (0 - 15). Your Adafruit servo shield should be the same, see below.

The link that you provide also has the Arduino version, see below. You should use that, instead of the Processing version.
The Arduino library Servo.h, handles all of the "Servo PWM to Arduino pin conversions" that you ask for. So, looking at the Fixbot code, it would seem that all you would need to do is change the five pins (servo PWM outputs) to which the servos are attached in setup(), according to which servo PWM outputs you attach each servo to.
#include <Servo.h>

String command;

Servo seg0;
Servo seg1;
Servo seg2;
Servo seg3;
Servo seg4;

void setup() {
  Serial.begin(115200);
  seg0.attach(8);            /* <--- Change Me !!! */
  seg1.attach(9);            /* <--- Change Me !!! */
  seg2.attach(10);           /* <--- Change Me !!! */
  seg3.attach(11);           /* <--- Change Me !!! */
  seg4.attach(12);           /* <--- Change Me !!! */
}

void loop() {
  if(Serial.available() > 0) {
    char inChar = Serial.read();
    command += inChar;
    if(inChar == '\n') {
      // clear command
      performCmd(command);
      command = "";
    }
    Serial.flush();
  }
}

void performCmd(String cmd) {
  int comma1 = cmd.indexOf(',');
  int comma2 = cmd.indexOf(',', comma1+1);
  int comma3 = cmd.indexOf(',', comma2+1);
  int comma4 = cmd.indexOf(',', comma3+1);

  int cmd0 = stringToInt(cmd.substring(0, comma1));
  int cmd1 = stringToInt(cmd.substring(comma1+1, comma2));
  int cmd2 = stringToInt(cmd.substring(comma2+1, comma3));
  int cmd3 = stringToInt(cmd.substring(comma3+1, comma4));
  int cmd4 = stringToInt(cmd.substring(comma4+1, cmd.length()));

  seg0.write(cmd0);
  seg1.write(cmd1);
  seg2.write(cmd2);
  seg3.write(cmd3);
  seg4.write(cmd4);

}

int stringToInt(String str) {
  String tmp = String(str);
  return str.toInt();
}

Regarding your question about the maximum and minimums, again, these will be handled by the Servo.h library.

TL;DR
Change the five servo attach lines in the setup() routine, to reflect which servo ports your servos are connected to.

Power Requirements
As an aside, remember that you will need to supply external power (+5V) to the Adafruit Servo board, via the blue screw terminal block, in order to have sufficient power (current) to actuate the servos. In the photo above the screw terminal block is not shown, but would be mounted half way up on the left hand side of the PCB (where it says 5-6V Servo). It can be seen in this photo, at the top:

If you do not supply external power, then the Arduino board, by itself will not be able to supply enough power. Even though the code may be running, the lack of power may make it appear that there is no output, as the servos remain immobile, due to the lack of current.


Voice recognition without module, is it possible? I'm trying to figure out how to process a voice signal for simple purposes. Wherever I look people using or suggesting recognition modules for Arduino.

What I'm wondering: is this possible to make a simple command recognition with Arduino, without modules?

I just simply want to attach a microphone to my Arduino and after I convert it I want to handle signal and program it in MATLAB or in an Arduino itself. How can I achieve that?

As you can see I'm newbie in this. Any help is appreciated. Thanks!

No, it's not possible. The Arduino is not powerful enough to run the algorithms needed.

You need something with far more processing power, memory and storage. Something like a Raspberry Pi, maybe, or a desktop PC.

Or just use one of the many commonly available VR modules you can buy on the internet for next to nothing.


Continous running light with fading trail In examples of FastLED library, there's the animation of a dot sweeping back and forth, with fading trails (file "DemoReel100", animation "sinelon"). How can I alter the code so instead of moving back, the dot begins at LED #1 again; so when using a LED ring, then the movement is continuous and circular.
Since the code will be part of a more complex project with reading of button states etc, the animation code has to be non-blocking, i.e. delay() is not an option.

void sinelon()
{
fadeToBlackBy( leds, NUM_LEDS, 20);
int pos = beatsin16( 13, 0, NUM_LEDS-1 );
leds[pos] += CHSV( gHue, 255, 192);
}

If you look at the surrounding methods, you'll see that 'fadeToBlackBy' will give a fading effect on anything you feed in. You'll want to locate method 'beatsin16' and then edit it yourself so that it doesn't bounce back but restarts the counter at the first LED. (hint: phase_offset)

You'll find the code snippet you want to copy in lib8tion.h

/// beatsin16 generates a 16-bit sine wave at a given BPM,
///           that oscillates within a given range.
LIB8STATIC uint16_t beatsin16( accum88 beats_per_minute, uint16_t lowest = 0, uint16_t highest = 65535,
                               uint32_t timebase = 0, uint16_t phase_offset = 0)
{
    uint16_t beat = beat16( beats_per_minute, timebase);
    uint16_t beatsin = (sin16( beat + phase_offset) + 32768);
    uint16_t rangewidth = highest - lowest;
    uint16_t scaledbeat = scale16( beatsin, rangewidth);
    uint16_t result = lowest + scaledbeat;
    return result;
}


Why is 'n' parameter of snprintf ignored? I have found that the n parameter of snprintf() seems to be ignored in my code.

char asdf[10];
Serial1.println(snprintf(asdf, 2, "hello"));

This prints 5 when I would expect it to print 2. What is happening?

snprintf() will not write more than <size> (snprintf's 2d argument) characters to your buffer, but it does count (and discard the extra) characters it would have written, had there been space enough, and that is the number it returns. Yeah, it can be confusing!

See this snprintf() reference.


How do i make my DC motors run simultaneously? Im coding an adafruit motor shield for  3 DC motors to go forward & backwards, and so my concern is why only my motor3 is running the whole time and motors 1 & 2 are switching off meaning 1 goes than 2 goes and on and on? My code is below if you see where my mistake is in the code can you just tell me what it is and what to do to make them run simultaneously?
#include <AFMotor.h>
AF_DCMotor motor1(1);
AF_DCMotor motor2(2);
AF_DCMotor motor(3);

void setup() {
  Serial.begin(9600);           // set up Serial library at 9600 bps
  Serial.println("Motor test!");
  // turn on motor
  motor1.setSpeed(300);
  motor2.setSpeed(200);
  motor.setSpeed(500);
  motor.run(RELEASE);
}

void loop() {
  uint8_t i;

  //third motor
  Serial.print("tick");
  motor.run(FORWARD);
  for (i=0; i<255; i++) {
    motor2.setSpeed(i);
    delay(10);
  }
  for (i=255; i!=0; i--) {
    motor2.setSpeed(i);
    delay(10);
  }

  //second motor
  Serial.print("tick");
  motor2.run(FORWARD);
  for (i=0; i<255; i++) {
    motor2.setSpeed(i);
    delay(10);
  }
  for (i=255; i!=0; i--) {
    motor2.setSpeed(i);
    delay(10);
  }
  Serial.print("tack");
  motor2.run(BACKWARD);
  for (i=0; i<255; i++) {
    motor2.setSpeed(i);
    delay(10);
  }
  for (i=255; i!=0; i--) {
    motor2.setSpeed(i);
    delay(10);
  }

  Serial.print("tick");
  motor1.run(FORWARD);
  for (i=0; i<255; i++) {
    motor1.setSpeed(i);
    delay(10);
  }
  for (i=255; i!=0; i--) {
    motor1.setSpeed(i);
    delay(10);
  }
  Serial.print("tack");
  motor1.run(BACKWARD);
  for (i=0; i<255; i++) {
    motor1.setSpeed(i);
    delay(10);
  }
  for (i=255; i!=0; i--) {
    motor1.setSpeed(i);
    delay(10);
  }
}

Start with the BlinkWithoutDelay example code and make modifications to suit your needs.
This is the original code.
    /*
  Blink without Delay

  Turns on and off a light emitting diode (LED) connected to a digital pin,
  without using the delay() function. This means that other code can run at the
  same time without being interrupted by the LED code.

  The circuit:
  - Use the onboard LED.
  - Note: Most Arduinos have an on-board LED you can control. On the UNO, MEGA
    and ZERO it is attached to digital pin 13, on MKR1000 on pin 6. LED_BUILTIN
    is set to the correct LED pin independent of which board is used.
    If you want to know what pin the on-board LED is connected to on your
    Arduino model, check the Technical Specs of your board at:
    https://www.arduino.cc/en/Main/Products

  created 2005
  by David A. Mellis
  modified 8 Feb 2010
  by Paul Stoffregen
  modified 11 Nov 2013
  by Scott Fitzgerald
  modified 9 Jan 2017
  by Arturo Guadalupi

  This example code is in the public domain.

  http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
*/

// constants won't change. Used here to set a pin number:
const int ledPin =  LED_BUILTIN;// the number of the LED pin

// Variables will change:
int ledState = LOW;             // ledState used to set the LED

// Generally, you should use "unsigned long" for variables that hold time
// The value will quickly become too large for an int to store
unsigned long previousMillis = 0;        // will store last time LED was updated

// constants won't change:
const long interval = 1000;           // interval at which to blink (milliseconds)

void setup() {
  // set the digital pin as output:
  pinMode(ledPin, OUTPUT);
}

void loop() {
  // here is where you'd put code that needs to be running all the time.

  // check to see if it's time to blink the LED; that is, if the difference
  // between the current time and last time you blinked the LED is bigger than
  // the interval at which you want to blink the LED.
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }

    // set the LED with the ledState of the variable:
    digitalWrite(ledPin, ledState);
  }
}

Here are the changes that cause the LED to light up for 500 ms, then go dark for 5000 ms.
The changes are marked by // *************.
Hopefully, this will get you the idea about how to use millis() to control a device at desired intervals.
        /*
          Blink without Delay
          http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
        */

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

    //  int ledState = LOW;                    // ************* // change this assignment as follows

        int ledState = 0;                      // ************* // ledState used as a state counter

        unsigned long previousMillis = 0;

    //  const long interval = 1000;            // ************* // change the interval as follows

        const long interval =  500;            // ************* // use a 500 ms interval

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

        void loop() {
          unsigned long currentMillis = millis();

          if (currentMillis - previousMillis >= interval) {

            previousMillis = currentMillis;    // ************* // program arrives here every 500 ms

    //      if (ledState == LOW) {             // ************* // this code is not needed
    //        ledState = HIGH;                 // *************
    //      } else {                           // *************
    //        ledState = LOW;                  // *************
    //      }                                  // *************

    //      digitalWrite(ledPin, ledState);    // *************

            if (ledState == 0 ) {              // *************
                digitalWrite(ledPin, HIGH);    // ************* // turn on LED at start of cycle
            }                                  // *************
            else if (ledState == 1 ) {         // *************
                digitalWrite(ledPin, LOW);     // ************* // turn off LED at end of 500 ms
            }                                  // *************

            ledState++;                        // ************* // increment state counter
            if (ledState > 10 )  ledState = 0; // ************* // reset ledState when it has reached end of cycle

          }                                                     // end of if
        }                                                       // end of loop


How do I debug on-chip with Arduino? Though an emulator is quite useful for debugging code that has no side effects, most real-world applications include some circuitry besides the Arduino. If a microcontroller on an Arduino had a JTAG interface, it would be pretty straight-forward, but what if it's e.g. an Arduino Uno?

The Arduino Uno uses the Atmel Atmega328p microcontroller, which only has one debug option, DebugWire.  There are a few tools that can work with it, but the least expensive and most commonly available is the AVR Dragon.

You can use AVR Studio 6 for this.  You can use the .elf file file produced during the Arduino build process directly, but setting up the debugger is a little easier if you port the Arduino program to the AVR Studio.  It's not difficult, but there are a lot of little pieces to deal with.  There are guides online to help you through this.


74HC595 to 4 Digit 7 Segment using SevSegShift Library I have a question regarding the use of SevSegShift library. I followed the example properly and tested it to see if it works. It was able to power up the seven segments and light up the whole LEDs (even the decimal) but it's not showing the output I want to show.
Based on the code below, I want to show the number 500 but it does not. Even tried sevsegshift.setChars("abcd"), no change.
This is my code:
#include <SevSegShift.h>

#define SHIFT_PIN_SHCP 6
#define SHIFT_PIN_STCP 5
#define SHIFT_PIN_DS   4

SevSegShift sevseg(SHIFT_PIN_DS, SHIFT_PIN_SHCP, SHIFT_PIN_STCP, 1, true);

void setup() {
  byte numDigits = 4;
  byte digitPins[] = {9, 10, 11, 12}; // These are the PINS of the ** Arduino **
  byte segmentPins[] = {0, 1, 2, 3, 4, 5, 6, 7}; // these are the PINs of the ** Shift register **
  bool resistorsOnSegments = false; // 'false' means resistors are on digit pins
  byte hardwareConfig = COMMON_CATHODE; // See README.md for options
  bool updateWithDelays = false; // Default 'false' is Recommended
  bool leadingZeros = false; // Use 'true' if you'd like to keep the leading zeros
  bool disableDecPoint = true; // Use 'true' if your decimal point doesn't exist or isn't connected

  sevseg.begin(hardwareConfig, numDigits, digitPins, segmentPins, resistorsOnSegments, updateWithDelays, leadingZeros, disableDecPoint);
  sevseg.setBrightness(10);
}

void loop() {
  sevseg.setNumber(500);
  //delay(1000);
  sevseg.refreshDisplay(); // Must run repeatedly; don't use blocking code (ex: delay()) in the loop() function or this won't work right
}

This is my breadboard schematic down below.

(220 ohm resistors on the digit pins and the segment pins are connected to the shift register)

Finally able to fix it with the help of @PeterPaulKiefer, I was able to find the problem. The problem is in the code itself (schematic is alright. No changes there) and this is the updated code.
#include <SevSegShift.h>

#define SHIFT_PIN_SHCP 6
#define SHIFT_PIN_STCP 5
#define SHIFT_PIN_DS   4

SevSegShift sevseg(SHIFT_PIN_DS, SHIFT_PIN_SHCP, SHIFT_PIN_STCP, 1, true);

void setup() {
  byte numDigits = 4;
  byte digitPins[] = {12, 11, 10, 9}; // These are the PINS of the ** Arduino **
  byte segmentPins[] = {0, 1, 2, 3, 4, 5, 6, 7}; // these are the PINs of the ** Shift register **
  bool resistorsOnSegments = false; // 'false' means resistors are on digit pins
  byte hardwareConfig = COMMON_ANODE; // See README.md for options
  bool updateWithDelays = false; // Default 'false' is Recommended
  bool leadingZeros = false; // Use 'true' if you'd like to keep the leading zeros
  bool disableDecPoint = false; // Use 'true' if your decimal point doesn't exist or isn't connected

  sevseg.begin(hardwareConfig, numDigits, digitPins, segmentPins, resistorsOnSegments, updateWithDelays, leadingZeros, disableDecPoint);
  sevseg.setBrightness(100);
}

void loop() {
  sevseg.setNumber(500);
  sevseg.refreshDisplay(); // Must run repeatedly; don't use blocking code (ex: delay()) in the loop() function or this won't work right
}

What changed:

Turns out my 7-segment is COMMON_ANODE so I changed my hardwareConfig
Set brightness to 100
(At this point, it shows the number in reverse but with a decimal point in each digit)
Set disableDecPoint to false
(At this point, the display is showing but in reverse but no more decimal point)

To fix this, I set the digitPins[] in reverse and it now shows the proper format

Thank you so much Peter for helping me figure out what's wrong!
Also the LED Bar I use is 4-Digit 0.36" LED, 7-segments display, common-anode. (The link is to the shop I got it from)


Mixed structure with int and string I want to create a structure like this:

 struct commands
{
  int   cmd;
  char  descr[25];
};

commands cmds[] =
{
  {16, "Hammond Organ"},
  {17, "Percussive Organ"},
  {18, "Rock Organ"},
  { 0, "" }                   // end of list marker
};

The compiler doesn't protest, but in a simulator the values of cmds[i].descr are all zeros.

And the line

Serial.write(cmds[1].descr);

prints nothing.

Please recommend how to rewrite the code.

Thanks.

EDIT

Thanks for your answer. It helped me a lot.

There is something wrong with the simulator (Simulator for Arduino - version 1.11E Designed by Virtronics). In the meantime I received the Mega 2560 board and the code works well with the board.

There must be something wrong with the simulator you're using, because your code works for me (Arduino IDE 1.8.9, OSX, Arduino Uno).

struct commands
{
  int   cmd;
  char  descr[25];
};

commands cmds[] =
{
  {16, "Hammond Organ"},
  {17, "Percussive Organ"},
  {18, "Rock Organ"},
  { 0, "" }                   // end of list marker
};

void setup(){
  Serial.begin(9600);
  Serial.write(cmds[1].descr);
}

void loop(){}


connect arduino to battery with 12V motor I am looking  at this(instructable with circuit picture) tutorial for making a self-balancing robot. However, I am confused about how the battery connects to the arduino. I know the 12 V must go to the motors to power them yet the diagram shows wires connecting to the Arduino through some kind of green device. I assume this connects to the power supply . However I do not have this green device and I don't know how to connect to the power supply. How should I get a charger cable and solder on the battery wires to the charger? If so are there any tutorials? Is the connection to the Arduino necessary?

(please look at the Firizing diagram in the instructable)
Thanks

I am looking at this(instructable with circuit picture) tutorial for making a self-balancing robot.
  However, I am confused about how the battery connects to the arduino.

Well, it seems he has attached a 9V battery through a voltage regulator, to the Arduino.
Which is bullshit.

You can put the 9V directly into the barrel-jack of the Arduino. You actually should. Putting 5V on the barrel jack is not within the specs. (https://www.arduino.cc/en/main/arduinoBoardUno)

  I know the 12 V must go to the motors to power them yet the diagram shows wires connecting to the Arduino through some kind of green device. I assume this connects to the power supply . However I do not have this green device and I don't know how to connect to the power supply.

Well, the motors only get 9V in this diagram (which might work neverthless). But bear in mind that 9V batteries won't last long.

I'm not sure what you mean by "Green device", the HC-05 or the L293D?
Anyway, the L293D are quadruple high-current half-H drivers, which basically is a way to switch 12V on/off/invert based on the 5V inputs (from Arduino).
You could do this with some circuitry, but I suggest picking up a "motor driver (arduino)"

  How should I get a charger cable and solder on the battery wires to
  the charger?

You can't charge regular 9V batteries.

  Is the connection to the Aruino necessary?

The specific connection he shows? No.
Power to the Arduino board? Yes.


Adding a common activation pin to a group of buttons I'm working on an Uno, which has only two interrupt capable pins, but i need at least three buttons to wake it up from its power saving mode.
Is there a way to wire buttons such that, in addition to their individual pin, they will also activate a common pin (in this case, the interrupt one)?

You can connect all the buttons to a single interrupt pin by ORing them via diodes (like Gerben wrote in the comments). That would look like this:

simulate this circuit – Schematic created using CircuitLab
The diodes isolate each input pin from the other, but allow the buttons to pull down the interrupt pin.
Though that is not the way, that I would suggest. Instead you could simply use the PinChange interrupt. That is a different type of interrupt, which can react to all pins of a port in a single ISR for the whole port. You can mask unused pins of the port away, so that the interrupt doesn't trigger for them. Nearly every pin is usable that way.
If you want to use the Arduino framework for this, you can just use the attachInterrupt() function, which can use the PinChange interrupt in the background.
If you want to go more down into the hardware side and configure the interrupt yourself, you should look into the corresponding sections of the datasheet. The Uno uses the Atmega328p. From 12.2.4 on you see the registers used for the PinChange interrupt (aka PCINT).

With the bits in PCICR you can enable the PinChange interrupt for the ports (3 distinct interrupts for the Uno).
The PCMSKn (n meaning number between 0 and 2) is used to mask unused pins of the port away. You should set the bits for the used pins to 1, the others to zero.

Then you need to define the actual Interrupt Service Routine (ISR) in your code:
ISR (PCINTn_vect) // handle pin change interrupt for D8 to D13 here
{
    ...
}

Here again substitute the n for the number of the PinChange interrupt, that you are using. Inside the ISR you need to read all the input pins of the buttons, that are connected to this PinChange interrupt, and execute your code accordingly. Note: As the name states, the interrupt is triggered on every change of the pin. Inside the ISR you need to sort out, what change that was. It comes down to just reading the pin, but you should keep that fact in mind.
Also make sure to never do long things inside an ISR; it has to be as short as possible; Do long things inside the main code, which can get triggered via a flag variable from the ISR)
If you google for something like "Arduino pin change interrupt" you can find detailed tutorials for this, which can go way deeper, than I can on this Q&A site.

Will this also work while in CPU sleep mode from the avr/sleep.h
library?

According to Table 9-1 in Chapter "9.1 Sleep Modes" in the datasheet, the PinChange interrupts are on the same level as the External Interrupts INTn in regard of sleep modes. So this should work just like with the INTn interrupts.


Can I use 1-byte datatypes to store digital input? I am reading the docs on DigitalRead() and wondering why it stores seemingly boolean HIGH and LOW inputs in int data type variable.

I have two issues with that:

int is 2-byte, while bool and uint8_t are 1-byte so it seems like a waste of memory for no benefit whatsoever.
It gets me confused when reading the code about whether the input came from digital or analog since int can have a wide range.

Is there any particular reason for storing digital inputs as int?

EDIT: bool and uint8_t are out of the question as per the answer below. int8_t still looks suitable for the purpose though.

You receive the data as int, but you store it as byte.

For example, when you call the serial library function to receive a data byte, the library will return either the data or a -1 if a problem has occurred.

The binary value of -1 is a byte 11111111 or int 1111111111111111.

The binary value of 255 is a byte 11111111 or int 0000000011111111.

I think that you can see the problem if you use byte data and the data is 255.

So, if you receive an int -1, then you do not process the data.  Otherwise you cast the int to uint8_t.

You could receive byte data, but then the value of 255 would be undefined.


Deviation of power consumption between datasheet and real world? According to the Atmega328P-PU Datasheet (side: 589) the current consumption of the microcontroller should be around 9.5mA (at 16MHz and 5V).
But I measured 15mA. (Nick Gammon who did some pretty good power saving research(gammon.com.au/power) got the same)
There is nothing connected to the outputs. The code I ran was this:

  void setup () {}
   void loop () {}

Now I'm wondering if this is just a normal deviation (datasheet to real world) or if Atmel measured their current consumption in a state that is different from mine?

EDIT:

I forgot to mention.. I didn't use it with the Arduino Uno board but as standalone device. There was only a 16Mhz oscillator with two capacitors connected. Power came directly form Power supply.

Now that I think about it..  Datasheet says this regarding the current measurement: "A sine wave generator with rail-to-rail output is used as clock source."

Is it possible that the oscillator needs that extra 5mA?

EDIT2:

Here is a screenshot of my schematic:

And a screenshot of the ATmega328P-PU Datasheet:

According to the datasheet:

  All current consumption measurements are performed with all I/O pins configured as inputs and with internal pull-ups enabled.

That was the critical point. Trying this sketch:

int main ()
  {
  for (int i = 0; i < 20; i++)
    pinMode (i, INPUT_PULLUP);
  }  // end of setup

Note that timers are not running (your sketch would have timer 0 running):

With that sketch, even using the crystal and capacitors (I actually had a resonator) the consumption at 5 V at around 20 °C was 9.2 mA which is within spec.

Fuses:

Signature = 0x1E 0x95 0x0F
Processor = ATmega328P
Flash memory size = 32768 bytes.
LFuse = 0xFF
HFuse = 0xDF
EFuse = 0xFF
Lock byte = 0xFF
Clock calibration = 0x96

If we turn pull-ups off:

int main ()
  {
  }  // end of setup

Now it consumes 14.4 mA, closer to what you measured.

And with your actual test sketch:

void setup () {}
void loop () {}

It consumes 15.5 mA, which is more, because Timer 0 is running (started in the init function). It is also close to what I had on my page about power - 15.15 mA.

So, working as expected. Those pull-ups are important, to stop the input drivers consuming current.

I did mention further down in my page the importance of configuring the pins:

  Testing in SLEEP_MODE_PWR_DOWN:

  All pins as outputs, and LOW: 0.35 µA (same as before).
  All pins as outputs, and HIGH: 1.86 µA.
  All pins as inputs, and LOW (in other words, internal pull-ups disabled): 0.35 µA (same as before).
  All pins as inputs, and HIGH (in other words, internal pull-ups enabled): 1.25 µA.

Notice the difference there of 0.9 µA when asleep. It would appear that there is an ever greater difference if the processor is awake.


How to have compiler know whether Arduino or ESP8266? I am doing some work for both Arduino Mini Pro and for a NodeMCU style ESP8266 board. Within the Arduino IDE I tell it what board I am compiling for and downloading to.

How do I access which board in my scripts?

Some sections are for one or the other exclusively. Right now I'm using a #define at top of the script, but changing this to switch between boards not the best. For example, version control keeps on thinking I'm in a new branch when I'm not.

There are a number of macros defined to help you with this:

__AVR__ for any board with AVR architecture.
ARDUINO_AVR_PRO for the Arduino Pro or Pro Mini selection in the Tools > Board menu.
ESP8266 for any ESP8266 board.
ARDUINO_ESP8266_NODEMCU for the NodeMCU 0.9 (ESP-12 Module) or NodeMCU 1.0 (ESP-12E Module) selections in the Tools > Board menu.

This allows you to do things like this:

#if defined(__AVR__)
// AVR specific code here
#elif defined(ESP8266)
// ESP8266 specific code here
#endif


automated parking system (sir sensor+ stepper motor) my project about automated system I am using stepper motor to open and close the gate

I want my code be like when the gate opened it stays 5 seconds

then check the sensor, if there is a motion the gate should not close and stay open, when there is no motion the gate should close

if the gate is closing and there is a motion, motion should interrupt closing the gate and reopening the gate

I am using Arduino uno

the code is :

#include <RH_ASK.h>//include radioHead ASK library
#include <SPI.h> // include dependant SPI libray
#include <Stepper.h> // Include the Arduino Stepper.h library:
// Define number of steps per rotation:

RH_ASK rf_driver; // create ASK object
int ledon = 13;
int ledoff = 5;
int sensor = 3;

const int stepsPerRevolution = 2048;// Define number of steps per rotation:

// Wiring:
// Pin 8 to IN1 on the ULN2003 driver
// Pin 9 to IN2 on the ULN2003 driver
// Pin 10 to IN3 on the ULN2003 driver
// Pin 11 to IN4 on the ULN2003 driver
// Create stepper object called 'myStepper', note the pin order:
Stepper myStepper = Stepper(stepsPerRevolution, 8, 10, 9, 11);

void setup() {

  rf_driver.init(); //initialize ASK object

  // Begin Serial communication at a baud rate of 9600:
  Serial.begin(9600);

  // Set the speed to 5 rpm:
  myStepper.setSpeed(5);
  pinMode(ledon, OUTPUT);
  pinMode(ledoff, OUTPUT);

}

void loop() {

  //set buffer to size of expected message
  //uint8_t buf[8];
  // uint8_t buflen =sizeof(buf);

  //check if recevied packet is correct size
  //  if (rf_driver.recv(buf,&buflen))
  //{
  // int i;
  // message received with valid checksum
  // Serial.print("id: ");
  // Serial.println((char*)buf);
  // String userid =(char*)buf;
  // Serial.println(userid);

  // }

  //delay(5000);

  // uint8_t buf2[8];
  // uint8_t buflen2 = sizeof(buf2);

  // if (rf_driver.recv(buf,&buflen))

  // {

  //  int i;
  // message received with valid checksum
  // Serial.print("password: ");
  // Serial.println((char*)buf);
  // String password = (char*)buf;
  //  Serial.println(password);

  // }
  // delay(5000);

  String pass = "1234";
  String id = "A00036757";

  if (pass == "1234" ) {
    Serial.print("car exists");
    digitalWrite(ledon, HIGH);
    delay(300);
    myStepper.step(stepsPerRevolution / 3); //clockwise -OPEN GATE
    delay(10000);

    //if(digitalRead(sensor) == HIGH){
    delay(500);
  }

  if (digitalRead(sensor) == LOW) {

    digitalWrite(ledon, LOW);
    delay(300);

    digitalWrite(ledoff, HIGH);
    delay(300);
    myStepper.step(-stepsPerRevolution / 3); // CLOSE AFTER 5s COUNTERCLOCKWISE -  close gate
    digitalWrite(ledoff, LOW);
  }
  else {
    Serial.print("NO CAR");
  }

When you use delay(), your code stops and dont check anything at all until the delay is over, if you want to check for sensors during a timer, you have to use millis()

There is a lot of documentation and tutorials you can find to replace delay with millis when you know what you are searching for


Connect Antenna to GPS Module ET314AC How can I connect antenna to GPS Module ET314AC?(it is not on a breakout board). I have an antenna like this one GPS Active Antenna and Here is the datasheet of ET314ACET314AC Datasheet.I want to connect it manually without any connectors or other things in fact I want to cutoff the connector from antenna.

Read the datasheet!

  V_ANT_IN

  This pin is reserved an external DC power supply for active antenna.
  If using 2.85V active antenna, pin 19 has to be connected to pin 20.
  If the bias voltage of active isn’t 2.85V,you can input bias voltage of you need to this pin.

So just wire the antenna to the RF_IN pin and GND, and connect pin 19 to +3.3V (since your antenna is 3.3V not 2.85V).


ESP send string to Arduino I'm trying to send a string from an ESP32 to an Arduino. I'm using a level shifter, where the Uno is now the Mega (since I couldn't get the Uno to work).

RX0 is now RX1, connected to UART2 of ESP32.
// Master sender ESP32

#include <HardwareSerial.h>

void setup() {
  // Serial.begin(115200);
  Serial2.begin(9600, SERIAL_8N1, 16, 17);
  delay(100);
}

void loop() {
  String shape = "1,2,3";
  Serial2.println(shape);
  delay(500);
}

//Receiver Mega

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  Serial1.begin(9600);
  Serial.begin(19200);
  delay(100);
}

void loop() {
  if (Serial1.available()) {
    String received = "";
    received = Serial1.readString();
    Serial.println(received);
  }
}

Is there something in either sketch that should be changed?

readStringUntil('\n')
//Receiver Mega

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  Serial1.begin(9600);
  Serial.begin(19200);
  delay(100);
}

void loop() {
  if (Serial1.available()) {
    String received = "";
    received = Serial1.readStringUntil('\n');
    Serial.println(received);
  }
}

It's about how Serial.readString() works: it reads from the serial port forever in this case. It stops reading if the serial interface is given a time-out. There are two possibilities:

use readStringUntil() on the receiver
call mySerial.setTimeout(300); (from setup()) to set a 300ms (for instance, as long as it's significantly less than 1000) time out on the receiver — it defaults to one second!


Need to read/send both values of a button push I'm trying to use a float switch to receive alerts via Blynk when a water level drops, and when it rises again. The code I have been using has been working for when the float drops (button pressed) and I could get it to work when the water comes back up, but it gets stuck in a loop. I'm new to Arduino programming and I'm sure it's some simple error in the way I'm writing/modifying this code...

#define BLYNK_PRINT Serial
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
BlynkTimer timer;

char auth[] = "710a4af9b1d82412fa477705bf642c634";
char ssid[] = "SSID";
char pass[] = "PWD";
int flag=0;
void notifyOnButtonPress()
{
  int isButtonPressed = digitalRead(D1); //assignment here for pin
  if (isButtonPressed==1 && flag==0) {

    Blynk.notify("Alert : Water Level has dropped");
    flag=1;
  }
  else if (isButtonPressed==0 && flag==0)
      Blynk.notify("Alert : Water level has risen");
  {
    flag=0;
  }

}
void setup()
{
  // Debug console
  Serial.begin(9600);
Blynk.begin(auth, ssid, pass);
  // Setup notification button on pin D1
  pinMode(D1,INPUT_PULLUP);
 timer.setInterval(16000L,notifyOnButtonPress);

}
void loop()
{
  Blynk.run();
  timer.run(); // Initiates BlynkTimer
}

I believe the problem is in function notifyOnButtonPress.

Change

else if (isButtonPressed==0 && flag==0)
    Blynk.notify("Alert : Water level has risen");

to

else if ((isButtonPressed==0) && (flag==1))
{
    Blynk.notify("Alert : Water level has risen");
}

Otherwise, when flag == 1, it will never revert back to 0.
Also it's best to add brackets, and use parenthesis.

Also, change the variable name flag to something more meaningfull.


Multiple RGB led strips with Uno - options? I know there's quite a few threads with similar answers already, but I hope you won't mind me asking anyways. One thread has what looks like a good solution but it's old and thought it may be better to ask fresh.

I have ten 12v rgb strips with 4 wires each, a 12v power supply and 30 mosfets. I want to control them individually with an Uno.

I'd like to make a wave effect where the strips increase and decrease in brightness at separate times. It's fine if they are all the same color during a wave. Then a wave of a different color.

(1) I'm thinking of trying the approach in this thread where AMADANON suggests using 3 pins for the color and then each strip gets its own common pin, 13 pins in my case. If I go this route, will I be able to set a color for all strips and a brightness for individual strips? This would let me make the wave effect I'd like.

(2) Alternately I'm thinking of upgrading to a Mega with 54 pins. I assume I could then control each strip individually using 3x10 = 30 pins?

(3) I've read lots of advice on chips to control the strips, but I'm a newbie and would like to keep it as simple as possible (plus delivery to my country takes 3 weeks or more, and I'd like to get started now)

Thanks for any advice!

EDIT:
(I replied to answers in comments, and I now see I should just instead edit this question. Thanks for your patience with a newbie!)

The mosfets are N-Channel MOSFET 60V 30A.

The led strips are rgb non-addressable with 4 wires, wired on both ends so they can be easily daisy-chained. But in my project the strips are snaking around some tracks and connected them in serial poses a problem. I'd prefer to wire each from only one end.

I think I'll try Gerben's and Andrew's advice about a chip and check out PCA9685 chip module as per Andrew's suggestion. Sounds inexpensive!

chrisl's suggestion for using WS2811 chips sounds easy too and maybe less wiring. In the same vein was an idea from this thread from gre_gor:

Setting 10 RGB Strips Independently from Single Arduino

... which talks about chainable STM32 rgb chips, only about 2 bucks on ebay, no mosfets, and pretty efficient.

Thanks for all the advice guys! I'm finishing the box and strips placement now and waiting for my Arduino to arrive which should be any day. This is my first venture into this domain (though I've done plenty of coding and have some experience with electronics).

I know what you mean - LED strips with all the same colour at the same time. I've used these and I assume you can wire up the MOSFETs ok. If you don't need individually-addressable LEDs they can still produce some effects.

To control 30 PWM lines, at first I thought using the Mega would solve it, but as someone else reminded us, only 15 are full (hardware) PWM and some would have to be software PWM. This may be good enough, I don't know. More expensively, you could use two MEGAs with one acting as a slave to get 30 full PWM pins.

Another idea would be to use a PCA9685 chip module. I got a couple of these on ebay some while ago (dirt cheap, under £2/$2 ) and each board provides 16 PWM outputs, all controlled from I2C input. They aren't hard to use and have library code for Arduino. Two of these and an UNO would do it or one and a MEGA.


Why Arduino pins don't output 0 volt? void setup() {
  pinMode(5, OUTPUT);
}

void loop() {
  analogWrite(5, 0);
  // or
  //digitalWrite(5, LOW);
}

Output is 0.003V and the tiny voltage causes the circuit to draw 20uA.

Is there anyway to get absolute 0V from Arduino PWM pin?

It doesn't output 0v because it's near impossible. 0.003v is in fact very low. The LOW output, according to the datasheet, can be as high as 0.8v (when powered by 5v) and still be considered valid.

LOW does not mean 0v. It means "below the voltage threshold that is considered a LOW".


ATtiny85 SPI with Timer 0 Trying to shift out from ATtiny85 to a shift register using the USI in SPI mode. I have Timer 0 running as slowly as possible (checked it was running by temporarily changing it to toggle a pin with an LED attached.) I have LEDs hooked up to USCK and DO so by rights I should be able to see them blinking as it sends.

What else do I need to do in order to get it shifting out in sync with Timer 0? All the examples I've looked at so far strobe the USI clock manually.

#include <avr/io.h>

int main(void){
    DDRB = (1 << DDB2) | (1 << DDB1); // USCK & DO Output
    DDRB &= ~(1 << DDB0); // DI Input
    PORTB |= (1 << DDB0); // Pullup Resistor for DI

    TCCR0A = (1 << WGM01); // Timer 0 in CTC Mode
    OCR0A = 0xFF; // Timer 0 Compare A
    TCCR0B = (1 << CS02) | (1 << CS00); // Prescaler / 1024

    USICR = (1 << USIWM0); // USI 3 Wire Mode
    USICR |= (1 << USICS0); // Timer 0 for USI 4-bit Clock Source

    USIDR = 0x7F; // Why you no go? :c

    USISR |= 0x08; // Set Counter to 8
    USISR = (1 << USIOIF); // Clear Counter Overflow

    while(1);
    return 0;
}

Did you forget to load the counter and clear flags in USISR?


Serial.println for pointers to the byte datatype behaves unexpectedly byte subkeys[16][48/8];

for (size_t address = 0; address < 16*6; address++)
    Serial.println( (byte) *(subkeys + address) );

Why won't the compiler handle this? It tells me

  cast from 'byte* {aka unsigned char*}' to 'byte {aka unsigned char}' loses precision [-fpermissive]

If I omit the (byte) part, it tells me

  call of overloaded 'println(byte [6])' is ambiguous

I have no idea what's happening.

A byte is to small to store a pointer value. Instead to casting to
byte, you should cast to uintptr_t, which is guaranteed to be large
enough. On an AVR-based device like the Uno, this is the same as
uint16_t or unsigned int, but uintptr_t is more general.

Edit: From your comment it would seem you want to print the contents
of the array instead of the addresses of the rows. The obvious way is to
loop with two indices:

for (size_t i = 0; i < 16; i++) for (size_t j = 0; j < 6; j++)
    Serial.println(subkeys[i][j]);

If you really want to use subkeys as a 1D array, then cast it to a
byte *, which is the type a 1D array would naturally decay to:

for (size_t address = 0; address < 16*6; address++)
    Serial.println(((byte *) subkeys)[address]);


Measure low current with variable voltage I want to make a system that always have the same current (about 1ma) in a water with silver electrode. At start it will be purified water so conductivity will be really low.

But with time silver particle will be released in water, raising his conductivity so if I don't lower the voltage the current will raise too (meaning that bigger particle will be released which I don't want too).

So, is there any way I can measure low current and adapt voltage with the result (since deducting resistance wouldn't be hard).

I know about ASC712 but It seem that he can't be precise enough (steps of 13ma max) to my use.

I precise it's not that long I'm trying to get back in electronics with arduino so many school things have been forgotten.

What you want is called a constant current source. You can actually build a simple one using one transistor ; but a better one uses two transistors - as in the left example below - see this page for explanations.

Here the leds would be your load, R=680 Ohm would give you about 1mA - and you would need to increase the value of the 2k2 resistor to somewhere around 22k.

The problem is that, as John Williams noted, forcing 1mA through a high resistance requires high voltage : 1MOhm would need 1kV, 10MOhm needs 10kV etc. That's very dangerous voltages! and quite some power as well : 10kV at 1mA means 10W.

I think you need to define your needs first :

What is a tolerable error on the absolute value of current? (Would constant 1.1mA be OK?)
What is a tolerable error on the current variations? (Would current varying between 1.19mA and 1.21mA be OK?)
Do you absolutely need 1mA right from start? Or can you accept a lower current at start, growing with increased conductivity until 1mA is reached and then being held nicely constant?

If the above examples are fine, a current source as described above would do the job nicely for less than 1USD.

If you really need a constant current source right from the start, then be prepared to work with expensive and dangerous pieces of equipment.