text:
Good book/reference for AVR coding in pure C/C++?
Can someone recommend a good book/reference for going vanilla (i.e. not using arduino simplified language) on e.g. ATtiny85? I will need to use the equivalents of analogRead() and digitalRead() quite a bit. And is softwareserial the best method for debug output? I have less than 8KB of flash, so any advice on that (and reduction of binary for upload) would also be greatly appreciated.

Have you tried Atmel's datasheets and application notes?

Yes, I am looking for something to supplement those. A collection of commented programs for ATtiny85 would be good, or a beginner/medium book/reference. The avrfreaks forum is very good, but I need more.

First, let's make this clear: The Arduino environment does not provide a
“simplified language”: it provides a simple hardware abstraction layer
through its core library. The language is plain C++.
Like Talk2, I don't have good book recommendations. The basics of
low-level programming are covered in the Arduino tutorial on port
manipulation[]. Past this you will have to dig into the datasheet of
your MCU. Look also at the doc of the avr-libc and the tutorials in
Nick Gammon's microprocessors pages.
I would suggest you try to develop your program like this:

Do the initial prototype of your idea on an Arduino Uno (or similar)
using the Arduino libraries. It just makes things easier, and you are
more likely to get a working prototype pretty fast.
Once the initial idea works, optimize it for the limited resources of
the ATtiny85. This may involve replacing some call to the Arduino
libs with avr-libc and/or direct port access.
You may then want to remove all references to Arduino core, but you
don't have to: there are some ATtiny cores available that you can use
if you want.
If it now fits in less than 8 K, port to the ATtiny.

The thing I love about the Arduino environment is that you can very
easily mix and match abstraction levels: you can have, in the same
program, calls to Arduino core, to avr-libc, direct port access, and
even inline assembly if want to. You don't even need to stick to the
setup() and loop() method: you can write your own main() if you
prefer, just remember to call init() to initialize the Arduino core if
you are going to use it. Oh, and you don't have to use the Arduino IDE
either if you don't like it (I don't).
As for the optimization tips, I would recommend :

Use direct port access instead of digitalRead(), because that
function is pretty big and slow.
analogRead() may not be that bad, size wise, but it has a serious
shortcoming: it's a blocking function which spends 104 µs in a
spin loop, just waiting for the ADC result. If your CPU has better
things to do, you may want to implement a non-blocking read instead.
For debugging output, the most efficient option is likely to be the
USI port. You will have to search for a driver or implement your own
based on the Atmel application note AVR307: Half Duplex UART Using
the USI Module. Alternatively, you could use something like
AltSoftSerial. Do not use SoftwareSerial: it blocks interrupts for
insanely long amounts of time.
Use the command avr-nm --size-sort -Crtd my_program.elf to get a
listing of the functions of your program sorted by flash usage. This
will help you choose good targets for size optimization.

This is as near to perfect as reality permits. Thank you very much :)

I can recommend the book "Make: AVR Programming", which uses avr-gcc directly. The Arduino IDE is mentioned at one point, but just in order to "place" it, and to explain how to use its libraries in your own code. You can study all the code used in the book right here (github link).
(late answer, I know, I was searching for other books that don't use the Arduino IDE and stumbled upon this question)

If you abandon the Arduino paradigm you will be pushed into dealing with setting up all the hardware that makes today's embedded processor so flexible.  This usually takes an experienced embedded programmer days if not weeks to get through on a new processor.  You will also need a dedicated Atmel programmer as you will no longer be using the Arduino boot loader.
Once you get past these obstacles, you can start studying C and C++. The "grand dad" C reference book would be by the "first guys" that did C, Kernighan & Ritchie.  The equivalent C++ book (if you are up to it) would be by Bjarne Stroustrup.
However...
What have you gained by abandoning the Arduino paradigm?
Some would say, not much.
Most of why programming in the Arduino paradigm is easy has to do with Arduino libraries.  They "abstract" the hardware down to a couple simple function calls.  For example, with one function call you can set up the pulse train that can position a servo motor using a familiar term: degrees.
It should also be pointed out that the compiler Arduino uses is a C / C++ compiler.  And that most Arduino libraries are purposely written in C++.
Perhaps writing a C++ Arduino library is a good way to learn C++.  Start by finding the code to libraries that you already use.  Then reviewing how the C++ code is put together.  Finally write you own C++ Arduino library.

Sorry, I don't have any book recommendation apart from the AVR Datasheet.
You could try to use AVR-LIBC as a abstraction layer instead of playing directly with individual registers: http://www.nongnu.org/avr-libc/.
That might help you saving some Ks on your code which the Arduino layer might be adding. Just make sure you have a proper IDE to assist you with code-completion and navigation.
Also Atmel has a good link how to optimize your C code: http://www.atmel.com/images/doc8453.pdf, which I had a look when doing some bootloader coding.
Finally, you could explore the Arduino libraries, and see the overhead added to each function, like "analogRead()" from your example. Most of the Arduino funcions will be a layer on top of the AVR-GCC, so it'll be a good learning exercise - again, get a proper IDE that helps with auto-completion and navigation.
Cheers

avr-libc does very little to abstract the hardware: you are still going to access the hardware registers “manually”. Only it is easier with avr-libc, as it lets you write things like PORTB |= _BV(2); instead of * (volatile uint8_t *) 0x25 = 1 << 2;. The generated code is the same (namely sbi 0x5, 2).

The Arduino implements a subset of c++. I am not sure what you expect to achieve by not using it.
If you are really after optimum code, there is no obligation to use any inbuilt function and you can code your own.
Most conventional compilers use a standard runtime library. The reason Arduino does not is because of the limited memory. It is necessary to omit many standard functions to save space.
By not using a library only functionality you need is actually linked in.

The Arduino core is a runtime library, built on top of avr-libc, which is itself another runtime library. But the linker is smart enough to only link into your program the functions you do use.

@EdgarBonet if it only links used functions it is a library which produces a staticly-linked executable, but not a "runtime library" which is loaded in its entirety by the OS - non-existent on the Arduino.

Yes, these are statically linked libraries. If by “runtime library” you mean a library loaded in its entirety by the OS (I would call that a “dynamic library”), then no, there is not, simply because there is no OS. There is a “C runtime” though, courtesy of avr-libc (the files crt*.o): it contains the interrupt vector table, the catchall interrupt, the initializations of r1, SREG and the stack, and the calls to main() and exit().


text:
How to control a DC Motor with Hall Encoder using Arduino and Motor Driver?
I'm using a DC motor with Hall Encoder. I bought it from DX.
I have made all the connections to motor driver and arduino and I suppose all are correct. I've connected m1 and m2 pins of motor to that of motor driver, encoder A phase and B phase to arduino pins 3 and 11, and GND of motor to GND of Arduino and 3.3V pin of motor to 3.3V pin of Arduino. Also motor driver is also connected to arduino.
The problem is that I'm unable to run the motor but I can count the rotations made by the motor. Please help me with the working code. Thanks.

What are the "m1" and "m2" pins you mention?
On the diagram I see on that link, the pins "1-M1 motor -" and "6-M1 motor +" should be connected to the motor driver. The other four pins should go to the Arduino only.
You can probably test the motor by disconnecting it and connecting pins 1 and 6 to a 9-12V battery or similar, to see if it turns.
By the way I guess the two Encoder Phase connections would be set up on the Arduino using PinMode setting "INPUT_PULLUP". But as you can already read the positions, that part may not matter.

m1 and m2 are the pins that you mentioned in 2nd paragraph.

I'll try connecting the motor pins to battery today and see if it turns.

It is not running when I connect 1st and last pin of the motor to the power supply. But if I connect another DC motor to the same power supply it runs.

Unfortunately it sounds like that motor has something wrong with it... I would get a meter (if possible) and measure the resistance across those two pins. If it's extremely high (mega ohms) or extremely low (below say 5-10 ohms) I'd say there's something wrong. You could also follow the traces on the board and measure at the two large solder "blobs" where they connect to the motor...

You know what...I connected those two large blobs to 12V power supply and the motor ran!!!! But I've run into some other problem...1 of my motor runs at a speed faster than the other one. When I pickup my bot above the ground both rotate but at different speed. But if I keep them on ground one does not rotate at all. I guess it is not able to generate enough torque. Please help!

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
What speaker can you drive with output pin?
I'm wondering how to drive a speaker using an arduino output pin.  I am using a pwm playback method with a sound data file.  If you wire a speaker across an output pin and ground then how do you calculate what speaker power and impedence you can use without damaging the arduino?  Is there a reference making these calculations?
Thanks

The Arduino can supply 5V at max 20mA so 5/0.02 ⇒ 250Ω (if you can find such a beast).
NOTE you should use a capacitor to prevent DC flow if using a conventional speaker.
In general the larger the speaker the better. Tiny speakers are inefficient transducers. Hi-Fi speakers are not a good choice, as they are often inefficient, trading efficiency for linearity.
An alternative, if you are a scrounger, is to scavenge a transformer from an old transistor radio - this should give the best match.

Typically the pins of an MCU are current sources, so a smaller load might be fairly harmless (if ineffective). The capacitor will help too in limiting average current.

I thought the sound volume and quality from a smartphone loudspeaker would be about right.  Not the earpiece but the one used for the loudspeaker.  Some are 10x15mm, most are 8ohm, .5 - 1W.  90dB  ex.)  http://www.knowles.com/eng/Products/Receivers-and-speakers/Dynamic-speakers  But I don't now how they are driven, probably a proprietary and expensive amp circuit.  To get the most value in the toy I'm interested in the simplest system, thus the single transistor method.

Milliways - The max current for the Uno is 40mA/IO pin.  Is this really how you size a speaker?  I have been told it has to do with the relative impedance of the devices but I haven't 'googlefound' any good references yet :(  BTW 5V/30mA = 167 ohms and I have found 150 ohm speakers but I still don't know if this is the right way to match a speaker and source.

@perigalacticon That is a rough engineering calculation. I am not sure the Arduino can deliver 40mA @ 5V (I have never measured). In fact the duty cycle would be 50% because the load is only actively driven on half cycle. Any higher impedance less current, lower less voltage swing. Speakers from phones are generally lower impedance, but the have higher powered drive circuitry. You could get more with a simple transistor amplifier.

@Milliways with 20mA due to 50% D.C. for lower impedance the voltage swing would only be reduced if the source was unable to provide the current correct?  Do you know of a source for more calculations?

@perigalacticon The comments were generic. I have not tested the ATMEGA under overload conditions. Engineers generally do not do this - it varies on different systems, which will either limit current or blow up. I always run to 40mA max/20mA per pin recommended of the specification.

Only very small ones with 20-30mA.  Earbud-size and slightly larger. You can buy a 2x3W amplifier which runs on 5V, and gives you two audio channels - but it works fine for mono. It can drive my 4 ohm desktop speaker, and is probably too powerful for that. Read about signal voltage and resistance for speakers. IIRC small audio outputs (like from an mp3 player) switch from -2.5V to 2.5V, giving an RMS of 5V. Or perhaps that was just my player. The only way to know this is to measure it - I played a sine wave and got a circa value. Offhand I can't say how to drive negative voltages from an arduino without extra circuitry. Hope it helps (and show us your code :)

USer400344 - I am trying to get max value into the toy so trying to I prefer to avoid the amp chip.  How do you calculate the size of speaker you can power with a given current?  Thanks.

The max value of your output pin is 5V/30mA (I would limit it to 20mA) - so 0.15W. As I said a speaker needs negative voltage as well. A PC speaker (the builtin kind for beeping BIOS codes) is probably driven by a transformed 5V source.

You need the speakers impedance for this as well, google audio output, 3.5mm TRS and RMS.

And I should add that driving 40mA from an uno pin is advised against by most of the arduino guys at arduino.cc - on USB power you can expect a total (all pins) of 400mA, on voltage regulator (raw/vcc) I would not go above 200mA. If you need to drive something with 40-60mA, you can attach pins in tandem (but keep each pin a few pins away from your other pin), and it will only work with digitalWrite(), not analogWrite()... I did this with a relay than needed 50mA to toggle (S pin), worked well. It's a good method if you have pins to spare, and don't want to add a transistor... offtopic, sorry.

so I can let the pin drive the speaker at 30mA.  If I progrogram the playback code to provide a signal centered at 2.5V then the signal can be 5V p-p.  With an amplitude of 2.5V this is an rms value of 1.7vrms.  Multiply by peak current 30mA gives .053Wrms power, is this what I use for speaker selection?  Do I choose the speaker ohms by 5V/.030A = 167ohms?  How much does the speaker inductance effect the impedence?  Thanks.

That's actually quite clever. I assumed the speaker membrane required negative voltage to 'move back' and positive to 'move forward'. If it just relies on a centered voltage that would make it simpler. Please post your results.

No, try measuring the resistance of a headphone speaker or builtin pc speaker. That's the type you can drive with ~30mA. A small amplifier board will really free you. Mine is tiny, and can drive 2 3W speakers from it. I supply 5V@500mA to the board and hook standard mp3 player audio to it. It does not do anything but amplify. It measures approx. 1.5cm by 3cm, cost me 3$

here are scope traces of a greeting card speaker voltages, and the speaker voltages from my application showing the detail of the pwm pulses.  I need to get the right caps to low pass filter the signal and then I'll try a few circuits.  The reason for no amp is cost, trying to keep the total toy cost under $5.  Greeting card speaker:  https://drive.google.com/file/d/0B-jN2Adg-YnuUG1wYzQxQVY3UzA/view?usp=docslist_api. Arduino pwm speaker:  https://drive.google.com/file/d/0B-jN2Adg-YnuR0VvTFN4NTZpTEk/view?usp=docslist_api

If it's a tiny speaker... those are driven from 3V sources. Have a look at the circuitry and find out how the negative voltage is generated (if it is at all generated). If you want something tiny for PWM, use an ATtiny85, they are very good for that. 8KB flash, 512B sram IIRC. Edit: Use something like the usb-asp ISP for attinys.

Thanks, for the greeting card trace I am surprised to see that the speaker terminal voltages are out of phase.  I was measuring each to ground, maybe the ground wasn't accurate?  How is it possible that one speaker terminal voltage increases while the other terminal decreases, is this expected maybe due to inductance?  I don't understand.

You should really ask on an AV forum.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
not getting proper bitstream output in serial monitor using digitalRead
I am producing a  data stream and feeding to a gpio pin. THe data is sampled at 2kbps. i want to dump this data into a file after a certain length of reading . how should i proceed with this ?

Not without seeing your code we can't.

My guess is that you are reading the port to often and not a multiple of the frequency of the wave.  So if your wave is 1Hz and you want to see 101010 then read at 1Hz not 4.25Hz.

You could clarify your question by describing the frequency of your test signal, and the sampling frequency. Unless you have an accurate reference clock (connecting the source and the sampling), you will need to oversample the signal, at least twice the toggle frequency, otherwise you will get a misleading result.

Without seeing your code it's impossible to tell just what is happening, but I would guess you are reading and printing the level of the wave, not the transitions from one level to another.
For instance:

As you can see, just reading regularly and printing it (which itself is quite slow) results in 11001101 rather than the 10101 that you want. That's because the speed of your reading/printing and the frequency of your wave are completely separate things and out of step with each other. There's nothing to tie one to the other.
Instead you need to look for the transitions from LOW to HIGH and from HIGH to LOW. Only when the input changes should you look to see what the new level is and print that.

As you can see the 1 and 0 are just after the change in level, since it's impossible to do anything during a change, only once the change has happened.
You might code that as something like:
void setup() {
    Serial.begin(115200);
    pinMode(3, INPUT);
}

void loop() {
    static byte oldValue = LOW;     // Place to store the previous level
    byte newValue = digitalRead(3); // Read the current level
    if (newValue != oldValue) {     // The input has changed
        oldValue = newValue;        // Save the current level
        Serial.print(newValue);     // Print it.
    }
}


text:
Informations lost in a string
At first, I sorry if I make some English faults but I'm French.
So, I'm making a connection between a client and an Arduino Uno. I receive all data that I need but when I send a response to my client some characteres are lost.
I receive this format : GET /?b=7&p=100$ (for exemple)
And my Arduino sends this to my client : GET /?b=7&p=1d
This is the function where I get all data from my client :
void read_data(int *state, int *progress_program){
  // Check if there is a client
  EthernetClient client = server.available();
  if (client) {
    url = "";
    index = 0;
    Serial.println("\nnew client");
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        Serial.println(c);
       if(c != '$') { // if end of char
          url[index] = c;
          index++;
        } else {
          url[index] = '\0';
          int i;
         Serial.print("\n");
          for(i=0;i<index;i++)
            Serial.print(url[i]);
          if(interpret(state, progress_program)){
            action();
            delay(100);
          }
          answer(client);
          break;
        }
      }
    }
    url[0] = '\0';
    // give the web browser time to receive the data
    client.stop();
    delay(100);
    Serial.println("\nclient disconnected");
  }
}

And the response sent to the client :
void answer(EthernetClient client){
  Serial.print("\nResponse"); // debug
  delay(100);
  client.print(url);
  Serial.print("Response Sent");
  delay(100);
}

With client.write(url) there is the same problem.
Have you got a solution?
thanks

How did you declare url? It should be an array, not a pointer.

I declare url like this : char *url = (char *)malloc(100);
But it's ok, my error was url = "";
With url[0] = '\0'; it's works !
Thanks

@electro I suggest you post that as an answer then. In time (with extra rep) you'll be able to then accept it as the correct answer and people with a similar problem will be able to find help easily. Be sure to detail just what the problem was and why it was a problem (what the effect of url=""; is)

So, the solution was very simple,
My pointer "url" received a constant null string with url=""; at the beginning. To initialize a string as null we need to make this :
 url[0] = '\0';

thanks


text:
PCINT with my arduino UNO says redefinition of 'void __vector_4()'
So i'm working on a quadcopter controlled by the arduino UNO, and focusing in pin interrupts for the reciever. This is the code for the reciever.
unsigned long timer[4];
byte last_channel[4];
volatile int input[4];

void rx_initialize() {
  PCICR |= (1 << PCIE0);
  PCMSK0 |= (1 << PCINT0);
  PCMSK0 |= (1 << PCINT1);
  PCMSK0 |= (1 << PCINT2);
  PCMSK0 |= (1 << PCINT3);
  Serial.begin(9600);
}

ISR(PCINT1_vect) {

  timer[0] = micros();//Lire la valeur PWM en microsecondes

  //////////////////////////CHANNEL1/////////////////////////////
  if(last_channel[0] == 0 && PINB & B00000001){//vaut digitalRead(HIGH); mais en plus rapide
    last_channel[0] = 1;//le state est HIGH
    timer[1] = timer[0];//Lire combien de temps HIGH
  }
  else if(last_channel[0] == 1 && !(PINB & B00000001)){
    last_channel[0] = 0;//le state est HIGH
    input[0] = timer[0] - timer[1];
  }

  //////////////////////////CHANNEL2/////////////////////////////
  if(last_channel[1] == 0 && PINB & B00000010){//Rising
    last_channel[1] = 1;//le state est HIGH
    timer[2] = timer[0];//Lire combien de temps HIGH
  }
  else if(last_channel[1] == 1 && !(PINB & B00000010)){//Falling
    last_channel[1] = 0;//le state est HIGH
    input[1] = timer[0] - timer[2];
  }

  //////////////////////////CHANNEL3/////////////////////////////
  if(last_channel[2] == 0 && PINB & B00000100){//Rising
    last_channel[2] = 1;//le state est HIGH
    timer[3] = timer[0];
  }
  else if(last_channel[2] == 1 && !(PINB & B00000100)){//Falling
    last_channel[2] = 0;//le state est HIGH
    input[2] = timer[0] - timer[3];
  }

  //////////////////////////CHANNEL4/////////////////////////////
  if(last_channel[3] == 0 && PINB & B00001000){//Rising
    last_channel[3] = 1;//le state est HIGH
    timer[4] = timer[0];
  }
  else if(last_channel[3] == 1 && !(PINB & B00001000)){//Falling
    last_channel[3] = 0;//le state est HIGH
    input[3] = timer[0] - timer[4];
  }
}

I'm using various files for every other part of the quadcopter such as PID controlling and IMU Reading.
But avrdude tells me that I did a redefinition of 'void __vector_4()'.
Itried to look into PinChangeInt.h in the Arduino library folder but still no solution to the problem.
Thank you for your help!

Did you look into using it?

Are you using SoftwareSerial perchance?

Hello? Are you going to answer my query?

Sorry i was using a library for PinChangeInterrupt and all vectors were declared in it. So i was declaring it twice and it was giving me errors.

I wasn't using softwareSerial BTW.

__vector_4() is just another name for PCINT1_vect(). The error
message simply means that you have defined that function twice. One
definition is explicit in the code you are showing to us. I cannot see
the other definition: obviously you are not showing all of your
code. Most likely that other definition lies inside some library you are
using in your program.
Since you cannot define an ISR twice, you will have to use another PCINT
which is not already in use. Or you could modify the library and try to
merge it's PCINT1_vect() with yours.
BTW, the error message does not come from avrdude, it comes from the
linker.

Thanks for everything guys.  I was using a library that defined these vectors.

The library I used defined the vectors. I just needed to comment them inside the library it worked fine. Thanks for everything!

just commented the lines and VOILA.

You should use the ISR(PCINT0_vect) instead of the ISR(PCINT1_vect).
Or if you want to use PCINT1:
PCICR |= (1 << PCIE1);
PCMSK1 |= (1 << PCINT8);
PCMSK1 |= (1 << PCINT9);
PCMSK1 |= (1 << PCINT10);
PCMSK1 |= (1 << PCINT11);

But them you have to change every PINB to PINC too as it uses a different PORT

I tried using your solution with PCINT0 and all corresponding pins(8, 9, 10, 11) but I still get the same error:

redefinition of 'void __vector_3()'

You should only use PCINT0 it the pins you already had and PCINT1 with 8 to 11. Changing both at the same time will give new errors

I mean i used this:

void rx_initialize() {
PCICR |= (1 << PCIE0);
PCMSK0 |= (1 << PCINT0);
PCMSK0 |= (1 << PCINT1);
PCMSK0 |= (1 << PCINT2);
PCMSK0 |= (1 << PCINT3);
Serial.begin(9600);
}
ISR(PCINT0_vect) {


text:
Reading Multiple switch inputs
I am trying to setup 20 input switches that can be pressed with hand. I am trying to get the output based on the pattern in which the input switches are pressed with the hand. Based on the pressure and the area of the hand pressing the input switches, there can be multiple switches that can be pressed to display the output pattern at the same time. How can I use Arduino Uno inputs to support these multiple pin reads at the same time?

You could use all your Uno pins, but none would be left for the output. Or you could use a parallel in serial out shift register.

Using a matrix is probably the best route - just like a keypad. 5x4 (9 pins) gives you 20 buttons with no extra hardware needed.

You could use a MCP23017 or similar.  Its an IC that provides 16 IO ports via I2C, I think you can have 4 of them so that should be enough for both hands.
Or you could use resistors.  All the buttons are connected to a single analogue port.  The resistors are chosen so that when you press any combination of buttons you will get a unique reading at the port. So if you press button one and get a reading of 100, press 2 and get 150, press 3 and get 200, etc.  So buttons 1+2 give you 250, 2+3 gives you 350 and 1+2+3 gives you 450.  The problem with this is the maths get out of hand very quickly and the IC is < $1.

I'd second the use of the MCP23017, have used this chip in several projects with good results, you can connect 8 of them together which gives 128 I/O pins.
Off the SDA/SCL pins UNO R3
Link Adafruit MCP23017
Also on Ebay from other suppliers.


text:
Single #include pulls in all libraries
I am tracking down the memory usage of an Arduino-like project I am working on (not a real Arduino, but has same microcontroller and it uses the Arduino build environment, version 1.6.8). I have some modules that I am using and placed them in the Libraries directory in my sketch directory:
Encoder
LiquidCrystal
OneWire
TGPages
TGPro

Now, when I compile a minimal sketch...
#include <Arduino.h>

void setup()
{
}

void loop()
{
}

...the compiled size is 450 bytes Flash and 9 bytes RAM. So far, so good.
Now here's the weird part: when I include a single header file from anywhere in the Libaries folder, the compiled size increases dramatically.
#include <Arduino.h>
#include "pins.h"

void setup()
{
}

void loop()
{
}

"pins.h" is located in the TGPro directory and only contains #defines, not even code or other includes.
....
Using library TGPro in folder: C:\Users\User\Project\TG\libraries\TGPro (legacy)
Using library OneWire in folder: C:\Users\User\Project\TG\libraries\OneWire (legacy)
Using library Encoder in folder: C:\Users\User\Project\TG\libraries\Encoder (legacy)
Using library LiquidCrystal in folder: C:\Users\User\Project\TG\libraries\LiquidCrystal (legacy)
Using library EEPROM at version 2.0 in folder: C:\Users\User\Project\TG\hardware\arduino\avr\libraries\EEPROM
Using library Wire at version 1.0 in folder: C:\Users\User\Project\TG\hardware\arduino\avr\libraries\Wire

Sketch uses 2,266 bytes (7%) of program storage space. Maximum is 32,256 bytes.
Global variables use 230 bytes (11%) of dynamic memory, leaving 1,818 bytes for local variables. Maximum is 2,048 bytes.

And I'm like: WTF? I'm not even referencing any of the files, still they get pulled in, wasting space. There are a few global, static variables in there which explain the used space and referenced code.
So, my questions:

Is het normal for Arduino to pull in all files in the Sketch\Libraries directory, regardless if they are referenced or not? It doesn't seem to do this with the 'core' libraries.
How can you prevent this? Suppose I have a large collection of modules that I use in various projects, but not all modules are used all the time. It would be a waste to include code that is never actually used.
How can I find out more about the code that is compiled in; I know the linker will leave out unreferenced code, but I want to make sure this is due to the statically defined variables.

avr-nm -C the_compiled_program.elf should tell you what's in there (your question 3).

What you are experiencing is due to the fact that your use case does not match with the Arduino foreseen use cases of "importing a library".
Basically you want the use case "include a file" and you get "import a library". The use case "import file" is simply not foreseen in the Arduino IDE.
Because the Arduino IDE add the library to your code it also adds the source doe files to your code. When these source codes contain global variables (which is very common and not a bad practise in embedded world) these will be part of your final code. As such your sketch will increase size even if you do not use these global variables.
To answer questions
1) yes it is normal because the use case "include file" is translated into "include library" in .ino files in the Arduino IDE.
Why this does not happen for the core? The core is first linked into a archive and then linked to the sketch. This leaves the linker more options to remove stuff.
2) I think the easiest is to copy the pins.h file in your sketch work folder (and you probably will need to restart the Arduino IDE).
Another option is to go for a real IDE like the arduino eclipse plugin called sloeber (which I develop)
In sloeber you could link to the pins.h file instead of copying. You could also reference the pins.h with a (partial/full) path avoinding the library include.
3) All global variables, static and similar stuff in the source code of the "imported libraries"

I know that Arduine pulls in the source code. However, my understanding so far is that if I include, say "lcd.h", it would import "lcd.cpp" together with its includes, and so on. I do not expect (nor want) everything to be pulled in, just because the file is in a particular directory.  2a) pins.h is already in the sketch folder, under Libraries. 2b) Copying files is of course unaccaptable; that will create a versioning nightmare. The idea is to share files between projects (sketches), of course. 2c) What would sloeber accomplish? 3) yes, Edgar Bonet's comment already gave a few hints.

that would be the use case "import class". I have never seen this usecase anywhere in c/c++.
2a) yes but it is there in such a way that also the c/c++ files are there.
2b) you could consider making a library only containing pins.h
2c) added 2 options to the answer.


text:
Audio sampling and serial communication
tl;dr: The sample rate of my code seems to be lower than what I expect it to be. How can I fix this?
Director's cut:
I am trying to sample audio data and send it via serial. The setup consists of a guitar plugged into an amplifier (about 10x) + low-pass filter (second order, around 1kHz) + voltage divider (centered at 2.5V), that is then connected to and Arduino Uno Rev3. When the Arduino receives a 'cap' command via serial, it enables the interrupt-based function that takes samples and sends them via Serial. With the 10-bit resolution, it gives me a number between 1 and 4 digits. With a baud rate of 115200 and adding 1 byte for the '\n' character, the slowest rate is of 2880 values per second, but most likely around 3.6k values per second (3+1 characters).
From what I understood (not used to working with timer interrupts), I've set up timer1 so that it doesn't have any prescaling, and it should be running pretty close to 2048Hz. The interrupt sequence reads the data at the analog input and sends it via Serial (for now, to the computer; later, a smartphone via Bluetooth).
To check if it is working, I am copying the data received by the computer, putting it into Matlab and running the sound(data, sampleRate) function. If I run it with 2048 as sampleRate, I get a clearly higher pitched sound, which indicates that the sample rate is in fact lower. Testing different values, I found that it sounds close enough around 1900.
From what I've read, the serial and the timer interrupt work in parallel, and the serial is faster than the capture. Why am I getting this apparently lower sample rate? How can I fix this?
Code:
// Variables
const int sampleRate = 2048; // Sampling rate
const int numSamples = 2048; // Number of Samples
//volatile int samples[numSamples]; // Data array
int currentSample = 0;
boolean capturing = false; // flags if it is in capture mode
boolean done = false; // flags if the capture is done
char chrCommand; // holds current character read
String strCommand; // joins the complete command string

// Functions
void captureSample();
void readCommand();
void executeCommand();

void setup() {
  /****************
   * Timer Setup
   ****************/
  cli(); // stop interrupts
  // set timer1 interrupt at 2048Hz
  TCCR1A = 0; // set the entire TCCR1A register to 0
  TCCR1B = 0; // set the entire TCCR1B register to 0
  TCNT1  = 0; // initialize counter value to 0
  // set compare match register for 2048Hz increments
  OCR1A = 7811; // = (16*10^6) / (sampleRate) - 1
  // turn on CTC mode
  TCCR1B |= (1 << WGM12);
  // no prescaling
  TCCR1B |= (1 << CS10);
  // enable timer compare interrupt
  TIMSK1 |= (1 << OCIE1A);
  sei(); // allow interrupts

  /****************
   * Serial Setup
   ****************/
  Serial.begin(115200);

  pinMode(13,OUTPUT);
}

void loop(){
  if(!capturing){
    // Case: waiting for command
    if(!done){
      if(Serial.available() > 0){
        readCommand();
        executeCommand();
      }
    }else{
      done = false;
    }
  }
}

/************************
 * Function Definitions
 ************************/

// Timer function
ISR(TIMER1_COMPA_vect){
  if(capturing){
    captureSample();
  }
}

void captureSample(){
  //samples[currentSample] = analogRead(0);
  Serial.println(analogRead(0));
  ++currentSample %= numSamples;
  if(currentSample == 0)
  {
    done = true;
    capturing = false;
  }
}

void readCommand(){
  strCommand = "";
  while(Serial.available() > 0)
  {
    chrCommand = ((byte)Serial.read());
    if(chrCommand == '\n')
    {
      break;
    } else
    {
      strCommand += chrCommand;
    }
    delay(1);
  }
}

void executeCommand(){
  // Command cap = capture
  if(strCommand == "cap"){
    capturing = true;
    return;
  }
  // Command mov = move
  if(strCommand == "mov"){
    // get the motor movement in the following command
    readCommand();
    moveMotor();
    return;
  }
  if(strCommand == "clr"){
    done = false;
    capturing = false;
    for(int i = 0; i < 2; ++i){
      digitalWrite(13,HIGH);
      delay(50);
      digitalWrite(13,LOW);
      delay(50);
    }
    return;
  }
}

If you run with different (higher) baud rates does the sample frequency change?

I've increased the baud rate and it seems to be working fine. For now, I think this will work, unless something limits my baud rate. Thank you!

You calculation of the data rate is wrong:

Serial.println() adds CRLF (i.e. "\r\n") to terminate the line,
That's 2 bytes, not one.
Each byte is sent by the serial port as one start bit, followed by 8
data bits, followed by one stop bit. That's 10 bits in terms of
timing.

In the worst case scenario (value ≥ 1000), you are sending 6 bytes,
or 60 bits: the fastest possible rate is 1920 samples per
second. In the arguably most common case (100 ≤ value < 1000), you send
50 bits per sample at up to 2304 S/s.
Edit: Here are a few optimization tips, just to make sure your
program is not CPU-bound:

Declare captureSample() as static, this way the compiler can
inline it and save the call overhead.
Make currentSample unsigned, this way the compiler can optimize the
modulo operation into a bitwise AND.
Replace analogRead(0) with a direct read of the ADC register, and
start the next ADC conversion right away. This way you do not have to
wait for 104 µs while the ADC does its work.
You may want to move the Serial.println() out of the ISR, otherwise
you may be blocking interrupts for too long if the serial port cannot
cope with the sampling rate.
Make some kind of binary protocol instead of using plain ASCII.

You may also trigger the ADC directly from a timer instead of going
through the timer ISR (see the datasheet for details). You would then
use ISR(ADC_vect) to retrieve the ADC result. This way you get a very
steady (hardware controlled) sampling rate.
More about the binary protocol: you could send only two bytes per
sample and remain ASCII-compatible (which is often desirable) by using
32 printable characters to represent 5 bits. This is the same idea used
in base64, but simplified to use consecutive characters:
uint8_t high_5_bits = sample >> 5;
uint8_t low_5_bits  = sample & 0x1f;
Serial.write('@' + high_5_bits);
Serial.write('@' + low_5_bits);

This gives a stream of characters in the range @A-Z[\]^_. Then your
maximum sampling rate is 5760 S/s.

Following @Majenko's suggestion, I've increased the baud rate and it seems to work fine. Still, I will try to implement these tips, make it better. Thank you very much for the answer!


text:
Sending Arduino data to MySQL using phpMyAdmin and XAMPP using Windows10
I want to send my Arduino's sensor data to a MySQL database, using XAMPP and phpMyAdmin. I have been using an ESP8266 for the wifi connection. But I am unable to send the value. And actually I have to send four values, but for the time being I am sending only one value. So also please tell how to send multiple values. I have written the PHP file and saved in to Apache's htdocs.
#include <WiFiEsp.h>
#include <WiFiEspClient.h>
#include <WiFiEspUdp.h>
#include <SoftwareSerial.h>
#include <PubSubClient.h>
#include <SPI.h>
IPAddress ip(192,168,8,1);
char ssid[] = "ZONG MBB-E8372-B67D"; // your network SSID (name)
char pass[] = "08522547"; // your network password
int status = WL_IDLE_STATUS; // the Wifi radio's status
int photocellPin = 4; // Analog input pin on Arduino we connected the SIG pin from sensor
int photocellReading; // Here we will place our reading
char server[] =  "192.168.8.1";
// Initialize the Ethernet client object
WiFiEspClient espclient;
SoftwareSerial soft(2,3); // RX, TX

void setup() {
  // initialize serial for debugging
  Serial.begin(115200);
  // initialize serial for ESP module
  soft.begin(115200);
  // initialize ESP module
  WiFi.init(&soft);
  // check for the presence of the shield
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue
    while (true);
  }
  // attempt to connect to WiFi network
  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network
    status = WiFi.begin(ssid, pass);
  }
  // you're connected now, so print out the data
  Serial.println("You're connected to the network");
}

void loop() {
  photocellReading = analogRead(photocellPin);
  // Fill the sensorReading with the information from sensor
  // Connect to the server (your computer or web page)
  if (espclient.connect(server, 80)) {
    espclient.println("GET /write_data7.php?"); // This
    espclient.println("value="); // This
    espclient.println(photocellReading);
    // And this is what we did in the testing section above.
    // We are making a GET request just like we would from our browser
    // but now with live data from the sensor
    espclient.println(" HTTP/1.1"); // Part of the GET request
    espclient.println("Host: 192.168.8.1");
    // IMPORTANT: If you are using XAMPP you will have
    //to find out the IP address of your computer and put it here
    // (it is explained in previous article). If you have a web page,
    // enter its address (ie.Host: "www.yourwebpage.com")
    espclient.println("Connection: close");
    // Part of the GET request telling the server
    // that we are over transmitting the message
    espclient.println(); // Empty line
    espclient.println(); // Empty line
    espclient.stop();    // Closing connection to server
  } else {
    // If Arduino can't connect to the server (your computer or web page)
    Serial.println("--> connection failed\n");
  }

  // Give the server some time to recieve the data and store it. I used 10 seconds here. Be advised when delaying. If u use a short delay, the server might not capture data because of Arduino transmitting new data too soon.
  delay(10000);
}

Following is the PHP code:
<?php
//connecting to the database
define('DB_HOST', 'localhost');
define('DB_NAME', 'connected_car_1');
define('DB_USER','Maryam1');
define('DB_PASSWORD','telecom1213');

$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());

$sql = "INSERT INTO connected_car_1.sensor (value) VALUES ('".$_GET["value"]."')";
// Execute SQL statement
mysql_query($sql,$con);
mysql_close($con);
?>

And this is my serial monitor output:

I am very new to coding in Arduino as well as PHP and databases. So kindly tell me what I am doing wrong. And do I have to provide the IP address of the server, ie. 127.0.0.1? If yes, then where?

Nice SQL injection attack vulnerability there. (http://yoursite.com/yourpage.php?value=');+drop+database+connected_car_1;--Will people never learn? Hint : Use PDO.

I am not uploading on a webpage. I am uploading on mysql. That is the comment in the code for if you want to upload it on a webpage, but iam not doing that.

You have a piece of PHP code there. That is a web page. It accepts GET parameters.

then how should i upload the arduino reading on mysql?

Through a web page, like you have created. Just learn, right from the beginning, best practices. Your web page, if it were ever public, would be a huge security risk.

I have to submit it after 1 week..so can you help and give some hints so that i learn fast?

Your problem looks to not be anything to do with MySQL, XAMPP, or anything like that. You seem to have a basic inability to communicate on the WiFi network. All those "Timeout" messages should tell you that much at least.  Get the network connection working first and then work on interfacing with MySQL.

i have googled to much already but found this code working much more better to connect to a wifi network. Can you give me some good links?

Step one: run some of the examples that come with your WiFi library to confirm that you can connect to your network correctly. There's huge numbers of warnings and errors in your output that tell me that something is fundamentally wrong with your setup. The ESP8266 is not a simple board to use with an Arduino.

Isn't GET the wrong verb to use when writing to a web server?

#include (avr/pgmspace.h) ^ compilation terminated. exit status 1.
Compile error card NodeMCU 1.0 (ESP-12E Module).

Its not very clear what this "Answer" is for, please can you edit it to clarify or delete it.

@CodeGorilla. The right verb is POST or PUT. POST for creating things, PUT for creating/updating things, according to HTTP/1.1 specs.

@LookAlterno - I know, I was trying to be subtle :)

192.168.8.1 should be your PC IP. Where your apache should be running. You can check it by visiting http://192.168.8.1/write_data7.php and see if the server is ok or not. Then you can try access from another machine to make sure no firewall is blocking you

Not sure how PDO would prevent SQL injection. After error checking data use mysql_real_escape_string()

You should write the PC IP, for example: 192.168.1.53, because 127.0.0.1 is the IP used only for phpmyadmin and the database inside your computer.

Being pedantic: 127.0.0.1 is the internal IP address present in every IP device, and it's use as a shorthand for "this machine". It's use for TCP/IP comms between process running in the same machine, like any program that need to access the local database (as you said). 127.0.0.1 is not routeable, and not accesible from other machines.


text:
Code example SPI multiple slaves Arduino DUE
I'm trying to get 2 devices (camera and sd card)to work on the SPI interface with an Arduino DUE.  I'm having trouble finding example code online showing how to communicate with multiple slaves on the DUE as I know it is slightly different than with the UNO.
Questions I have include:
How do you indicate you want to talk to a slave on pin 4? Instead of digitalWrite(4,LOW) do you call SPI.begin(4)? etc..
Can someone post some example code?

Everything you need is given here - you just need to know how to put it together:

https://www.arduino.cc/en/Reference/DueExtendedSPI

There are variants of all the major methods that take an extra parameter - that parameter is the first parameter in the parameter list and defines the SS Pin to use for that function.  That includes the .transfer() function.
To use it you have to begin() all the pins you want to use SPI with. Then you can use .transfer() with those pins:
void setup() {
    SPI.begin(10);
    SPI.begin(4);
}

void loop() {
    // Receive using pin 10 as SS
    byte byteFromTen = SPI.transfer(10, 0x00);
    // Transmit 123 using pin 10 as SS
    SPI.transfer(10, 123);
    // Both directions:
    byte otherByteFromTen = SPI.transfer(10, 123);

    // Receive using pin 4 as SS
    byte byteFromFour = SPI.transfer(4, 0x00);
    // Transmit 123 using pin 4 as SS
    SPI.transfer(4, 123);
    // Both directions:
    byte otherByteFromTen = SPI.transfer(4, 123);
}

Doing multi-byte transfers is slightly more complex since you don't have control over the SS pin, so you have to use yet another version of the transfer() function that tells it to "continue" the transaction:
// Receiving 3 bytes using pin 4:
byte firstByte = SPI.transfer(4, 0x00, SPI_CONTINUE);
byte secondByte = SPI.transfer(4, 0x00, SPI_CONTINUE);
byte thirdByte = SPI.transfer(4, 0x00);

Of course, mixing reading and writing is pretty much the same as usual. For instance, to read the port A values from an MCP23S17 would look like:
SPI.transfer(4, 0x41, SPI_CONTINUE); // Address 0, read bit set
SPI.transfer(4, 0x12, SPI_CONTINUE); // Select register 0x12 (GPIOA)
byte porta = SPI.transfer(4, 0x00);

The SPI_CONTINUE tells the SPI system to keep the SS pin LOW. It is only then raised once it gets a .transfer() without the SPI_CONTINUE. This is the same as the traditional way of using digitalWrite() to lower SS before the first transfer and raise it after the last transfer.


text:
Complete Bread board arduino
I bought a ATmega328 microcontroller and burn the bootloader. Now I want to upload code directly from pc to the microcontroller on bread board. I have max232 ic for the communication but I recently knew that I need a serial port rather usb to connect max232 to pc. There are many usb to serial converter available on the market but can I make my own? One more thing is there any other way burn program from arduino ide to microcontroller via USB on bread board without having the arduino board. Or can I burn program to microcontroller on the bread board from arduino board without removing the on board ic.

If you don't have that hardware in place, you don't have an  "complete" Arduino.

There are many usb to serial converter available on the market but can I make my own?

Yes, but if you need to ask how then you're not ready to undertake the task.

One more thing is there any other way burn program from arduino ide to microcontroller via usb on bread board without having the arduino board.

Yes. The IDE doesn't care how you connect to the MCU, only that it has the appropriate bootloader for the programming method.

Or can I burn program to microcontroller on the bread board from arduino board without removing the on board ic.

ArduinoISP will let you use an existing Arduino as an AVR ISP programmer. ISP does not require a bootloader, nor does it require a serial (UART) connection.

yea thank you. what is the issue of designing own usb to serial converter ;

Laying out a USB device needs knowledge and a bit of experience. It's not something for a novice.


text:
send mixed data over serial
I want to launch a communication between two Arduinos, in which case the first Arduino (S) sends data to the second one (R). The type of the data is mixed, consisting of integers, longs, floats and maybe some text. For example:
{125, 1250, 12500, 125000, 1.25, 12.5, 125.0, "some text"}

I thought about converting each one value to string, adding up all strings to a big one, and send the final string with  Serial.print(Big_string).  In that case I reckon that it would be difficult for the Receiver to extract the string to the exact substrings and convert them to real values.
A second thought was to convert all values to bytes and create a byte (or char) array, but each value would be limited to 0-255 (let alone floats and text)
A third thought was to convert them to word type (let alone the text), but I think that Serial.print( ) sends only bytes, not words.

In any case, which is the best way to send mixed data over serial?
Any thoughts would be appreciated.

Please, tell us a little bit more about those data types. Are they always the same (e.g. always 2 ints, 2 longs, 3 floats and 1 string)? Do you know the maximum possible length of the string? Is it small enough that padding to that length would not be too wasteful? Can you guarantee that the string will have no embedded comma (or semicolon, or other char that you could use as a field separator)?

I didn't have enough reputation to make a comment! you can check out the answer to this post. Ask me if you had any questions.

@ Edgar Bonet Yes, alwayws the same. Small string. No commas or other "strange" character.

I think the easiest way to solve your problem is using a separator and transmit the array values one after the other. That means having a for loop and in every iteration sending one value of the array with
Serial.println(array[i]).
The function will

convert numbers into Strings so you will get "125", "1250", ...
append a carriage return character (ASCII 13, or '\r') and a newline character (ASCII 10, or '\n')

On the receiver side you can simply wait for Serial.read() to equal the number 13 and (immediately afterwards) 10 and split the messages there. That works unless your transmitted strings contain new lines.
The disadvantage is, that numbers are of course transmitted in an unefficient way. If you want to transmit them as real numbers instead of strings you have to write your own protocol. This video "Wireless Module Multiple Receivers" goes into that direction, it's using a fixed packet length but it gives an idea of how such a thing works.

I didn't expect so many answers, thus I need some time to work them out. Thank you.

I have a library that does exactly what you want. It can also work with RS-485 and RS-422 multi-drop networks.

https://github.com/MajenkoLibraries/ICSC

You can even get it communicating with a Linux computer (such as a Pi or BeagleBone Black) with the Linux library:

https://github.com/MajenkoLibraries/icsc-linux

You can use it to send data of any kind between nodes and trigger specific functions to be executed (like RPC) at the remote end.

I didn't expect so many answers, thus I need some time to work them out. Thank you.

If you want to communicate between 2 arduino's with similar cpu (for instance uno and mega) I would go for binary data in a struct.
When using a struct you can not use the String class but you can use a char array.
Consider this struct as example
struct SerialDataPacket
{
        int someIntegerData;
        long someLongData;
        int someMoreIntegerData;
        char aString[20];
};

You can send this struct as follows:
String myString;
SerialDataPacket transmissionPacket;
transmissionPacket.someIntegerData=1;
transmissionPacket.someLongData=millis();
transmissionPacket.someMoreIntegerData=2;
strncpy(transmissionPacket.aString,myString.c_str(),min(20,myString.length()));
Serial.write((uint8_t *) &transmissionPacket, (uint16_t) sizeof(SerialDataPacket));

you can receive the struct at the other side as follows:
Serial.readBytes((uint8_t *) &transmissionPacket, (uint16_t) sizeof(SerialDataPacket));
myString=transmissionPacket.aString;

Again this method will only work if you have possessors with the same memory byte order. If the processors have a different bit (8 16 32 bit) you lust use processor independent types for it to work.

@jante I didn't expect so many answers, thus I need some time to work them out. Thank you.

If your primary concern is transmission speed, you might consider turning everything into bytes and reversing the process at the other end.  If speed is not important, you can use sprintf() to create a character string and sscanf() to parse out the character string at the other end.
Turning everything into bytes is a very custom / specific approach.  A character would turn into 1 byte, an integer into 2 bytes, ect.  You would have to write custom code to encode this and remember to write code at the other end to do exactly the reverse process.  The advantage is that you would only be sending your data and no other information.  But this approach is not vary flexible.  If you were able to fit your data into 1 byte then suddenly needed 2 bytes (for example, a value once always less than 255 was now 300), you would have to re-write your code at both ends of the connection.
Turning everything into a string with sprintf() is very similar to printing out all your data.  You will be including extra characters like commas and / or space for delineation. At the other end sscanf() is used to parse out the character string.  At both ends, if done properly, all string assembly and parsing should be done by only these 2 calls.  And some issues are taken care of automatically.  For instance, the number 100 is 3 characters long and the number 10 is 2 character long.  But the sprintf() and sscanf() calls automatically compensate for these (reasonable) variations and continue to work as expected.
added later...
FYI: Even though sscanf() is available for the Arduino, it is not clear to me if it is well supported.  You might try testing (create and parse a string in the same sketch) what you want to send / receive before actually committing to this method.

If you are going to send binary between two Arduinos, no need to encode anything: just send the data as it is in memory. This is explained in jantje's answer.

@st2000 I didn't expect so many answers, thus I need some time to work them out. Thank you.


text:
Arduino Uno and ESP01: can't issue AT commands [Solved]
I would like to connect an Arduino Uno and an ESP 01 module. I use the Arduino IDE and I tried to test communication via serial monitor. I get the "ready" message from the ESP 01, but I am not able to issue AT commands from the serial monitor. It only displays random characters on the console.
It seems that no newline character is issued, because if I try to insert commands, they are inserted next to previous characters. I use "Both NL & CR" and 115200 baud settings in Arduino IDE. I tried 9600 baud too, but then the text is unreadable.
I used the following pins on my ESP-01:
Vcc -> 3,3V
Gnd -> Gnd
Rx  -> Tx(pin 0) of my Arduino, used voltage divider to make it 3.3V.
Tx  -> Rx(pin 1) of Arduino
CH_PD -> 3.3V

Please see serial monitor screenshot:

EDIT: PROBLEM RESOLVED:
My Arduino is connected to my PC via USB, so I changed pins for communication with the ESP by SoftwareSerial to pins 10 and 11. Now it works. Thank you.

Just to have an answer instead of just an edit/addition to the question:

EDIT: PROBLEM RESOLVED:
My Arduino is connected to my PC via USB, so I changed pins for communication with the ESP by SoftwareSerial to pins 10 and 11. Now it works. Thank you.

Ok... sure... your Uno's Atmega384 was talking with pins 0 and 1 to the USB adaper chip (Atmega16u2 on Uno R3) and at the same time to the ESP-01.
Read the fine schematic: Arduino Uno R3

It could be the case, that the Arduino power supply is insufficient.
"[...] note that the Arduino 3.3V regulated output (50 mA max) can't drive the current requested by the ESP (Up to 200 mA). Some tutorials on the Internet use the Arduino 3.3V to power the ESP, but it didn't worked for me. I'm using an external power supply (An old 5V Android charger)."Source
Possible, that the power consumption was within range when the readable text was printed and too high when all the unreadable stuff was sent.

Tried to use power supply with 3,3V / up to 1A and now and received only random characters instead of "ready"message :(

Also, I inserted power source directly to Vcc pin of ESP, didnt uset any kind of diode/stabilizator etc, this could problem maybe?

Also, my voltage divider is: 3300 Ohm and 6600 Ohm, not sure if this is ok :x


text:
Oxygen sensor up to 50%
Are there any oxygen sensors that measure up to 50%?.
As I understand, there are sensors that measure only in range 0-30%.
Is it possible to increase the threshold of sensitivity of the sensor?

You can try SO002 or DS-TR250.

Is it possible to increase the threshold of sensitivity of the sensor?

I don't think its possible. Perhaps you can tweak the reading sensitivity, but since the sensor are mostly analog, it's not possible. And maybe that also the reason the 2 sensors I've mentioned above have several series based on their measuring threshold.

The Bosh LSU 4.X sensor(s) are what I think you are looking for. Here are some related links:
http://www.waltech.com/open-source-designs/wbo2_report/
https://github.com/Hell-Fire/WidebandO2


text:
Receiver Module Second Data Pin
Many of the receiver modules (MX-05V) working with the Virtual Wire library (I would like to add a link here but it requires 10 reputation, so I'll do that later) have two data pins. However only one of them is used in the examples I have seen so far.
This picture shows a transmitter (top left) and a receiver (bottom right). Apparently the receiver has four pins - two of them are data pins.

Image source
What is the purpose of the second data pin on the receiver module and how to use it?

you can still put the part number of the module in your question.  Someone might then edit your post and put in the data sheet.

I would expect only one data line output from the receiver.
Looks like the manufacturer might have just connected the 2 data pins together. You could try using either pin to confirm that the two data output pins are simply connected together.


text:
Trouble reading analog (PWM)
I'm trying to test my analog signal before I send it to an actual analog device. I've written some code and considering the analog square I have expected to see a digital ON or OFF during a single duty cycle but I'm either seeing all OFF for analog values 0-127 and all ON for values 128-255.
My expectation is that I would see 51 ON and 49 OFF thus getting a value closer to 128 of 255.
What am I missing? Is this even possible?
int OUTPUT_PIN = 2; // digital 2 (PWM)
int INPUT_PIN = A0; // analog 0

void setup() {
  pinMode(OUTPUT_PIN, OUTPUT);
  pinMode(INPUT_PIN, INPUT);

  Serial.begin(9600);
}

void loop() {

  analogWrite(OUTPUT_PIN, 128);

  float j = 0;
  for(int i = 0; i < 100; ++i) { // get 100 reads per duty cycle
    float v;
    v = digitalRead( INPUT_PIN );
    if(v >= 1) Serial.println("ON");
    if(v <= 0) Serial.println("OFF");
    j += v;

    delay(12); // trying to match the duty cycle
  }
  j /= 100; // average out the 100 reads

  Serial.println(j);

}

Seeing all on for 128+ and all off for 127- is indicative that you are using a pin that can't do PWM.
If you use a non-PWM pin with analogWrite it goes "Is this less than 128? Yes? Then I will turn it off. Otherwise I will turn it on.".
case NOT_ON_TIMER:
default:
    if (val < 128) {
        digitalWrite(pin, LOW);
    } else {
        digitalWrite(pin, HIGH);
    }

Since you don't mention what board you are using I can only assume that you have picked a pin that can't do PWM. Change to a pin that can do PWM and you should get a PWM signal.

I tried on both Mega 2560 and Uno. I see now on the uno that some digital pins have a ~ in front of the number. Coincidentally these are the only pins which send a PWM signal. Moving from outpin pin 2 to 3 solved the issue.

That's not coincidental. The ~ is used to denote which pins can do PWM. Like it says on the board: DIGITAL (PWM ~)

You are completely right. You've certainly made me very aware of my rookie mistake. Thanks for your time in helping me track down my issue.


text:
Bizarre behavior, loop function affects setup function
I've connected two stepper through two uln2003 chip. And wrote a small class to control them.
The class works perfectly and I'm able to control the steppers (rotate the CW and CCW).
My main code looks like this :
#include "StepperControl.h"

StepperControl myStepperControls[2];

void setup() {
    delay(1000);
    myStepperControls[0].init(6,5,4,3);
    myStepperControls[1].init(11,10,9,8);

    delay(1000);
    for (int i = 0; i < 2; i++)
    {
        myStepperControls[i].DelayBetweenSteps = 1200;
        myStepperControls[i].StepCCWDegree(90);
        myStepperControls[i].StepCWDegree(51);
    }
}
int moveNumber = 0;
void loop(){
    int stepperNumber = moveNumber / 2;
    bool cw = ((moveNumber % 2)  == 0);
    moveNumber = (moveNumber + 1) % 4;
}

As you can see I:

Init both instances of the class to different pins.
Set the Delay between the steps (in microseconds).
Rotate myStepperControls[0] counter clock wise and then clock wise.
Same for myStepperControls[1]

This doesn't work correctly, one of the motors doesn't move clock wise.
It is not always the same motor !! For the last hour the problem appeared only in myStepperControls[0], now it is only in myStepperControls[1].
I'm 100% sure it is not a wiring/electrical problem because:

If I'll delete the content of the loop (which runs after setup) it will fix the problem.
If I'll make the delay between steps 2000 it will fix the problems.
As I've mentioned the problem was only in myStepperControls[0] for an hour, in that hour i switch the pins of the motors and still the motor that was connected to myStepperControls[0] was not able to rotate CW.

Any suggestions to how to investigate the problem will be appriciated
Here is my library code:
// StepperControl.h

#ifndef _STEPPERCONTROL_h
#define _STEPPERCONTROL_h

#if defined(ARDUINO) && ARDUINO >= 100
    #include "arduino.h"
#else
    #include "WProgram.h"
#endif

class StepperControl
{
 public:
    StepperControl();
    void init(byte blue, byte pink, byte yellow, byte orange);
    void StepCW(int steps);
    void StepCCW(int steps);
    void StepCWDegree(float degrees);
    void StepCCWDegree(float degrees);
    const int StepsPerFullRotation = 4076;
    int DelayBetweenSteps;
 private:

    void setPinsState(byte step);

    byte m_currentState;
    byte m_pinValuelookup[9];

    byte m_bluePin; // = 11;    // Blue   - 28BYJ48 pin 1
    byte m_pinkPin; // = 10;    // Pink   - 28BYJ48 pin 2
    byte m_yellowPin; // = 9;    // Yellow - 28BYJ48 pin 3
    byte m_orangePin; // = 8;    // Orange - 28BYJ48 pin 4
                            // Red    - 28BYJ48 pin 5 (VCC)

};

#endif

here is the cpp file :
#include "StepperControl.h"

StepperControl::StepperControl() : m_pinValuelookup{B01000, B01100, B00100, B00110, B00010, B00011, B00001, B01001, B00000}, DelayBetweenSteps(1100), m_currentState(0)
{
}

void StepperControl::init(byte blue, byte pink, byte yellow, byte orange)
{
    m_bluePin = blue;
    m_pinkPin = pink;
    m_yellowPin = yellow;
    m_orangePin = orange;

    pinMode(m_bluePin, OUTPUT);
    pinMode(m_pinkPin, OUTPUT);
    pinMode(m_yellowPin, OUTPUT);
    pinMode(m_orangePin, OUTPUT);
    delayMicroseconds(DelayBetweenSteps);
    setPinsState(8);
    delayMicroseconds(DelayBetweenSteps);
}

void StepperControl::StepCW(int steps)
{
    for(int i = 0; i < steps; i++)
    {
        m_currentState = (m_currentState - 1) % 8;
        setPinsState(m_currentState);
        delayMicroseconds(DelayBetweenSteps);
    }
    setPinsState(8);
}

void StepperControl::StepCCW(int steps)
{
    for(int i = 0; i < steps; i++)
    {
        m_currentState = (m_currentState + 1) % 8;
        setPinsState(m_currentState);
        delayMicroseconds(DelayBetweenSteps);
    }
    setPinsState(8);
}

void StepperControl::StepCWDegree(float degrees)
{
    float steps = degrees * (float)StepsPerFullRotation / 360.0f;
    StepCW((int)steps);
}

void StepperControl::StepCCWDegree(float degrees)
{
    float steps = degrees * (float)StepsPerFullRotation / 360.0f;
    StepCCW((int)steps);
}

void StepperControl::setPinsState(byte step)
{
  digitalWrite(m_bluePin, bitRead(m_pinValuelookup[step], 0));
  digitalWrite(m_pinkPin, bitRead(m_pinValuelookup[step], 1));
  digitalWrite(m_yellowPin, bitRead(m_pinValuelookup[step], 2));
  digitalWrite(m_orangePin, bitRead(m_pinValuelookup[step], 3));
}

Some one helped me in the Arduino forums, and I felt obligated to add the answer here :
The : m_currentState = (m_currentState - 1) % 8; is the bug.
I accidentally assumed that doing % on -1 will jump to 7.
Somehow this caused the strange behavior I had.

You found the solution yourself. I am posting this answer anyway just to
give some background on the problem.
I must say you were somewhat unlucky: you have just hit a couple of the
least intuitive features of the C and C++ languages: integral promotion
and signed division.

Integral promotion: C does not know how to perform arithmetic on
anything smaller than an int. When you write m_currentState - 1,
the variable m_currentState is automatically promoted to int.
Note that this promotion has converted an unsigned type (byte is
unsigned) into a signed integer. Then, (byte) 0 - 1 is (int) -1
instead of (byte) 255.
Signed division: When dividing a negative number by a positive
one, the quotient is rounded towards zero and, conversely, the rest
is negative. Then, -1 % 8 is -1 instead of 7.

There are several ways around these problems. One is to replace the
modulo operation % 8 by a bitwise and: & 7. This is an optimization
the compiler would have done anyway if dealing with unsigned integers.
The option I prefer is to simply undo the integral promotion by an
explicit cast:
m_currentState = (byte) (m_currentState - 1) % 8;

This way, if m_currentState is zero, (byte) (m_currentState - 1) is
255 and the result is, as expected, 7. Also, the compiler optimizes the
unsigned modulo operation into a bitwise and: the whole lines compiles
very efficiently into just two single-cycle instructions:
subi r24, 0x01  ; subtract 1
andi r24, 0x07  ; bitwise and with 7

It is worth noting that nothing of this would have happened if
m_currentState was an unsigned int, as there would have been no
integral promotion in the first place.


text:
Sparkfun Can-Bus Shield example not working
I recently bought a Sparkfun Can-Bus Shield, and tried the SparkFun_CAN_Demo from here but the program only prints "CAN-Bus Demo" and then does nothing, even when I have it connected into my vehicle's OBD-II port and the key is turned to ON (I can't run the engine because I am in my garage). Any help will be appreciated.

SPI pins are located on different pins in Arduino Mega. You have to wire it correctly with your shield. Some shields uses ICSP (6-pin header) for better compatibility but this one doesn't.
See Arduino SPI Reference for more details (section: Connections)


text:
Precise rotation (steering direction to a given angle) on obstacle avoidance robot
Forgive my lack of knowledge of some robotic related terms, but the way my two wheel drive robot steers is simply by having each wheel move at different speeds; for left, for example, the left wheel moves while the right one stays stationary for a given delay of time and vice versa.
but I want to make my obstacle detection a little more sophisticated with the following logic:
As the robot moves, scan the environment using an ultrasonic sensor(60 degrees to left and 60 degrees to the right) and using a simple max finding algorithm find the optimal angle i.e. angle at which the ultrasonic reading was highest. and then I want to find a way, using the same system of vehicle rotation if possible, turn to that specific angle proceed to move forward and scan simultaneously.
what I aim to achieve in the end is smoother obstacle avoidance as compared to the most common stop when close to obstacle -> turn left or right -> move and loop

The only way you can know how far you have turned, with any form of accuracy and, more importantly, repeatability, is by employing some form of feedback.
In other words, to work out how far you have turned you need, first, to know how far you have turned.
The simplest method is probably to use some form of monitoring on the wheels themselves. That could be an optical encoder to give a nice high resolution "number of degrees the wheel has turned", which can be coupled with the circumference of the wheel to calculate the distance travelled (which can then be used with some simple trigonometry to work out the angle you have turned through) or a more coarse "magnet on the wheel + hall effect sensor" to give you the number of revolutions the wheel has gone through (not very accurate and only really any use at higher speeds when there will be lots of revolutions. Maybe this method would be better on the motor before the gearbox that drives the wheel?)
However, do you really care that much anyway? Are you over thinking things a little too much?
Surely a simpler method would be to first turn left an arbitrary amount (somewhere around 60-degrees-ish, you're not really worried) then sweep from left to right (a distance of somewhere around 120 degrees in total) looking for the furthest distance. Once you have completed your sweep you then just reverse your turn direction until you read the same (or within a certain tolerance) distance at which point you will be facing your longest space.
All that can be done just with spinning the wheels either for a pre-defined period, or until a specific reading has been obtained. No need to worry about precise angles or anything fancy like that.

You could try an electronic compass, such as this one. Use it to compare your current (turn) angle to the desired angle, and keep turning until the desired angle is reached.


text:
ESP8266 Web Server Crash + Arduino IDE
I am working on HTTP GET Request. I have created ESP wifi as web server. It creates a access point with IP address : 192.168.4.1
When my android app is connected to web server, it sends values every 50ms on 192.168.4.1/R"VALUE". Value is integer type (0~1023). Example :- 192.168.4.1/R546
However, it is working fine when I send values every 1s, but esp crashes, when IP is hit every 5ms second. I have captured the crash detail on serial monitor. Attaching the file and code as well. Kindly help.
#include <ESP8266WiFi.h>
#include <EEPROM.h>
#include <ESP8266WebServer.h>

#define RED_LED     12

WiFiServer server(80); //Initialize the server on Port 80

char myTestUrl[100];

void setup()
{

  EEPROM.begin(512);
  Serial.begin(9600); //Start communication between the ESP8266-12E and the monitor window

  WiFi.mode(WIFI_AP); //Our ESP8266-12E is an AccessPoint
  WiFi.softAP("LED_Downlight1", "12345678"); // Provide the (SSID, password); .
  server.begin(); // Start the HTTP Server

  IPAddress HTTPS_ServerIP = WiFi.softAPIP(); // Obtain the IP of the Server
  Serial.print("Server IP is: "); // Print the IP to the monitor window
  Serial.println(HTTPS_ServerIP);
}

void loop()
{
  WiFiClient client = server.available();
  if (!client)
  {
    return;
  }

  String request = client.readStringUntil('\r');
  //Serial.print(request);

  request.toCharArray(myTestUrl, 100);

  char *Red = strstr(myTestUrl, "/R");
  if (Red)
  {
    int RedValue  = atoi(Red + 2);
    analogWrite(RED_LED, RedValue);
    Serial.print("Red: ");
    Serial.print(" ");
    Serial.print(RedValue);
    Serial.print("\n");

    int SetRedValue = (RedValue / 4);
    EEPROM.write(0, SetRedValue);

    EEPROM.commit();

    Serial.print("Red Memory Write :");
    Serial.print(" ");
    Serial.print(SetRedValue);
    Serial.print("\n \n");

  }
}

Exception(29) = A store referenced a page mapped with an attribute that does not permit stores - information from this page - personally I wouldn't be using EEPROM like that

So what is the best way to use EEPROM? How can I improve my code? Any Suggestion or sketch would be useful.

One reason you may get the error is that writing to EEPROM is exceptionally slow (compared to other memory operations) and I wouldn't use EEPROM to store data like that for two reasons. 1) you never read it, so why store it. 2) EEPROM has limited write cycles, write many times a second, you will reach (permanent) failure point sooner rather than later

I've worked with ESP8266 to create a centralized network over which different devices could communicate. In my first iteration I used an ESP8266 as an AP and let other ESP8266s connect to it. This didn't work for longer than 5 minutes. I suspected the ESP8266 couldn't handle many connections for a long period of time and bought an USB WiFi router. Now, I connected all ESP8266 to the WiFi router, including the ESP8266 that I set up as server. And it worked.
In other words: the ESP8266 isn't strong enough to be an AP and communicate a lot of data at the same time. Instead, you'd rather like your ESP connect to an existing wireless network with other devices and let those devices connect to the IP of the ESP.


text:
Programming Arduino With Python
Im a beginner working with arduino.
Im little familliar with java syn and its not hard for me to do the work with ide ;but i know python better....is there any Lib that let you program Arduino with Python?

This page on playground lists a number of links on the subject. As a matter of fact, the first paragraph hints how you may use python on your pc to interact with an arduino over a serial connection.

This has been asked before.

Here is a page on interfacing Arduino with Python.
Interface Arduino with Python


text:
Accelerometer Z Value off a significant amount, all other values reasonable
I'm using the MPU9255 Accelerometer to measure acceleration in the X,Y, and Z directions.  As per the datasheet, I've applied a scaling to the raw digital values based off of whether I specified +- 2G, +- 4G, +- 8G etc.  This scaling works fantastically, but there is consistent noise on the Z axis, far greater than that of gravity's 1G of force.  Here is a sample output
ACCELEROMETER-X
0.7226562500
ACCELEROMETER-Y
0.1523437500
ACCELEROMETER-Z
7.9707031250

ACCELEROMETER-X
0.7460937500
ACCELEROMETER-Y
0.1875000000
ACCELEROMETER-Z
8.0468750000

As you can see, there is about 7G of noise on the Z axis. I calculated the scaling with this code:
//Get accelerometer scaling based off of how many G's per of variation the system was tuned to handle
int16_t getAccScalar(int16_t system_scale){
  int16_t acc_scalar = 16384;
  short scalar = 1;
  if(system_scale == ACC_FULL_SCALE_4_G){
    scalar = 2;
  }
  else if(system_scale == ACC_FULL_SCALE_8_G){
    scalar = 4;
  }
  else{
    scalar = 8;
  }
  acc_scalar /= scalar;
  return acc_scalar;
}

And then in configuration I use a register writing function with this header:
void I2CwriteByte(uint8_t Address, uint8_t Register, uint8_t Data)

and call it with these values
I2CwriteByte(MPU9250_ADDRESS,28,ACC_FULL_SCALE_2_G);

Anyone know why this is happening? Thanks and have a squanchy day.

I suspect are just looking at the 1G from gravity and your scaling is off; What happens when you turn the accelerometer on its side?

When you turn the accelerometer on its side, all the force transfers to the other axis as expected.  But here's the thing, the scaling I'm using is perfect scaling for X and Y, so why is Z so far off? It's the same scaling for all 3 axes.

The accelerometer scaling value was off from the one that I set as the actual scaling, so scaling was indeed the problem. Thanks.

Accelerometer static errors are usually not anywhere near that large, so I suspect your scaling code is not behaving correctly. You could verify this by turning the accelerometer on its side and see if the Z axis retains a +7G value, or if the X/Y axis instead becomes too large.


text:
Using an external interrupt alongside serial
I want to read data from an accelerometer sensor, which pushes its data to the Arduino via an external interrupt. I then want the Arduino to relay this data to a host computer via the serial connection.
Will the external interrupt interfere with the serial connection? If the Arduino's in the middle of transmitting via serial, and the accelerometer triggers the interrupt, won't that potentially break the serial connection?

What do you mean by "break the serial connection" exactly?

Transmitting a single character via UART on the ATmega328P (and all other AVRs with a dedicated USART) cannot be interrupted since it is independently clocked. Loading the next character into the transmit buffer can be (since the INTx interrupts have priority over the USART,xxx interrupts), but this will not actually break communications, just slow it down.


text:
NodeMCU Arduino set PWM Frequency to specific frequency
I am using NodeMCU and I program it using Arduino IDE, I need to change the PWM frequency of a port, in Arduino I used to change the frequency using timers registers like that:
TCCR1B = (TCCR1B & 0xF8) | 1 ;

How can I change the frequency of a digital pin using some function like that:
analogWriteFrequency(pin, 31250);

So that the code will looks like that:
#ifdef __AVR__
TCCR1B = (TCCR1B & 0xF8) | 1 ; //generates the MCKL signal
#else
analogWriteFrequency(pin, 31250);
#endif
analogWrite(pin, 128) ;

Thanks.

PWM frequency is 1kHz by default. Call analogWriteFreq(new_frequency) to change the frequency.

source

Thanks.
but, can I adjust it to a specific pin ?

Probably not. They probably all use the same single PWM generator.

Source link is 404.


text:
Arduino Dim RGB LED
I have an RGB led and I (just) would like to dim is brightness programmatically.
I searched Google thoroughly without any interesting code.
Some of them present only "how to" fade from on to another color.
If I change PWM value from 0 to 255, I can easily change color, but, my need is to change the brightness value from potentiometer (through read from analog pin).

To control the brightness of an LED with a POT read the pot position using the ADC, convert the range of values from 0 - 1024 to 0 - 255 then write that to the PWM controlling the LED.
This segment of code came from this discussion:
void loop()
{
  knobvalue = analogRead(potpin);
  knobvalue = map(knobvalue, 0, 1023, 0, 255);
  analogWrite(11, knobvalue);
}

This is just for 1 LED.  If you have 3 LEDs connected to 3 Arduino PWM pins, you will have to write the same value to all 3 pins.
If this is 1 RGB LED and you are controlling each of the 3 LEDs with 3 Arduino PWM pins, this will (for most RGB LEDs) cause the RGB LED to always appear White as you are varying all colors by the same amount.
If you are trying to vary the brightness of an RGB LED that is set to an arbitrary color...  this is more difficult:
Using 3 variables ranging from 0 to 255 pick your color.  Before writing these to the 3 PWMs which control the RGB LED, multiply each by the value read from the ADC connected to the POT.  Now divide each by the maximum possible ADC value.  Take care you do not exceed the range of your variables!  Write these new values to the 3 PWMs which control the RGB LEDs.


text:
Does anyone have a data sheet for MC16-0072
I can't seem to relibly find data sheets for MCM electronics parts.. Searched for hours.. Any help?

not really an arduino question, could possibly be better served in the electronics stack exchange... But it could be betetr answered if you described the item and packaging and/or a pic

I'm voting to close this question as off-topic because stack exchange is not a human replacement for google when you are not able to get search results.

A quick search gave me the impression that MC16-0072 is actually some sort of rebranding. It seems MCM is not the manufacturer, simply a distributor.
Does the hardware itself have any number or serial printed on it?
In any case, when I dug a bit deeper and found this datasheet. However, without an image of your hardware or its serial number, I cannot confirm the datasheet is for your hardware.


text:
ACS712 Not working correctly with Arduino
So I have the basic setup ready with one relay that is controlling a 200W bulb. The Phase of this bulb is passed through a current sensor acs712. While running a simple analog read example sketch, I get output 511 from ADC, which is as expected. Then I subtracted this 511 from my measurement and observed the results while turning on/off the bulb.
int sensorValue;

void setup()
{
  Serial.begin(9600);  // sets the serial port to 9600
}

void loop()
{
  sensorValue = analogRead(0);       // read analog input pin 0
  Serial.println((511-sensorValue), DEC);  // prints the value read
  delay(100);                        // wait 100ms for next reading
}

Here is the output graph;

While the bulb is off, the current remains 0, but when I turn on the bulb, the voltage fluctuates over positive and negative side. Why is the sensor showing this behavior ?, I am not using any additional capacitor for noise reduction. Do I need to ? but I guess this is not noise. Is it ?

You are seeing that because that is what the current is doing. It's called AC - Alternating Current. It's what the mains current is.
To work with AC you have to rapidly sample over a short period to get the maximum and minimum values. Subtract one from the other and that gives you the peak-to-peak current. You can then use that to calculate the RMS current which is what you are (most likely) interested in.

http://whatis.techtarget.com/definition/root-mean-square-RMS

oh now I got that... Thank you so much :),
got the code from
http://henrysbench.capnfatz.com/henrys-bench/arduino-current-measurements/acs712-arduino-ac-current-tutorial/
and its working now

I'm not sure if that is the case here. Since it's AC the current would also be negative half the time, and we are not seeing this here. The acs712 seems to be made for AC, though I couldn't understand enough of the datasheet to say anything useful.

@Gerben It is negative, but around a 2.5V DC offset. That's the 511 reading  Anum mentions.

Ahhh. Silly me. (-:


text:
Storing an array of function pointers
I have some Arduino code that looks like:
char packet = ser.read();
switch(packet){
    case 'a':
         someobj.somefunc();
         break;
    case 'b':
         otherobj.otherfunc();
         break;
    ...
}

I've added a few large libraries that are now causing my sketch to exceed the Arduino Uno's memory. I've done all the usual tricks to reduce memory usage, like using F(), removing unused variables and functions, but I'm still 5% over the memory limit.
I tried commenting out various parts of my code to see what was taking up so much space, and I found removing this switch statement freed up a whopping 20% of memory.
Since it acts like glorified array index, I was wondering if it could in fact be replaced with an array of function pointers, with the packet variable serving as the array index. e.g.
uint packet = ser.read();
func_array[packet]();

Although the class instance types are arbitrary, the methods all return the same type and take no arguments.
How would you write an array of pointers to arbitrary class instance methods in Arduino C/C++?

Are you talking about flash or RAM? F() helps with RAM, not with flash.

This all gets very much trickier than just an array of function pointers.
Your functions are methods in unknown objects. As such you can't have one single type that stores pointers to the functions in different objects.
The simple reason is that C++ changes the function prototype for you.  For instance, it changes:
class MyClass {
    public:
        int myFunction(int size) { ... }
};

into:
int myFunction(MyClass *this, int size) { ... }

For another class you end up with something like:
int myFunction(MyOtherClass *this, int size) { ... }

And that is a problem, because although you started with functions that, to you, look the same, they are actually very different. So you can't have one function pointer array with one type that can store either.
One possible method is to use polymorphism, where you have one interface class that defines the interface your other classes use:
class MyBaseClass {
    public:
        virtual int myFunction(int size) = 0;
};

class MyClass : public MyBaseClass {
    public:
        int myFunction(int size) { ... }
};

class MyOtherClass : public MyBaseClass {
    public:
        int myFunction(int size) { ... }
};

You can then access myFunction() in either object as if it were in the class MyBaseClass.  Instead of then storing pointers to the functions within the classes you can then store pointers to the classes themselves:
MyBaseClass *classes[2];

classes[0] = (MyBaseClass *)&myClassInstance;
classes[1] = (MyBaseClass *)&myOtherClassInstance;

And then access the functions:
x = classes[i]->myFunction(z);

However, this is all probably very much a moot point.  The switch statement in your code is most likely not what is using all the memory, but all the classes are. By removing the switch you are most likely then not actually doing anything with the classes you have included, and so the linker is then stripping out all that now unreferenced code. A single switch, unless it is an absolutely mammoth bit of code, won't take 20% of the Uno's flash.

Thank you, I had been trying to use a base class, but I wasn't sure of the exact syntax. You nailed it perfectly.

This is not a direct answer to your question, as I have no such answer,
and I believe the answer you are seeking would be of no use to you.
The problem with your question is that your method of testing memory
usage is heavily flawed. By removing the switch statement, you most
likely have allowed the linker to remove lots of methods referenced by
it, leading to huge memory savings. Those savings do not mean the
culprit is the switch statement itself.
The correct way to test static memory usage is to use either
avr-objdump or avr-nm. You have to find where the IDE puts the
compiled elf file, then you can issue the command:
avr-nm --size-sort -Crtd my_program.elf

This will give you a list of all symbols in your program sorted by size.
Symbols of type 't', 'w' and 'd' (upper or lower case) eat flash.
Symbols of type 'd', 'b' and 'v' eat RAM.

You're right, this is arguably really what I'm looking to do. I had Googled for ways to analyse Arduino memory usage but I didn't find anything. I'm glad there's a simple method after all.

I'm not sure if it will not blow your memory limit as every pointer takes up 16 bits. But in C you usually do it this way:
void func1() {
    puts("Hello");
}

void func2() {
    puts("World!");
}

void func3() {
    puts("Array of Size 4");
}

void func4() {
    puts("with Pointer");
}

void func5() {
    puts("to a Function with no arguments");
}

void func6() {
   puts("with return type void");
}

void (* myFunc[6])() = { func1, func2, func3, func4, func5, func6 };

int main(int argc, const char * argv[]) {
    for (int i = 0; i < 6; i++) {
        myFunc[i]();
    }

    return 0;
}

For explanation of
void (* myFunc[6])()

You read form inside to outside looking first to the right then to the left
The variable is named myFunc.
myFunc

My func is an array of size 6.
myFunc[6]

Each of those entries is a Pointer.
* myFunc[6]

Now we need parentheses to make clear, that we have a Pointer to a function with no arguments.
(* myFunc[6])()

And its return type is void.
void (* myFunc[6])()

Hope this helps a bit.

The OP is talking about pointers-to-member-functions - but you've given a VERY good breakdown of pointers-to-functions in general. However, to make it easier do this: declare a typedef as follows: typedef void Fn();. That's a declaration of a type-of function. You can now declare variables of pointers-to-that-type as follows: Fn *fn_p; Which means that you can declare your array (not the OP's array) as Fn *myFunc[6] = { func1, func2, ... }; Neat, huh!


text:
ATMEGA328 SPI MCP2515 - SPI communication freezes at certain point
I got 2 boards with an ATMEGA328 microcontroller and MCP2515 CAN Controller and I'm trying to get them communicate with each other.
To shortcut the programming a little bit I'm using the Sparkfun CAN BUS Library, but I am not using ther CanbusClass(), I'm directly using the included mcp2515.c/h
The MCP2515 drives a MCP2551. CAN_H and CAN_L of both boards are connected with each other, the line has a 120Ohm termination resistor.

Both Microcontrollers share the same code:
#include <mcp2515.h>
#include <global.h>
#include <mcp2515_defs.h>
#include <defaults.h>
#define CANSPEED_125    7
const uint8_t PIN_LED_RED = 6;
const uint8_t PIN_LED_GREEN = 7;

void setup()
{
  Serial.begin(9600);
  pinMode(PIN_LED_GREEN, OUTPUT);
  pinMode(PIN_LED_RED, OUTPUT);
  unsigned long now=micros();
  unsigned long init = 0;
  if(mcp2515_init(CANSPEED_125)) {
    init=micros();
    Serial.println("CAN Init ok");
    digitalWrite(PIN_LED_GREEN, HIGH);
    delay(500);
    digitalWrite(PIN_LED_GREEN, LOW);
  } else {
    init = micros();
    Serial.println("Can't init CAN");
    digitalWrite(PIN_LED_RED, HIGH);
    delay(1000);
    digitalWrite(PIN_LED_RED, LOW);
  }
  Serial.print("Time for init: ");
  Serial.println (init-now);
  delay(1000);
  mcp2515_bit_modify(CANCTRL, (1<<REQOP2)|(1<<REQOP1)|(1<<REQOP0), 0);
  Serial.println("-------------------------");
  Serial.println("1. CAN - MSG1");
  Serial.println("-------------------------");
}

void loop()
{
  tCAN CANmessage;
  unsigned long tnow;
  unsigned long tsend;
  if (Serial.available() > 0) {
    char incomingByte = Serial.read();
    switch (incomingByte) {
        case '1':
            Serial.println("1. CAN - MSG1");
            tsend=micros();
            CANmessage.id = 0x01;
            CANmessage.header.rtr = 0;
            CANmessage.header.length = 8;
            CANmessage.data[0] = B01010101;
            CANmessage.data[1] = B11001100;
            CANmessage.data[2] = B11100011;
            mcp2515_bit_modify(CANCTRL, (1<<REQOP2)|(1<<REQOP1)|(1<<REQOP0), 0);
            mcp2515_send_message(&CANmessage);
            tnow=micros();
            Serial.print("Message send in time: ");
            Serial.println(tnow-tsend);
            break;
    }
  }
  checkCANBus();
}

void checkCANBus() {
  if (mcp2515_check_message()) {
    tCAN CANmessage;
    PORTD ^= _BV(7);
    Serial.println("Has message");
    if (mcp2515_get_message(&CANmessage))
    {
        Serial.print("Message receivced: ");
        Serial.print(CANmessage.id);
        Serial.print(", ");
        Serial.print(CANmessage.data[0], BIN);
        Serial.print(", ");
        Serial.print(CANmessage.data[1], BIN);
        Serial.print(", ");
        Serial.print(CANmessage.data[2], BIN);
        Serial.print("end ");
        if (CANmessage.id==0x01) {
            Serial.println("MSG ID1 received");
            PORTD ^= _BV(6);
        }
    }
  }
}

On Serial port of both boards I get on startup:

CAN Init ok
  Time for init: 250
  1. CAN - MSG1

When I send a byte on the Serial port of one baord ('1') I get on the Serial:

Message send in time: 212

On the receiver side I only get

Has message

and the green LED on PIN7 is turned on (means mcp2515_check_message() returns that the MCP2515 has set the receive interrupt signal).
After that the program crashes in the routine mcp2515_get_message().
By toggling the LED's I figured out that the program crashes directly at the beginning of mcp2515_get_message() in the line mcp2515_read_status(SPI_RX_STATUS);
So the problem lies in mcp2515_read_status().
int8_t mcp2515_get_message(tCAN *message)
{
  // read status
  uint8_t status = mcp2515_read_status(SPI_RX_STATUS);
  ...
  ...
}

uint8_t mcp2515_read_status(uint8_t type)
{
    uint8_t data;
    RESET(MCP2515_CS);
    spi_putc(type);
    data = spi_putc(0xff);
    SET(MCP2515_CS);
    return data;
}

uint8_t spi_putc( uint8_t data )
{
  SPDR = data;
  while( !( SPSR & (1<<SPIF) ) )
    ;
  return SPDR;
}

By further toggling I figured that the last line correctly executed is spi_putc(type);
The line data = spi_putc(0xff); freezes the microcontoller! Which means the while loop in spi_putc() is endless running as the SPIF bit is not cleared.
Here is what I think I figured out so far:

The SPI bus connection is clearly working as the initialization is working!
As the mcp2515_check_message() returns on the receiver board that MCP2515_INT is set so I assume the CAN communication is working (otherwise, why would controller set the MCP2515_INT).

SPI_RX_STATUS is defined as 0xB0(original as in library).
The Datasheet of the MCP2515 controller states on page 66

The RX STATUS instruction (Figure 12-9) is used to
  quickly determine which filter matched the message
  and message type (standard, extended, remote). After
  the command byte is sent, the controller will return
  8 bits of data that contain the status data. If more clocks
  are sent after the eight bits are transmitted, the
  controller will continue to output the same status bits as
  long as the CS pin stays low and clocks are provided.

Which it clearly doesn't! But what I cant figure out is why :)

I would be tempted to find out why you only get 'Has message' which implies that if (omcp2515_get_message(&CANmessage)) is returning zero.

The code shows omcp2515... and mcp2515... functions. What's that about?

@PeterSmith thats not the case. The program freezes in that call of mcp2515_get_message(&CANmessage).

@JimmyB, thats just a copy of the function I used to toggle the LED. I didnt want to mess with the original code in the library. I edited the question!

Just try another library, like this one: https://github.com/Seeed-Studio/CAN_BUS_Shield just be careful as this library does not implement atomic SPI transaction.

There is one huge pitfall in Master Mode in this ATMega - Select Slave pin (/SS - active low). If it's configured as input, SPI is switched to Slave Mode by low level on this pin. And /SS is on pin PB2 (used as CAN_INT).
In the library defaults I can see: #define    MCP2515_INT D,2. PD2 is also INT0 external interrupt pin, so it does make sense to be here and it can be used with attachInterrupt. PB2 is used as an output for selecting slave device, so it's ok too.
Schematics corresponds with that defaults:

In OPs schematics there are slight changes. Interrupt request CAN_INT is located on /SS pin (PB2, arduino pin 10). CAN_CS was moved from PB2 to PB1 (arduino pin 10 -> pin 9)
And in Mega328 datasheet is section: 19.2 SS Pin Functionality:

19.3.2 Master Mode
  When the SPI is configured as a Master (MSTR in SPCR is set), the user can determine the direction of the /SS
  pin.
  If /SS is configured as an output, the pin is a general output pin which does not affect the SPI system. Typically,
  the pin will be driving the SS pin of the SPI Slave.
If /SS is configured as an input, it must be held high to ensure Master SPI operation. If the /SS pin is driven low by
  peripheral circuitry when the SPI is configured as a Master with the /SS pin defined as an input, the SPI system
  interprets this as another master selecting the SPI as a slave and starting to send data to it. To avoid bus
  contention, the SPI system takes the following actions:
  1. The MSTR bit in SPCR is cleared and the SPI system becomes a Slave. As a result of the SPI becoming a Slave, the MOSI and SCK pins become inputs.
  2. The SPIF Flag in SPSR is set, and if the SPI interrupt is enabled, and the I-bit in SREG is set, the interrupt
  routine will be executed.
  Thus, when interrupt-driven SPI transmission is used in Master mode, and there exists a possibility that SS is
  driven low, the interrupt should always check that the MSTR bit is still set. If the MSTR bit has been cleared by
  a slave select, it must be set by the user to re-enable SPI Master mode.

Conclusion: If you are using HW SPI in master mode, you can't just use pin 10 (PB2) as general input.

Could you possibly clarify this answer more, it is really vague and short. Also the connections of the OP's circuit is basically the same as the schematic from Sparkfuns shield

I think you are on the right track. Dont know, why I missed that in the datasheet... Let me quickly cut the track of PB2 and connect a botch wire to PB0 to test it.
Btw. if I understand it correct, actually I would only need to change CAN_CS (which is an output) with CAN_INT (which is an input) in my final layout and everything should be ok, right?

Yes, you can switch these signals. But if you dont use D10, it must be set eiter as output (and used for another signal) or input pullup (and left unconnected). However i'd recommend to use PD2 (INT0) or PD3 (INT1).

Just tested it and it works! Thank you very much for helping me out! Finding this cost me days :)

So what is the conclusion? What should be done? Can you make it clear (by editing your answer)?

Turns out this applies for other Atmel products, including the ATiny1627, too.  Very useful answer!

@hegel5000 However in the ATtiny1617 you can disable this functionality and use SS pin as IO: "If SSD in SPIn.CTRLB is ‘1’, the SPI does not use the SS pin, and it can be used as a regular I/O pin, or by other peripheral modules.". This is not possible in the older AVRs

@KIIV well, not general I/O.  If you leave the SS pin as input, even with SPIO.CTRLB = SPI_SSD_bm, SPI can still hang!  But it seems to work fine as output; no need to pull high.  (Or I'm getting (un)lucky.  Whether it hangs due to SS is somewhat random.)

@hegel5000 Right, at least Atmega4809 has this mentioned in Errata document - even if you configure it, it won't disable it