text:
very lightweight low power microcontroller with memory?
I have build a couple of projects using arduino.  For a new project I want to log skin surface temperature vs. time (just perhaps a few times per day) and possibly other easy to obtain info such as voltage.
I need to make everything as small and lightweight as possible (since it would be measuring skin temperature on a small mammal), i.e. below 5g, lighter if possible, ideally 3g, including the battery, so that it doesn't upset the 50-100g animal too much.
I read it might be possible to change the arduino pro mini to use less current by getting rid of the voltage regulator? but perhaps it is more sensible to change completely and learn to program another type of microcontroller which someone could recommend? It would need to be possible to operate it directly from a lightweight coin cell or similar lightweight battery. (I'm also not sure how to find a lightweight 3.3V battery for the arduino pro mini, I guess they exist but I can only find 3V batteries so far). If it has onboard memory to save temperature every few hours which could be downloaded later that would be ideal (I would also be interested if anyone has recommendations for memory). I know it's possible to buy an "Ibutton" but if I have time I would like to make my own so that I can add other sensors and obtain more information.

...sorry, my actual question is: Could someone recommend a suitable low powered lightweight microcontroller, or do you think I should continue with arduino and try to adapt it?  Any help is really appreciated!

You could use an ATmega328 at 8MHz, powered with two 1.5V batteries in series. You could then continue using Arduino libraries and IDE.

@jfpoilpret, 2AA would be too heavy I think. A 2032 3V coin cell could be better.

Depending on how you program it, an ATmega328 or an ATtiny84 or 85 might have very light current consumption and work with a lithium CR2032 cell for quite some time. However, reducing power consumption of a circuit (ATmel or any other) can become rather tricky.

I made up a small torch locator which used an ATtiny85 powered from a button-cell (CR2032). It looks like this:

Other side:

That currently weighs 5.9g. The battery-holder weighs 1.6g so you could save that by making a more light-weight holder (perhaps a bit of plastic for insulation, and soldering directly to the battery). The chip socket weighs at least 0.5g, so you could save that as well by soldering to the processor pins. So we are down to 3.8g.
The ATtiny85 has 512 bytes of EEPROM which you could use to log readings to. I'm not sure about a clock if you are trying to save weight, but if you start it at a known time, you could have a reasonable estimate of the time by using the millis() function to find miliiseconds since startup.
I made another one a while ago which flashes an LED every couple of seconds:

That is similar. The processor is there (upside down under the chip socket) and the battery is underneath. That weighs 6g. The battery has lasted a couple of years, and that is flashing an LED every couple of seconds!
Instead of the LED you could have a thermistor to read the temperature.
You could program it to take a reading every few hours and save it to EEPROM. Then when instructed (eg. by joining a couple of pins) it could output the readings to another pin (via serial).
You could save more weight by using SMD (surface mounted) devices, and perhaps using a tiny circuit board you could get made up.

Code
The code for my torch locator is below. Of interest is the fact that it sleeps most of the time. Also it sleeps during the ADC sampling. Although in my case I am measuring a LDR (light dependent resistor) the code for measuring a thermistor would be similar. You just need to do some calculations at the end to turn the reading into a temperature.
// ATtiny85 torch detector
// Author: Nick Gammon
// Date: 25 February 2015

// ATMEL ATTINY 25/45/85 / ARDUINO
// Pin 1 is /RESET
//
//                  +-\/-+
// Ain0 (D 5) PB5  1|    |8  Vcc
// Ain3 (D 3) PB3  2|    |7  PB2 (D 2) Ain1
// Ain2 (D 4) PB4  3|    |6  PB1 (D 1) pwm1
//            GND  4|    |5  PB0 (D 0) pwm0
//                  +----+

/*

  Pin 2 (PB3) <-- LDR (GL5539) --> Pin 7 (PB2) <----> 56 k <----> Gnd

  Pin 5 (PB0) <---- LED ---> 100 R <-----> Gnd

*/

#include <avr/sleep.h>    // Sleep Modes
#include <avr/power.h>    // Power management
#include <avr/wdt.h>      // Watchdog timer

const byte LED = 0;          // pin 5
const byte LDR_ENABLE = 3;   // pin 2
const byte LDR_READ = 1;     // Ain1 (PB2) pin 7
const int LIGHT_THRESHOLD = 200;  // Flash LED when darker than this

 // when ADC completed, take an interrupt
EMPTY_INTERRUPT (ADC_vect);

// Take an ADC reading in sleep mode (ADC)
float getReading (byte port)
  {
  power_adc_enable() ;
  ADCSRA = bit (ADEN) | bit (ADIF);  // enable ADC, turn off any pending interrupt

  // set a2d prescale factor to 128
  // 8 MHz / 128 = 62.5 KHz, inside the desired 50-200 KHz range.

  ADCSRA |= bit (ADPS0) | bit (ADPS1) | bit (ADPS2);

  if (port >= A0)
    port -= A0;

#if defined(__AVR_ATtiny85__)
  ADMUX = (port & 0x07);  // AVcc
#else
  ADMUX = bit (REFS0) | (port & 0x07);  // AVcc
#endif

  noInterrupts ();
  set_sleep_mode (SLEEP_MODE_ADC);    // sleep during sample
  sleep_enable();

  // start the conversion
  ADCSRA |= bit (ADSC) | bit (ADIE);
  interrupts ();
  sleep_cpu ();
  sleep_disable ();

  // reading should be done, but better make sure
  // maybe the timer interrupt fired

  // ADSC is cleared when the conversion finishes
  while (bit_is_set (ADCSRA, ADSC))
    { }

  byte low  = ADCL;
  byte high = ADCH;

  ADCSRA = 0;  // disable ADC
  power_adc_disable();

  return (high << 8) | low;

  }  // end of getReading

// watchdog interrupt
ISR (WDT_vect)
{
   wdt_disable();  // disable watchdog
}  // end of WDT_vect

#if defined(__AVR_ATtiny85__)
  #define watchdogRegister WDTCR
#else
  #define watchdogRegister WDTCSR
#endif

void setup ()
  {
  wdt_reset();
  pinMode (LED, OUTPUT);
  pinMode (LDR_ENABLE, OUTPUT);
  ADCSRA = 0;            // turn off ADC
  power_all_disable ();  // power off ADC, Timer 0 and 1, serial interface
  }  // end of setup

void loop ()
  {
  // power up the LDR, take a reading
  digitalWrite (LDR_ENABLE, HIGH);
  int value = getReading (LDR_READ);
  // power off the LDR
  digitalWrite (LDR_ENABLE, LOW);

  // if it's dark, flash the LED for 2 mS
  if (value < LIGHT_THRESHOLD)
    {
    power_timer0_enable ();
    delay (1);  // let timer reach a known point
    digitalWrite (LED, HIGH);
    delay (2);
    digitalWrite (LED, LOW);
    power_timer0_disable ();
    }

  goToSleep ();
  }  // end of loop

void goToSleep ()
  {
  set_sleep_mode (SLEEP_MODE_PWR_DOWN);
  noInterrupts ();       // timed sequence coming up

  // pat the dog
  wdt_reset();

  // clear various "reset" flags
  MCUSR = 0;
  // allow changes, disable reset, clear existing interrupt
  watchdogRegister = bit (WDCE) | bit (WDE) | bit (WDIF);
  // set interrupt mode and an interval (WDE must be changed from 1 to 0 here)
  watchdogRegister = bit (WDIE) | bit (WDP2) | bit (WDP1) | bit (WDP0);    // set WDIE, and 2 seconds delay

  sleep_enable ();       // ready to sleep
  interrupts ();         // interrupts are required now
  sleep_cpu ();          // sleep
  sleep_disable ();      // precaution
  }  // end of goToSleep

for your flashing led "thing", wouldn't it be better to use a 555 timer chip? I find using an ATtiny somewhat of a waste.

I was going for low power consumption. The processor sleeps most of the time, and then flashes the LED for a millisecond or so.

thanks! looks possible to use this, will have a go at learning how to set up and program it.

Re “Instead of the LED you could have a thermistor to read the temperature”, one could instead read ADC channel 15, the on-board temperature sensor.  [However it isn't highly sensitive or accurate.]

Your torch finder is a wonderful piece of design and the power consumption estimation you did is very much in the spirit of the "engineer as much as you need to" spirit of Ardunio. The whole thing warmed the cockles of my heart (wherever those are).

Thanks! That's very kind of you. :) It's still working by the way. I look at it in the evenings wondering when it will fail.

I would personnaly suggest an ATtiny 45/85. It is pretty much a small AVR with 5 GPIOs. You can program it with the Arduino IDE and use the Arduino as ISP. If you can design you own custom PCB, a SMD version of the ATtiny is small, low and compact. The total circuit to make the ATtiny function is also minimal.

Also, at a low clock speed (0-4MHz), you can power the ATtiny at a voltage as low as 1.8V. You could probably even run it at 1.5V, but this is not totally recommended. If you want to be safe, a 3V coin cell will be small, flat, and it can last probably many years. It is also a little safer compared to lipos which have many risk, especially if you mount it on an animal that you can't really control.

I would also recommend SMD components if possible. It lets all the component be lower and it doesn't hurt or sratch the skin of the person/animal you are monitoring.

Looks like we both had the same idea!

thanks!! this looks great,  really appreciate the help!  I will try to learn the basics of how to set up the microcontroller etc. from the first circuit and once I get it working will probably change to SMD components as you suggested.  I think realistically I will need to do that to make it small enough.


text:
Which pins of an Arduino UNO can be used as Tx and Rx pins for connecting to GSM GPRS SIM 900A
I am using Arduino UNO and SIM 900A. Pins 0 and 1 are used as TX and RX. Is it possible to use any other pins?

SoftwareSerial... Google GSM shield and Arduino, how then did you have the SIM module working in your other question?

The best choice for serial communications is obviously the HardwareSerial object, Serial, on pins 0 & 1.  However, it is really dedicated to the USB connection (via the onboard Serial-to-USB adapter).  There are ways to connect other devices to these pins, but it is an advanced topic, and should not be attempted by beginners.
The second best choice would be pins 8 & 9, because AltSoftSerial requires those pins.  It is very efficient and reliable.
After that, any other pins can be used with one of these two software serial libraries:
NeoSWSerial is less efficient than AltSoftSerial, but much more efficient than SoftwareSerial.  It only supports baud rates 9600, 19200 and 38400, but it does support simultaneous TX and RX.  I maintain this library.
If you must use a different baud rate, SoftwareSerial is the last choice.  It blocks interrupts for long periods of time and can interfere with other libraries.  It cannot transmit and receive at the same time.

source: Stack Exchange

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

sort: votes


text:
TCP connection CPU usage, multiple signals?
I'm connecting a client (java program) to an arduino (server). What I want to know is, how high the CPU usage is, and what to do if there are no clients that are trying to connect to arduino? Should I make a delay?
My code looks like this:
EthernetClient client = server.available();

if(client){
    Serial.println("Connected");
    server.write("Hello\n");

    //check if client is still connected
    while (client.connected()){
        Serial.println("Still there");
        delay(2000);
       //check if client received any data
       if(client.available()){
           //read message from client
     }
  }
} else {
     Serial.println("Nope");
     server.write("Hello\n");
     ???????????? delay(2000); ??????????????
}

Thank you for your help.

You don't need to do anything. If the else clause has a delay (e.g. of 2 seconds), then it will take up to that long before the arduino accepts the connection.
The "server.write" in the "else" clause doesn't make any sense - who are you sendin it to? server.write will normally write to all available connections.
If there's nothing else you want to do, you might as well retry straight away.
Note that, if you are doing a serial.println statement, and you have no delay, then, while waiting for a connection, it will print the "Nope" message, as fast as it can.

Thank you for your answer! Oh okay, I understand, I'm quite new at arduino and connections, and I know that my code is nonsense :) so I just put a delay before that "Nope" and it will connect before throwing that "Nope"? And few more things: Is there a way to send a String to arduino (server) over TCP conection in one piece? I'm currently receiving byte by byte. Thank you for your time!

Does it make sense to print "Nope" every two seconds that you don't get a connection? For testing purposes, it may be entirely acceptable to do so, in which case a 2 second delay establishing a connection may also be ok. Yes, you should be able to send a string to an arduino in one piece (up to about 1kb); if it's giving it back one character at a time, it's likely an issue in your code - I suggest you post this as a separate question, as it's quite a different question from this one. Include both the sending and receiving code.

Normally, I would not have an "else" clause in code like this - if there is no incoming connection, there is nothing to be done (unless debugging). Just let it go around the loop again, as fast as it can.

So it has to loop over server.available() as fast as it can? Okay I'll ask another question.

Oh one more thing.. while client.connected() will return true for ever once it connects right?

client.connected() will return until one side or the other disconnects. Since there is no code in your snippet showing that the Arduino disconnects, it will keep returning true until the client disconnects. If you use the windows or linux 'telnet' command for testing, to disconnect, control-], press , then q

It doesn't have to do it as fast as it can - if there are other things you need to do in your code, you can easily do it between loops. However, there is no point in delay()ing it.

I have Java program (I asked another question as you said): http://arduino.stackexchange.com/questions/18137/sending-data-over-tcp-connection-in-one-piece So it will return true until my close() function?

As the Arduino typically has no demand-based clock scaling, or alternate threads of comparable priority you can schedule, there's really little point in using a delay (which is implemented as a busy-wait) rather than a tight loop - really, the primary appropriate reason would be to reduce the frequency of status output.
However, if you want to design a power-efficient system, you could consider sleeping the CPU between checking if there is anything worthwhile to do, or until an interrupt indicates that there is.  This is not something which delay() will take care of for you, so it is a fair amount of extra work and testing to get right, but it can be very worthwhile if running from batteries.
If your application is not particularly intensive you can also configure the clock divider fuse and slow the chip down generally.

Thank you for your answer! I'm not worried about power consumption, I'm more worried about overheating. This arduino will handle quite few thing (quite important too) and I don't want any problems.
Few more things: Is there a way to send a string over TCP connection in one piece? I'm currently reading byte by byte, but it would be great if there is any other more efficient way.
Oh and about TCP connection. Java program will have proper GUI and I want to know how to check if there is no connection? Try/Catch block, and program the catch block so it tells the user?
Thank you for your time!

Overheating and power consumption are very nearly two sides of the same coin, as it is power consumption which creates heat.  Effectively an ATmega won't get substantially busier than it already is running a typical busy-wait type of sketch as it typically does.  And unless you have other sources of heat, or very atypical thermal insulation of the package, that shouldn't be a problem.  Your regulator may produce some heat in normal operation though.  As for your other questions, SO rules are one question per post.

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


text:
Pressure Gauge analog reading via RS232
I am trying to read the analog signal from a Pfeiffer TPG 261 Single Gauge (https://www.idealvac.com/files/brochures/Pfeiffer_Single_Gauge_TPG261.pdf)
The pin assignment of the connector I am using is the following:

Here is the circuit I have built:

And here is the code used:
int pressureSensorPin = A0;

int analogValueP = 0;

void setup(void)
{
  Serial.begin(9600);
}
void loop()
{
  analogValueP = analogRead(pressureSensorPin);
  Serial.println(analogValueP);
  delay(1000);
}

Unfortunately the ouput I get with such a build is only 0 with now and then a 1023.
Any idea of what I am doing wrong ?

The Arduino has 5 V TTL Serial. the connector is RS232, possibly +/-12 V. You need a converter. The value read on RS232 would be data to read with Serial.read(), not an analog signal

You have a misconception, which signals get's outputted where. If you want to simply read the analog signal of the sensor, you need to use the "control" connector. There you can find the analog signal on pin 2. But this analog signal goes up to 10V, so you need a voltage divider between the sensor and the Arduino, to divide the voltage down to 5V max.
Currently you are using the RS232 connector. RS232 is a communication standard, which transmits digital data, not analog data. Thus you read only digital values (min voltage and max voltage, nothing inbetween). You can use it do talk with the sensor, change configuration settings and reading data digitally. But to actually do this, you need to consider 2 important things:

RS232 is an interface, which involves it's own voltage levels (namely +-12V), which do not fit the TTL level (0 - 5V) that the Arduino Uno uses. You can very well destroy your Arduino by connecting it directly to RS232. For making this work, you need a level converter chip (I think the MAX232 is commonly used for this), to convert the voltage levels to TTL logic. From there on this communication is normally called UART.
You need to understand and then implement the sensors communication protocol (when to send what data), so that the sensor and Arduino are understanding each other

For me it seems, that the analog signal from the "control" connector is all, that you currently need, so for simplicity you can use this. RS232 is used for more control over the functionality of the sensor.

Even the analog signal from the control connector supplies a voltage range of 0 .. 10V, which requires some treatment (voltage divider) and is not directly applicable to an Arduino.

You are correct, I will add this to the answer

Thanks for all the information, yes I did have a major misconception, I understand better now. So if I wanted to access the digital output something like this could work : https://www.conrad.de/de/p/entwicklungsboard-mikroelektronika-mikroe-222-1221401.html ?

Yes, that would work

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


text:
ISR for very fast processes, strange code found. Has ISR effect on timer behaviour?
I found the following code within an example for performing very fast changes on a PWM-output. It works, however I'm wondering about some details.
TIMER2 was set up in setup() as follows:
TCCR2A = 0;               // We need no options in control register A
TCCR2B = (1 << CS21);     // Set prescaller to divide by 8
TIMSK2 = (1 << OCIE2A);   // Set timer to call ISR when TCNT2 = OCRA2
OCR2A = 32;               // sets the frequency of the generated wave
sei();                    // Enable interrupts to generate waveform!

If I understand that correctly, the timer will run until overflow and generate interrupts any time in between as defined by OCR2A.
ISR(TIMER2_COMPA_vect) {  // Called each time TCNT2 == OCR2A
  static byte index=0;    // Points to successive entries in the wavetable
  OCR1AL = wave[index++]; // Update the PWM output
  asm("NOP;NOP");         // Fine tuning
  TCNT2 = 6;              // Timing to compensate for time spent in ISR
}

TIMER2 is used to call this routine in equidistant points in time.
To adapt the timespan between two calls of the ISR the author sets OCR2A and within the ISR resets TCNT2. As the timer is reset at the end of the ISR there's some time "already gone" written into the start value of the timer. However there are two things I don't understand.

Why isn't CTC mode used by setting WGM21 in TCCR2A? This should call the ISR in precise intervals.

If not using CTC mode the counter has to be reset by the ISR. But why isn't that done directly at the beginning of the ISR? Everytime the ISR gets some minor changes the correction value written into TCNT2 has to be changed.

Am I missing some vital detail? Or is my idea of using CTC better?
For sake of completeness, the only other things done in setup() are configurations on timer1:
pinMode(9, OUTPUT);       // Make timer's PWM pin an output
TCCR1B  = (1 << CS10);    // Set prescaler to full 16MHz
TCCR1A |= (1 << COM1A1);  // PWM pin to go low when TCNT1=OCR1A
TCCR1A |= (1 << WGM10);   // Put timer into 8-bit fast PWM mode
TCCR1B |= (1 << WGM12);

loop() is empty.

Mhh, not using CTC in such a case doesn't make much sense to me either. Especially since the timer does not stop when the compare ISR is called. It will keep running just fine while the ISR is working (since the Timer works in hardware). I would guess that this is just a bad code

Why isn't CTC mode used by setting WGM21 in TCCR2A?

As we cannot read the author's mind, we cannot say for sure. That being
said, to me, the most likely reason is that either the author was not
aware of CTC mode, or they just didn't think about it.
You are right that CTC is the most straightforward way to get precise
intervals. You are also right that the resetting the timer at the end of
the ISR makes the code somewhat fragile. If, for some reason, I needed
to avoid CTC in a code like this, I would
OCR2A += 32;

rather than resetting TCNT2.

I tend to think, the author did not know the CTC mode well enough. Otherwise I cannot explain the solution proposed. I was just stunned because it was published in a magazine. https://makezine.com/projects/advanced-arduino-sound-synthesis/  Not that I think this is a guarantee for quality but who knows...

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


text:
Data from PROGMEM array mismatches initialisation
The amount of memory needed for my user interface is outrageous. Hence I decided to use flash memory. But after some successful readouts from program space, problems emerge.
Updated:
I have some sort of initialisation files to collect all global arrays which go into flash like this: (intitialisation.cpp)
#ifndef INITIALISATIONDEF
#define INITIALISATIONDEF

#include "initialisation.h" //which includes Arduino libraries and "globals.h"

const uint8_t gl_PsNMenuType[MAXMENUS] PROGMEM = { 0, 0, 0, 0, 0};  // this is, what I intend to read out later.
const uint8_t gl_PsNMenuParent[MAXMENUS] PROGMEM = { MAXMENUS, 0, 0, 0, 0};
const uint8_t gl_PsNMenuFixTexts[MAXMENUS][MAXFIXTEXTSPM] PROGMEM = {
  { 20, 2, MFTS, MFTS, MFTS}, // 0
  {2, 9, 1, MFTS, MFTS}, // 1
  {2, 10, MFTS, MFTS}, //2
  {2, 11, MFTS}, //3
  {2, 12, MFTS} //4

};
#endif

Updated:
while I propagate all global vars via another header (globals.h):
#ifndef GLOBALS
#define GLOBALS
#define SDTXT

#define MAXMENUS 80
#define MAXFIXTEXTSPM 5

#include "initialisation.h"
extern const uint8_t gl_PsNMenuType[MAXMENUS];
extern const uint8_t gl_PsNMenuParent[MAXMENUS];  // referenz auf den übergeordneten MP
extern const uint8_t gl_PsNMenuFixTexts[MAXMENUS][MAXFIXTEXTSPM];  // Liste der festen Menütexte zu jedem MP
#endif

as one can see, I do not initialise my arrays fully, as I'm in a development phase, but the first bytes should be zeroed out correctly AFAIK.
But, when accessing my stored values later in a third file: (uimenu.cpp)
#include "uimenu.h" // which includes globals.h and initialisation.h

// somewhere in the code inside a function, with uint8_t mp=0:
Serial.print(pgm_read_byte(gl_PsNMenuType[mp]));

The last line should print 0, as stated in initialisation, but it prints 12.
So, I think, I'm doing sth. substantially wrong here, but have no clue at the moment. I have several guesses:

I should not use const with PROGMEM. I did this to be informed by the compiler, if I accidentally write to an array stored in flash.
I made some mess with #includes, perhaps with order of occurrence. At the moment I try to sort the order out.
There's something with having global variables or arrays defined and declared in a header and accessed in another source files function. But I cannot imagene, what.
Updated: something wrong with my indices for my arrays? is uint8_t insufficient?

If you need more information or code, I'll edit my question accordingly. Thanks in advance! I appreciate any help.
(all files were edited for brevity before posting them)
Update:
I moved the definitions of the progmem arrays to the source file and all macro constants (#define) to globals.h. The outcome is: different numbers are printed, but they are wrong whatsoever. I poked elsewhere into the progmem array and got other wrong numbers.

Did you try declaring them as PROGMEM in your header so that other code units know how to use them?

The correct way to use pgm_read_xxx is pgm_read_byte(gl_PsNMenuType + mp).

@Gerben: ... or pgm_read_byte(&gl_PsNMenuType[mp]) and mainly switch on warnings. This kind of error should be caught by gcc warnings.

@IgnacioVazquez-Abrams I guess I brought some confusion into this matter by not posting my updates in a new section but changing the code. Actually the first thing I tried was to qefine and initialise it in header file. But I still have a extern declaration in "global.h" which is included by all other headers in my project. IMHO the declaration with extern should suffice for other code to make it linkable, shouldn't it? But I think I have to check gerben's comment as soon as I'm back at the hardware again.

@TMa: seems to work! I totally missed the necessity of referencing the array element. Thanks a lot. But I did not get any compiler warnings without the reference operator. Why isn't this call typesafe?

@TMa: seems to work! I totally missed the necessity of referencing the array element. Thanks a lot. But I did not get any compiler warnings without the reference operator. Why isn't this call type-safe?

The PROGMEM word is an attribute, not a type. It might be type-safe but not attribute-safe (if there is such a thing). See Data in Program Space

Reference
Putting constant data into program memory (PROGMEM)


text:
MCP23S17 library crashes
I have a rather voluminous sketch with a heap of source and header files.
Now I'm facing the problem, that controlling the MCP23S17 on my board fails in different ways within this sketch. This is rather awkward, because when I modify the sample sketch taken from this library to my needs, the port expander can be accessed and controlled without any problem.
what happens within my own sketch?
If I initialise SPI myself before using any of the library methods, everything of my sketch and hardware but the port expander works flawlessly. I.e. all hardware does what it is intended to, only the pins of the port expander do nothing.
If I remove all SPI commands I inserted there to initialise SPI according to my needs, the code will fail during the first call to MCP23S17::pinMode(…).
Fail means: The CPU crashes. It hangs inside this routine and keepalive-LED stops blinking, serial output is severed. As I don't have any means of debugging besides Serial.print(), I narrowed it down to the call of
_spi->transfer(cmd);

within
void MCP23S17::writeRegister(uint8_t addr)

So something from my other code must interfer with this call, somehow, so the CPU comes to a halt. What the heck do I have to look for?
Additional information:

Portexpander chip select is tied to Pin 7 of Arduino Uno.
Portexpander address i 0
Other device connected to SPI: display
Other notable devices: RTC (on I2C), lot of 1-wire devices.

Addendum
following Majenko's suggestions, I reduced my code to reach functionality in this issue. I did not succeed. So I decided to post two antagonistic sketches, one crashing and one working.
Spoiler: I found my coding flaw myself five minutes ago, I'm going to post it as answer later, but decided to go on writing this addendum as I had intended
Here comes the .ino-file of the failed sketch:
#include <SPI.h>
#include <MCP23S17.h>
#include "spin.h"

void setup() {
    Serial.begin(9600);
    Actors::setup();
    Serial.println("setup finished");
}

void loop() {
    Actors::service();
}

part of this are two further files, from which I removed everything possible:
spin.h:
#ifndef _INC_SPIN
#define _INC_SPIN

#include <MCP23S17.h>

class Actors
{
    private:
    static const uint8_t PexSSPin;
    protected:
    static MCP23S17 portExp;

    public:
    static void setup();
    static void service();

};
#endif

and spin.cpp:
#include "spin.h"

const uint8_t Actors::PexSSPin=7;
MCP23S17 Actors::portExp(&SPI, Actors::PexSSPin, 0);

void Actors::setup()
{
    Serial.print(F("Ac:se#"));
    Serial.print(".");
    portExp.pinMode(2, INPUT);  // not used. INPUT mode prevents damage due to accidental shorting
    Serial.print(".");
    portExp.pinMode(3, INPUT);  // not used. INPUT mode prevents damago due to accidental shorting
    Serial.print(".");

    Serial.print(F("Ac:se!"));
}

void Actors::service()
{
    Serial.print(F("Ac:sv#"));
    Serial.print(F("Ac:sv!"));
}

As noted in my first part of the question this code comes to a halt during the first call to the pinMode() method of the portexpander. There's no serial output after the first pinMode call and the actors weren't working either (when there was useful code left).
On the contrary here comes a working sketch with the same library controlling the same port expander on the same hardware.
#include <MCP23S17.h>
#include <Arduino.h>

#ifdef __PIC32MX__
// chipKIT uses the DSPI library instead of the SPI library as it's better
#include <DSPI.h>
DSPI0 SPI;
#else
// Everytying else uses the SPI library
#include <SPI.h>

#endif

const uint8_t chipSelect = 7;

MCP23S17 Bank1(&SPI, chipSelect, 0);
uint16_t data;

void setup() {
    Serial.begin(9600);
    Bank1.begin();
    Bank1.pinMode(8, OUTPUT);
    Bank1.pinMode(9, OUTPUT);
    Bank1.pinMode(10, OUTPUT);
    Bank1.pinMode(11, OUTPUT);
    Bank1.pinMode(12, OUTPUT);
    Bank1.pinMode(13, OUTPUT);
    Bank1.pinMode(14, OUTPUT);
    Bank1.pinMode(15, OUTPUT);

    // Bank2.pinMode(15, INPUT_PULLUP);
}

void loop() {
    if (data==0)
    {
        data = 0xffff;
    }
    else
    {
        data = 0x0000;
    }
        Bank1.writePort(data);
    delay(2000);
    Serial.println(data);
}

I take it since you're wanting my response it's my library you are using?

Do you have anything connected to pin D10? If so, what, and what mode are you using the pin in?

@Majenko yes your library. pin D10 is connected to the CS of the display. And according to the display library it is used in output mode.

It sounds like some form of conflict, certainly. If _spi->transfer() is hanging then it's most likely that the SPI transaction is never completing, which is something in the SPI library. It may be that your display library is doing things that affect the SPI library in some way.

I would suggest starting with working expander code, then add each extra item until it fails. Then remove everything except the expander and whatever was last added and see if it still fails. If it does then post that code so we can find the conflict.

Ok, I'm going to check that out, by removing everything, first of all all includes to the display library. The library I'm using is DOGM_7036.

I'd love to know, why my question is a bad question...

Since you have answered the question yourself you should accept the answer as the correct answer.

So here is what I found five minutes ago.
I forgot to call MCP23S17::begin()
Simple that is.
Before that, I tried to rule out a whole lot of other things. It never came to my mind, that I could have missed such a vital initalisation.
What did I do to get to this point?

removed every other library using SPI
removed every code using I2C
removed every code using 1wire
removed every code using Interrupts
threw away 9 out of 10 files
removed 9 out of 10 calls for functions which seemed irrelevant for this problem.

None of these measures did anything to solve the problem. Only when I had my code reduced to the minimum, so I could dare to post it here, the single line caught my attention. So this Q&A is not really a technical or coding riddle but more a didactic play on how one can fool himself and what to do to locate errors.
But in the end I only found the culprit by strictly following Majenko's advice to remove everything until the code started to work again.


text:
Display unresponsive in one sketch, while working in another
I'm using a DOGM163 Display. It works in a DEMO sketch provided by the manufacturer but not in my sketch. This is strange, because I am using the same library specific commands as in the example.
I think of the following possibilities:

Something inside the other libraries I use in my sketch is hindering the dogm from working (perhaps by fiddling around with the ports connected to the display).
I've got a power problem which surfaces when doing more than just that demo.
Timing is botched.
Something with my wiring is wrong. Perhaps in conjunction with 1).

I'm using:
#include <Arduino.h>
#include "newsched.h"
#include "dplan.h"
#include <EEPROM.h>
#include <PinChangeInt.h>
#include <dogm_7036.h>
#include <SPI.h>
#include <OneWire.h>
#include "lampcontrol.h"

Power seems to be ok, as I'm receiving all debug messages via serial correctly.
The display is sharing its port with a port expander and a SD-port. But removing the SD-port doesn't change the problem.
Update (Part1)
Here comes the code, which works:
http://pastebin.com/eXUVzeV8
This is a slightly modified manufacturer example. But it does what it should do. It displays the demo text.
Here comes, what doesn't work:
Main sketch
newsched.h
newsched.cpp
display.h
display.cpp
menu.h
menu.cpp
The other source files, 19 in total!, can be posted on request, but as you can see from newsched.cpp I already disabled most of the code to narrow down the error.
What exactly means "not work"? Not work means, the display seems to be turned off. The LED backlight is on, but you cannot see the grey character boxes (due to display bias), which appear in the working code sample.
Update 2
Schematic:

What you should do next is show us your wiring (schematic) and sketch.

My initial response is that this is too broad to be answered. For one thing you say it "works" in one case but "not in my sketch" in another. A lot more detail would be helpful, describing what "work" and "not work" refer to, exactly. For more help I would suggest posting the code (or a link to it if it is very long) and also your debugging messages, which you say you got. Presumably if you got debugging messages it "works" to some extent (that is, it doesn't hang completely). But removing the SD-port doesn't change the problem. - again, what problem?

That sounds like a mighty complex program with that number of files. Have you considered you might simply be running out of memory? I notice you have never used _F(...) around any of your string constants to lock them into flash...

I added a bunch of code and schematic now. Let me know, if you want to see more source files...

@Majenko: No, that _F-feature is new to me. String constants are predominant in the menu class. The other classes deal with small portions of measurement data and control tasks. What makes the project big is the use of a lot of peripherals over the three stooges: SPI, I2C and 1-wire bus. To keep the overview I make a class at least for each peripheral unit. Now, I'll have a look onto the F-thing...

The _F() thing stops the strings being copied into RAM.  It's a macro that makes then into PROGMEM items so that PROGMEM-enabled functions are used to access them instead of non-PROGMEM ones that require the string to first be copied into RAM to access them. It's all because the Flash and RAM are on completely separate data/address buses.

Ok, got it. It's just a PROGMEM macro. How convenient.

To my discomfort the F-macro only works where the functions are overloaded appropriately. Which is not the case for the display routines. But the hint was good, as I had forgotten the fact, that strings are copied to ram at program start.


text:
Blocking Serial Data
I am driving two stepper motor using serial data from Raspberry Pi to Arduino. Motors work fine when i am passing serial data but once i stop sending serial data, it doesn't accept serial data again unless I burn the program again in arduino. Here is code for that:
 #include <Driver.h>

//////////////////////////////////////////////////////////////////////////////////////////
/*
   Hardware pins defined in this section as connected from arduino to Pan DRV8834
   controller and tilt DRV8834 controller.M0 and M1 pins are common for both controllers
   ,hence declared only once(This is done to save number of pins, connecting it to
   additional pins , provide no special advantage since both both motors should be set
   to same level of microstepping).SLP pin is not currently used.

*/
//////////////////////////////////////////////////////////////////////////////////////////

#define PAN_DIRECTION_PIN 8
#define TILT_DIRECTION_PIN 7

#define PAN_STEP_PIN 10
#define TILT_STEP_PIN 9

#define M0 6
#define M1 5

#define MOTOR_SPEED 200

#define SLP 0
///////////////////////////////////////////////////////////////////////////////////////////

#define BAUD_RATE 230400      //Baud Rate for serial communication

///////////////////////////////////////////////////////////////////////////////////////////

/*
   field data for receiving buffer on arduino side , important for serial communication
*/
#define NUMBER_OF_FIELDS 2 // how many comma separated fields we expect
int fieldIndex = 0;           // the current field being received
int values[NUMBER_OF_FIELDS];  // array holding angles for both motors

const char startChar = '<'; //beginning character of a valid command
const char endchar   = '>'; //this will be ending character to ensure a valid command has ended
boolean storeString = false; //This will be our flag to put the data in our buffer

#define zeroCharacter 'z'

bool zeroCommand = false;

#define DATABUFFERSIZE 50
char dataBuffer[DATABUFFERSIZE + 1]; //Add 1 for NULL terminator
int dataBufferIndex = 0;

int procBufCounter;         //iterate through whole string to obtain the commands

float panAngle, tiltAngle;

int sign = 1;

    Driver stepper_pan(M0, M1, PAN_STEP_PIN, SLP, PAN_DIRECTION_PIN);
    Driver stepper_tilt(M0, M1, TILT_STEP_PIN, SLP, TILT_DIRECTION_PIN);

    void processCommand(char *buffer) {

        procBufCounter = 0;
        bool startprocessing = false;
        bool endprocessing = false;

        values[0] = 0;
        values[1] = 0;

        while ((procBufCounter < DATABUFFERSIZE) && (!endprocessing)) {

            char ch = buffer[procBufCounter];           //read the character while simulatneously increasing the buffer cursor

            if (ch == '<') {
                startprocessing = true;
            }
            else if (ch == '>') {
                values[fieldIndex] = values[fieldIndex] * sign ;
                fieldIndex = 0;
                endprocessing = true;
            }

            if (startprocessing)
            {
                if (ch == ',') {
                    values[fieldIndex] = values[fieldIndex] * sign ; // set value to the accumulated value
                    sign = 1;
                    fieldIndex++;
                }
                else if ('0' <= ch && ch <= '9' ) {
                    values[fieldIndex] = (values[fieldIndex] * 10) + (ch - '0');
                }
                else if (ch == '-') {
                    sign = -1;
                }
                else if(ch == 'z'){
                  zeroCommand = true;
                }
            }
            procBufCounter++;
        }
        panAngle = ((float)(values[0]))/100;
        tiltAngle = ((float)(values[1]))/100;

       bool panMoved = true, tiltMoved = true;
        stepper_pan.moveTo(panAngle);
        stepper_tilt.moveTo(tiltAngle);
      while (panMoved || tiltMoved) {
        panMoved = stepper_pan.run();
        tiltMoved = stepper_tilt.run();
      }

      if(zeroCommand){
        stepper_pan.reset_positions();
        stepper_tilt.reset_positions();
        zeroCommand = false;
      }

    }

    //////////////////////////////////////////////////////////////////////////////////////

    void setup() {
      stepper_pan.setStepMode(STEP_THIRTYTWO);
      stepper_pan.setSpeed(MOTOR_SPEED);
      stepper_tilt.setStepMode(STEP_THIRTYTWO);
      stepper_tilt.setSpeed(MOTOR_SPEED);
      Serial.begin (BAUD_RATE);
      Serial.flush();
    }

    void loop() {
      if (processString) {
        processCommand(dataBuffer);
        processString = false;
    //     dataBuffer = "";

      }
    }

    void serialEvent() {
      static int dataBufferIndex = 0;
      while (Serial.available() > 0) {
        char incomingbyte = Serial.read();
        if (incomingbyte == startChar) {
          dataBufferIndex = 0;  //Initialize our dataBufferIndex variable
          storeString = true;
        }
        if (storeString) {
          //Let's check our index here, and abort if we're outside our buffer size
          //We use our define here so our buffer size can be easily modified
          if (dataBufferIndex == DATABUFFERSIZE) {
            //Oops, our index is pointing to an array element outside our buffer.
            dataBufferIndex = 0;
            break;
          }
          if (incomingbyte == endchar) {
            dataBuffer[dataBufferIndex] = endchar; //null terminate the C string
            dataBuffer[dataBufferIndex + 1] = '\0';
            //Our data string is complete.  return true
            storeString = false;
            processString = true;
            dataBufferIndex = 0;
          }
          else {
            dataBuffer[dataBufferIndex++] = incomingbyte;
            dataBuffer[dataBufferIndex] = 0; //null terminate the C string
          }
        }

      }

    }

It's difficult to debug your code because it's not complete, I think there is quite a bit of code in parameters.h.  Also the commented out LCD code is a distraction.  Is it possible to edit your post to have al of the relevant code? (Then people can copy it and debug it)

@Matt I have edited the code , can you please have a look now, thanks!

I finally figured it out. It is due to reset whenever I open a port for serial communication. Attaching a 10uF capacitor between ground and reset fixed everything.

Note that you can control the reset behavior from the Raspberry Pi without having to add components: http://arduino.stackexchange.com/questions/16776/how-to-connect-arduino-device-to-linux


text:
Can't include files
For some reason, the Arduino IDE can't find the file I have made for the project:
#include <foo1.h>
#include <foo2.h>
#include "foo3.h"

Where foo1 and foo2 are normal libraries thus included with <..> but foo3 is another file I wrote which resides in the same directory as the .ino file from where this code is taken.
If I essentially convert foo3 into a library and include it as a library in my project it works but makes the project harder to move.
Error I get:
Project.ino:6:23: fatal error: foo3.h: No such file or directory
:#include "foo3.h"
:compilation terminated
Error compiling project sources

Note: Error is persistent in both the Arduino IDE and VMicro

In the error message, it shows  <> for the problem file, although your question suggests you're using "" (as you should). Which is it?

Seems I have copied the wrong error message. Thanks for noticing.

It seems that my mistake was that I just created new files with another program and simply put them in the project directory. This probably confused the IDE as the files were not included in the build of the project.
Managed to fix this issue by creating new files within the project itself and simply copying my code into them. For VMicro/Visual Studio:

VMicro\Add Code\Add Empty Arduino .h and .cpp files

Changing to double quotes with header files in the same folder worked for me.

The question is a bit unclear, however as far as I know, for the included libraries use:
#include <SPI.h>

So the < and > are used for common libraries which are in the C:\Program files...\Arduino folder
And for specific (own made or sketch-depending) include files
#include "MyFile.h"

should be used, which should be located in the same folder as the sketch file.

Yes, that is what I have done but the file I have included as ".." can't be located by the IDE even though it is in the same folder as the main .ino file.

The 'brackets' aren't to do with where the files are, but to do with the order the directories are searched.  For GCC (Visual Studio is different) files in quotes are searched in the directory containing the file that is doing the including then the "preconfigured system directories" where as the <> brackets skip the local folders.  Also it is easier to find compile errors if you include <> first and the "", because the error location of a duplicate definition will be reported against you code and not the system libraries (which you shouldn't be changing)


text:
I am using millis () function but after one iteration it does not check the condition and enters the loop. What should I do?
I am using mq7 sensor where I have to toggle vcc between 5 to 1.5 V for 1 min and 1.5 min. For this I am using millis function.But after 1st iteration it skips the condition and enters the loop.
The code is as follows:
    //the number of the LED pin
    const int ledPin = 14;
     float sensorPin = 34;
    // setting PWM properties
    const int freq = 5000;
    const int ledChannel = 0;
    const int resolution = 8;
    unsigned long previousMillis = 0;

    void setup(){
      // configure LED PWM functionalitites
      Serial.begin(115200);
      Serial.println("started");
      ledcAttach(ledPin, freq, resolution);
      ledcAttachChannel(ledPin, freq, resolution, 0);
    }

    void loop(){
      // increase the LED brightness
     unsigned long  currentMillis = millis();
      Serial.println("hii");
    // changing the LED brightness with PWM
        ledcWrite(ledPin, 255);
       if (currentMillis - previousMillis > 60000)
       {
        previousMillis = currentMillis;
        // save the last time you blinked the LED
        Serial.println("switching");
        // changing the LED brightness with PWM
        ledcWrite(ledPin, 95);
        delay(90000);
        Serial.println("switching");
         // we need to read the sensor at 5V, but must not let it heat up. So hurry!
        ledcWrite(ledPin, 255);
        delay (50); //don't know how long to wait without heating up too much. Getting an analog read apparently takes 100uSec
       // read the value from the sensor:
       Serial.println("switching");
        int sensorValue = analogRead(sensorPin);
        Serial.println(sensorValue);
       }
    }

The output is as follows:

The millis()-based programming idiom you are using is intended to
handle delays without ever blocking the program in a delay() call.
Then you are completely defeating its purpose by calling delay(90000).
After this 1.5 min delay, of course one minute will have elapsed, and
the test currentMillis - previousMillis > 60000 will always be true.
If you want to embrace the non-blocking paradigm millis() allows, you
should completely ban delay() from your vocabulary (as well as other
blocking loops).
Edit: Answering the question in the comment “Can you suggest as to
how can I modify the code for 1.5 minutes delay”. As suggested by
JRobert in another comment, you should follow the “Blink Without Delay”
Arduino example. There is only one caveat: this Arduino example keeps
the LED on for one second and off for another second, while you want to
toggle your system between two states with different durations.
The solution is to remember what state you are currently on, and write
separate code paths for handling each state. As an example, the code
below toggles the on-board LED, keeping it on for 100 ms and off
for 900 ms. This is achieved by remembering the current state (in
the boolean variable is_on below) and conditioning the code execution
on the current state (e.g. if (is_on && ...)).
/*
 * Toggle the on-board LED on for 100 ms every second.
 */

const unsigned long time_on  = 100;  // on time  = 100 ms
const unsigned long time_off = 900;  // off time = 900 ms
unsigned long previousMillis;   // previous time the LED was toggled
bool is_on;                     // is the LED currently on?

void setup() {
    pinMode(LED_BUILTIN, OUTPUT);
    digitalWrite(LED_BUILTIN, LOW);
    is_on = false;
}

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

    // If the LED has been on long enough, turn it off.
    if (is_on && currentMillis - previousMillis >= time_on) {
        digitalWrite(LED_BUILTIN, LOW);
        is_on = false;
        previousMillis = currentMillis;
    }

    // If the LED has been off long enough, turn it on.
    if (!is_on && currentMillis - previousMillis >= time_off) {
        digitalWrite(LED_BUILTIN, HIGH);
        is_on = true;
        previousMillis = currentMillis;
    }
}

Can you suggest as to how can I modify the code for 1.5 minutes delay should I write millis loop

See the Examples in the Arduino IDE. In the second group, 'Digital', the 'Blink Without Delay' sketch shows a good example of how to do that.

@YuktaSanghvi your code already contains a 1 minute delay using millis() ... what is preventing you from changing it to 1.5 minutes?


text:
Why are my ESP8266 HTTP firmware updates failing?
I've just spent a few hours on this and I am starting to go crazy. I have code to do a firmware update over HTTP working on several ESP32s. I'm trying to adapt that code to work on an ESP8266, but can't get it to work. I've copied several examples from the internet that work for everyone else, not to mention my own code that works on the ESP32. The error is

HTTP_UPDATE_FAILD Error (-106): Verify Bin Header Failed

I would attribute that to an issue with my bin URL, however, when I copy/paste the link in to a browser, it downloads it fine, and I even tried using the same URL that is working with my ESP32 boards, with the same result. My code is below, and is pretty darn close to the provided example (I'm on the ESP 3.0.0 core).
    #include <ESP8266WiFi.h>
    #include <ESP8266HTTPClient.h>
    #include <ESP8266httpUpdate.h>

    #define URL_fw_Bin "https://raw.githubusercontent.com/[my profile]/[my project]/main/[firmware].bin"

    void setup() {
      Serial.begin(9600);
      WiFi.begin();
      while(WiFi.status()!=WL_CONNECTED){
        delay(1000);
        Serial.print(".");
      }

      WiFiClientSecure client;
      client.setInsecure();
      ESPhttpUpdate.setLedPin(LED_BUILTIN, LOW);
      t_httpUpdate_return ret = ESPhttpUpdate.update(client, URL_fw_Bin);

      switch (ret) {
      case HTTP_UPDATE_FAILED:
        Serial.printf("HTTP_UPDATE_FAILD Error (%d): %s\n", ESPhttpUpdate.getLastError(), ESPhttpUpdate.getLastErrorString().c_str());

      case HTTP_UPDATE_NO_UPDATES:
        Serial.println("HTTP_UPDATE_NO_UPDATES");
        break;

      case HTTP_UPDATE_OK:
        Serial.println("HTTP_UPDATE_OK");
        break;
      }
    }
    void loop() {
    }

The error message "Verify Bin Header Failed" suggests there might be an issue with the header of the binary file.

have "solved" the issue -- this is due to a bug in the ESP8266 core 3.0.0. Using core 2.7.4 solves the issue. This issue appears to describe the issue, but perhaps the fix hasn't made it to the full release yet:
https://github.com/esp8266/Arduino/issues/8079


text:
Is the Arduino bootloader really the Atmel bootloader? Can I use Flip to upload?
I've been asked to do a small project using an Ada BlueFruit board. It has a ATMega32U4. The 32U4 comes from the factory with a bootloader pre-installed. I've never used an Arduino before, but I have used AVR a bit in the past. Is the Arduino bootloader actually the one that came pre flashed from the factory? Does it even matter if it's the same bootloader as far as Flip is concerned?
Can I use the Flip batchisp utility to load my application code? We don't have a programmer handy and I don't want to muck up the bootloader on the board.
It's my understanding that the Arduino IDE tool chain does a bit of preprocessing "behind your back". I'd much rather continue writing straight AVR code in Atmel Studio. Is there anything I need to take into account when writing my application code? For example, do I need to do anything when compiling my app code, or when uploading it, to ensure it doesn't try to write to the memory addresses in the bootloader's range?

I don't really see what this is to do with the Arduino. You are asking about using a non-Arduino and not using the Arduino IDE.

Doesn't have anything to do with Arduino? The AdaFruit uses the Arduino software. https://learn.adafruit.com/adafruit-feather-32u4-basic-proto

I think you are talking about the "Bluefruit LE Micro" board.  Please note, Adafruit has several products called Bluefruit! So I think you are confusing people here.  And getting answers that may not be what you want.  Bottom line, (I think) you are "re-inventing the wheel".  If you go this alone (do bare-metal-programming or Atmel-boot-loader based development) you may have problems using the Adafruit Arduino libraries for their Bluetooth module soldered on this board.

The AdaFruit uses the Arduino software. - yes but the OP said s/he did not want to use the IDE. So the question was basically "how do I upload a .hex file to a ATMega32U4?".

I think the OP is giving up a lot of working-out-of-the-box code (Arduino-Adafruit Bluetooth libraries that I linked to) that he/she will have to port to the new IDE/SDK they pick.  ...  So, what the OP's question boils down to is can they use FLIP instead?  Maybe.  There's nothing special about the Arduino boot loader.  But it is likely you will have to program the Atmel with a real Atmel programmer or use a 2nd Arduino as discussed in this thread.

@st2000 I'm not giving up anything as far as I can tell. I don't see why I can't use those libraries. The libraries are written in cpp, nor ino. I do not want to burn the bootloader at all. I want to keep it intact. Why would I need to program the board when there's already a bootloader? Would EE be a better place to ask this question?

@NickGammon there's a bit more to it than that. You mentioned in your (updated) answer that I would need to ensure the memory doesn't overlap with the bootloader. I'd like to know how to do that. I'm happy to edit this question to clarify, but I need some help figuring out how to do that here.

To be honest, I'm am used to bare-metal programming.  And having done a boot loader and application embedded processor project, I know it is not trivial to keep the two separated.  That is, your worries about how the linker needs to be put together is not unfounded.  That said, I'm not sure the Atmel has the right type of resources to keep the Arduino boot loader in memory and still allow you to do what ever you want w.r.t. your application programming.  Keep in mind the boot loader is situated to run FIRST after processor reset.  How are you going to work around that?

Is the Arduino bootloader actually the one that came pre flashed from the factory?

You would have to ask Adafruit that.

It's my understanding that the Arduino IDE tool chain does a bit of preprocessing "behind your back". Is there anything I need to take into account when writing my application code?

The things you are talking about is generation of function prototypes, that sort of thing. It's nothing you really need to worry about.

For example, do I need to do anything when compiling my app code, or when uploading it, to ensure it doesn't try to write to the memory addresses in the bootloader's range?

No, it would be crazy for the IDE to overwrite the bootloader. Then you wouldn't be able to use it again. In fact, to change the bootloader needs special hardware. You need to connect a programmer to the ICSP pins.

I just want to know if I need to do anything special during linking to ensure there's no memory address conflicts

I doubt you need to worry about that, as long as you ensure that whatever tool you are using knows to allow room for the bootloader.

and if I can use the Flip tool to upload

I don't see why not. Or you could use the dfu-programmer as I describe in my post How to flash the USB chip on the Arduino Uno.

I should have been more explicit. I don't want want to use the Arduino "IDE". I can compile my C code to a hex. I just want to know if I need to do anything special during linking to ensure there's no memory address conflicts and if I can use the Flip tool to upload.

See amended reply.

I'd much rather continue writing straight AVR code in Atmel Studio.

The Arduino IDE allows you be lazy about #includes and forward references to functions, but it won't get in your way if you choose to write correct code.
I write standard C/C++ and switch back and forth between Eclipse (no over-helpful pre-processing) and the Arduino IDE. The Arduino IDE knows better; it just CYA (covers your assumptions :) in case you don't.

Arduino uses a different (second) bootloader, next to the DFU one that build into the 32u4.


text:
Arduino: Reading DS18B20 interferes with servo
I have an Arduino with a servo, INA219 (current and voltage sensor) and 2 DS18B20 connected to it.
DS18B20 are connected in full-power mode with 5k resistor connected between DATA line and +5V.
I use DallasTemperature library: https://github.com/milesburton/Arduino-Temperature-Control-Library
I get the temperature readings, but the problem is that my servo is jittering slightly almost every time temperature reading is done.
If I disconnect DATA line from pin 2 (where it's normally connected) then servo is not moving anymore and everything is fine.
Any ideas what might be causing it? I would expect servo interfering with OneWire readings, not the other way around :)
Here is the full code:
https://pastebin.com/xcES4PVT
Here is the minimal example with which I can reproduce the problem:
    #include <DallasTemperature.h>
#include <Servo.h>

#define ONE_WIRE_BUS 2
OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);

Servo myservo;

long previousMillis = 0;

long tempRequestedMillis = 0;

bool tempRequested = false;

void setup(void)
{
  // start serial port
  Serial.begin(115200);
  Serial.println("Dallas Temperature IC Control Library Demo");

  myservo.attach(9);

  // Start up the library
  sensors.begin();
  sensors.setWaitForConversion(false);
}

void loop(void)
{

  unsigned long currentMillis = millis();
  if (!tempRequested && currentMillis - previousMillis > 2000) {
    previousMillis = currentMillis;

    sensors.requestTemperatures(); // Send the command to get temperatures

    tempRequestedMillis = currentMillis;
    tempRequested = true;
  } else if (tempRequested && currentMillis - tempRequestedMillis > 2000) {
    Serial.println(sensors.getTempCByIndex(0));
    tempRequested = false;
  }
}

maybe something is taking up too much time in the loop ... start by commenting out all the serial.print statements

I have the same problem that Leonti. BUt in my case, i have a duemilanove and the lcd shield, that which occupies pins 9 and 10 that I read are the necessary ones in the duemilanove to work with this library. Is there any possibility of using other pins? Is there another library that uses different pins? I have free: A1,A2,A3,11,12 and 13...

Arduino's Servo library on AVR uses interrupts; if interrupts are disabled for any amount of time, the servos will twitch.
1-Wire protocol (used by DS18B20) needs to disable interrupts for the protocol to work. Therefore, servos glitch.
There is a great explanation of the problem here: https://learn.adafruit.com/neopixels-and-servos/overview , just mentally replace "Neopixel library" with "OneWire library". Their TiCo_Servo library sounds just like what you want.

That was it!
After using TiCoServo library there are no issues!
Thanks a lot!

The OneWire library was poorly implemented IMO. It globally disables all interrupts when it only really needs to disable interrupts on the data line. If other interrupts are well behaved and return quickly, it won’t disrupt the One wire timing. I don’t know how to turn my avr code into an Arduino library, but there’s an alternative implementation in my digital thermometer project. https://github.com/rubberduck203/digital-thermometer


text:
nrf24l01 fried when supplying 6.5V to VIN?
I have two Arduino Unos (One clone, one genuine) and I'm trying to make a remote and a base station. Got everything working flawlessly, (Using RF24 library) and the last piece of the wiring was to get the remote Arduino off the USB and powered by battery. I have a 4 AA battery holder which I put 4 brand new alkaline batteries in. Soldered up some connectors, plugged it in and...nothing?
Ran the demos everyone seems to use. Nothing again. Ran the "diagnostic script at the end of that thread...results seemed fine...
CheckConnection Starting

FIRST WITH THE DEFAULT ADDRESSES after power on
  Note that RF24 does NOT reset when Arduino resets - only when power is removed
  If the numbers are mostly 0x00 or 0xff it means that the Arduino is not
     communicating with the nRF24

STATUS       = 0x0e RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=7 TX_FULL=0
RX_ADDR_P0-1     = 0xe7e7e7e7e7 0xc2c2c2c2c2
RX_ADDR_P2-5     = 0xc3 0xc4 0xc5 0xc6
TX_ADDR      = 0xe7e7e7e7e7
RX_PW_P0-6   = 0x00 0x00 0x00 0x00 0x00 0x00
EN_AA        = 0x3f
EN_RXADDR    = 0x03
RF_CH        = 0x4c
RF_SETUP     = 0x07
CONFIG       = 0x0e
DYNPD/FEATURE    = 0x00 0x00
Data Rate    = 1MBPS
Model        = nRF24L01+
CRC Length   = 16 bits
PA Power     = PA_MAX

AND NOW WITH ADDRESS AAAxR  0x41 41 41 78 52   ON P1
 and 250KBPS data rate

STATUS       = 0x0e RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=7 TX_FULL=0
RX_ADDR_P0-1     = 0xe7e7e7e7e7 0x4141417852
RX_ADDR_P2-5     = 0xc3 0xc4 0xc5 0xc6
TX_ADDR      = 0xe7e7e7e7e7
RX_PW_P0-6   = 0x00 0x20 0x00 0x00 0x00 0x00
EN_AA        = 0x3f
EN_RXADDR    = 0x03
RF_CH        = 0x4c
RF_SETUP     = 0x27
CONFIG       = 0x0e
DYNPD/FEATURE    = 0x00 0x00
Data Rate    = 250KBPS
Model        = nRF24L01+
CRC Length   = 16 bits
PA Power     = PA_MAX

Ran test on the working arduino, and got a similar result. Checked continuity on all pins twice. Can't think of what could have suddenly gone wrong? Definitely didn't change my code, but just to be sure tried the examples from the above thread...
The only thing I did different was supplying power from VIN at 6.5 V (Measured with multimeter). Should be well within range for the linear voltage regulator? Definitely correct polarity. Hooked in a servo and wrote a quick sketch to drive it then powered the PWM from the battery powered arduino. Other function from my code (rotary encoder, OLED, etc) all seem to be functioning perfectly.
Fried module?
EDIT
I was powering the module through the 3.3V regulated output pin on the Arduino.
Noticed with the battery plugged in whenever I check the voltage with my meter 3.3 pin bounces to 3.7 then settles to 3.3. Not sure if that's the meter, or just the regulator catching up to the (what should be very low with a multimeter) load. Same behavior occurs with USB.

Unrelated; 6.5 Volt is on the low side for Vin. And this voltage will drop even lower when the batteries drain. Minimal recommended voltage is 7 Volt.

If I remember correctly (IIRC) The nrf24l01 module:

runs on 3.3 Volts
doesn't have a voltage regulator

It could be fried, try supplying a regulated 3v3 supply and see if it works then.

I should have mentioned that I'm using the 3.3 regulated voltage on the arduino to power the module. This has worked for me, and is still working on the other arduino. Didn't even need the capacitor as some people suggest. When I plug in the battery the multimeter says that it's at 3.3 V.

perhaps the LDO on the uno  can't power the wireless interface; i know the esp8266 is like that. I's possible that with a higher input voltage and a strong load on the LDO it could overheat and/or fail

As per the datasheet nrf24L01 runs for voltages below 3.6V ~ 1.1V.
Also soldering a capacitor between the Vcc and Gnd of an nrf24L01 module would help you to in connection issues.
Please see this video for further assistance on working:
A network of nrf24L01

The 3.3V regulator on the Arduino is only good for 150mA. On the clone, who knows.
If you're seeing 3.3V, the regulator may be capable. The nrf24L01 draws more current when transmitting, so it's possible it looks good at time and fails at other times.


text:
Improving moving mouse loop to optimize speed
Code:
#include <Mouse.h>
#include <hiduniversal.h>
#include "hidmouserptparser.h"
#include <USBController.h>

USBController controller;
USB Usb;
HIDUniversal Hid(&Usb);
HIDMouseReportParser Mou(nullptr);
String x;
String y;
boolean isX;
int recv;

void setup() {
    Mouse.begin();
    Usb.Init();
    delay(200);

    if (!Hid.SetReportParser(0, &Mou))
        ErrorMessage<uint8_t > (PSTR("SetReportParser"), 1);
}

void loop() {
    Usb.Task();
    recv = controller.read();
    if ((recv-48)==29){ // recv = M
        // , : -4
        // /n : -38
        x="";
        y="";
        isX = true;
        while (true){
            recv = controller.read();
            if (recv!=0 && recv!=2){ // filter out 0 and 2
                if ((recv-48)==-38){ // -38 is a line break
                    break;
                }
                else if ((recv-48)==-4){ // switch to y value after comma
                    isX = false;
                    continue;
                }

                if (isX){
                    x+=String(recv-48);
                }
                else{
                    y+=String(recv-48);
                }
            }
        }
        Mouse.move(x.toInt(),y.toInt());
    }
}

void onButtonDown(uint16_t buttonId) {
    Mouse.press(buttonId);
}

void onButtonUp(uint16_t buttonId) {
    Mouse.release(buttonId);
}

void onMouseMove(int8_t xMovement, int8_t yMovement, int8_t scrollValue) {
    Mouse.move(xMovement, yMovement, scrollValue);
}

I'm using an Arduino leonardo with a usb host shield. My goal is to move my cursor to a specific location based on the data read in. Format of the data read in is "MX,Y" and a line break.
In the main loop,

I read the data and subtract 48 because that's the real number.
Then I check if the first character is M because that is where the beginning of my data starts.
Then I filter out 0 and 2 because those values are useless to me and randomly appear.
I loop to add the integer values as strings to x then switch to y after the comma appears.
Then I convert the string values to int and mouse.move.

The problem is the mouse movement is slow and jittery and I think it's because the toInt and String() methods are slowing it down. How could I improve my algorithm?

This:

while (true){
    recv = controller.read();
    // ...
}

is a blocking loop. This means that, while executing this part of the
code, the Arduino is stuck for an indeterminate amount of time, and can
do nothing else. Specifically, it cannot run Usb.Task(), which could
well be the cause of the jittery behavior you are experiencing.
I would recommend reading the incoming data in a non blocking fashion:
each time there is a byte to be read, read it and move on. Do not wait
for the subsequent bytes. Only when you find an end of line would you
handle the data you received. For example:
// Parse and execute a command received through USB.
executeCommand(String &command) {
    // Implementation left as an exercise to the reader.
}

// Whether we are presently receiving characters from a command.
bool receivingCommand = false;

// Received command, may be incomplete.
String command;

void loop() {
    Usb.Task();
    if (controller.available()) {
        char c = controller.read();
        if (!receivingCommand && c == 'M') {  // start of command
            receivingCommand = true;
        } else if (receivingCommand && c == '\n') {  // end of command
            executeCommand(command);
            command = "";
            receivingCommand = false;
        } else if (receivingCommand) {  // body of command
            command += c;  // buffer the received character
        }
    }
}

A better approach would be to avoid the String class, which is not
friendly to your Arduino's memory, and use a plain C string, as
explained in Reading Serial on the Arduino. This, however, is
likely unrelated to your jitter issue.

Thanks! How would I use a C string to this program. My input is originally a float and I need to add that to a character array. Don't I need to convert it to a String first?

@JakeJin: No, you do not need a String. You can convert a float to a character array using dtostrf().


text:
ATMEGA2560 died inside a arcade game circuit
I am building arcade game with 10 player buttons (5 for each player) and one start button. All buttons have build in LED inside. Player buttons has LED for 12V and start button has led for 5V. I am using ATMEGA2560 pro boar. I have also 4 TM1637 displays (two for each player) showing time and score. I am using 12V adapter. This is my schematic:

This is test code which I had:
#include <Arduino.h>
#include <TM1637Display.h>

#define BTN_A1_PIN 16
#define BTN_A2_PIN 18
#define BTN_A3_PIN 28
#define BTN_A4_PIN 26
#define BTN_A5_PIN 47

#define BTN_B1_PIN 44
#define BTN_B2_PIN 36
#define BTN_B3_PIN 39
#define BTN_B4_PIN 46
#define BTN_B5_PIN 37

#define LED_A1_PIN 13
#define LED_A2_PIN 17
#define LED_A3_PIN 11
#define LED_A4_PIN 15
#define LED_A5_PIN 19

#define LED_B1_PIN 25
#define LED_B2_PIN 27
#define LED_B3_PIN 23
#define LED_B4_PIN 21
#define LED_B5_PIN 29

#define BTN_START_PIN 32
#define LED_START_PIN 35

#define DISPLAY_A_SCORE_CLK 20
#define DISPLAY_A_SCORE_DIO 10

#define DISPLAY_A_TIME_CLK 40
#define DISPLAY_A_TIME_DIO 43

#define DISPLAY_B_SCORE_CLK 42
#define DISPLAY_B_SCORE_DIO 33

#define DISPLAY_B_TIME_CLK 34
#define DISPLAY_B_TIME_DIO 38

typedef struct
{
  uint8_t btnIn;
  uint8_t ledOut;
} btn_t;

btn_t btn[] = {
    {
        .btnIn = BTN_A1_PIN,
        .ledOut = LED_A1_PIN,
    },
    {
        .btnIn = BTN_A2_PIN,
        .ledOut = LED_A2_PIN,
    },
    {
        .btnIn = BTN_A3_PIN,
        .ledOut = LED_A3_PIN,
    },
    {
        .btnIn = BTN_A4_PIN,
        .ledOut = LED_A4_PIN,
    },
    {
        .btnIn = BTN_A5_PIN,
        .ledOut = LED_A5_PIN,
    },
    {
        .btnIn = BTN_B1_PIN,
        .ledOut = LED_B1_PIN,
    },
    {
        .btnIn = BTN_B2_PIN,
        .ledOut = LED_B2_PIN,
    },
    {
        .btnIn = BTN_B3_PIN,
        .ledOut = LED_B3_PIN,
    },
    {
        .btnIn = BTN_B4_PIN,
        .ledOut = LED_B4_PIN,
    },
    {
        .btnIn = BTN_B5_PIN,
        .ledOut = LED_B5_PIN,
    },
    {
        .btnIn = BTN_START_PIN,
        .ledOut = LED_START_PIN,
    },
};

TM1637Display displayAScore(DISPLAY_A_SCORE_CLK, DISPLAY_A_SCORE_DIO);
TM1637Display displayATime(DISPLAY_A_TIME_CLK, DISPLAY_A_TIME_DIO);
TM1637Display displayBScore(DISPLAY_B_SCORE_CLK, DISPLAY_B_SCORE_DIO);
TM1637Display displayBTime(DISPLAY_B_TIME_CLK, DISPLAY_B_TIME_DIO);

void setup()
{
  for (int i = 0; i < 11; i++)
  {
    pinMode(btn[i].btnIn, INPUT_PULLUP);
    pinMode(btn[i].ledOut, OUTPUT);
  }
  displayAScore.setBrightness(0x0f);
  displayATime.setBrightness(0x0f);
  displayBScore.setBrightness(0x0f);
  displayBTime.setBrightness(0x0f);

  displayAScore.showNumberDec(1111, false);
  displayATime.showNumberDec(2222, false);
  displayBScore.showNumberDec(3333, false);
  displayBTime.showNumberDec(4444, false);
}

void loop()
{
  for (size_t i = 0; i < 11; i++)
  {
    if(0 == digitalRead(btn[i].btnIn))
    {
      digitalWrite(btn[i].ledOut, HIGH);
    }
    else
    {
      digitalWrite(btn[i].ledOut, LOW);
    }
  }
}

And this is what it looks like inside:

The problem is ATMEGA2560 just burned. I was testing it firstly without TM1637 (they were connected to power but I did not use lib for them at that time) and it was working okay (buttons were lighting up upon pressing).
Then I added lib for TM1637 to code and for 2 seconds I saw "1111" "2222" ... so on as it is in code, so there is no bad connection. But after 2 seconds it started buzzing (probably linear regulator temp protection was kicking in) and ATMEGA just burned.
Now when I plug 12V in it MCU gets hot pretty fast. I can measure 5V on the linear regulator so it is not shorted. I had always connected only 12V and no power from USB. I know my wires are not the shortest but I would not expect that MCU dies. Could you help please? I don't want to plug the next 20€ chip just to see another expensive smoke.

either something is miswired, or a component is not what you think it is ... maybe the buttons have an internal connection between the switch and the indicator LED

@jsotola thanks for answer. I double checked every connection and it was correct. No, buttons are not connected with LEDs

The 5V pin on the board probably isn't a good place to pull power for the displays.  I'm sure that's more than it can supply.  Ideally they should have their own power supply.

You fried it because you broke rule #1: "A Power Supply the Arduino is NOT!". Your displays can pull 320 Ma in themselves. That is over 2 watts of power before anything else. When you get a new one purchase a buck converter and power the LEDs with the 5V output of that, use the 12V to feed it. As I understand it The suggested maximum power dissipation for the Mega regulator is 1 Watt. So with 12V into the regulator the max current is about 140 mA (1W / (12V - 5V)), This does not count your LEDs.

I was counting on the protection circuit of the regulator, these linear ones use to have it. But is it strange why ATMEGA burned, but regulator is outputting 5V. I used separate supply for ATMEGA and displays and now it is working. Thanks for answer.


text:
Comparators for digital input mode
I've asked another question in electronics about what to use to compare 2 input voltages, the answer was to use comparators.
Digging around a bit, turns out most of the comparators outputs are pull-up, which makes it quite difficult to translate (probably due lack of general electronics knowledge, self-learned) and I'm not able to distinguish from maker's PDFs which comparators have pull-up or pull-down outputs.
I've figured PD comparators illustrate in PDF a resistor right after the output... but many illustrations I've seen doesn't clarify PD / PU, or I'm just missig that.
But my question is, are there any PD comparators (well known) where it's output can be connected to the digital pins or arduino (while those are defined as INPUT mode)?
I appreciate any guidance on this topic.
Just a side note, I want to switch on a led, when ever external source is at 12V and turn that same led off when it's below 11.5V...

You can't put 12 volts into a Uno input pin in any case.
You could run it into a voltage divider and divide it down to somewhere on the range 0 to 5 V, and then do an analogRead to see exactly (or almost exactly) what the resulting voltage is.
I don't really see where comparators come into it in this particular case. I mean, you could use a comparator to turn the LED on, but then where does the Arduino come into it?

I've actually tried with voltage divider, I went pretty high on my resistors, taking the 12V source and hooked in 4x1M resistors but the 12V never came down significantly.

You need a voltage divider like this:

Those values give you 4 V on the Arduino pin if there is 12 V on the input.
Vout = (R2 / (R1 + R2) ) * Vin
So:
(1000 / 3000) * 12V = 4V

Perhaps the 12Vs don't have to do anything with the comparator. It does not read like it is related.

You could be right, but I read I want to switch on a led, when ever external source is at 12V and turn that same led off when it's below 11.5V... as the purpose for the comparator.

I was guided towards comparator since the external source is signal turning light in vehicle at it seems to output 12v as active and 11v (or close to 11v, +-0.5v) as inactive signal into the lightbulb. tho I suspect that there is some module that listens to these voltages and gives either 0 or 12v to the actual bulb but I'm unable to take apart that headlight to confirm that.

Ive actually tried with voltage divider, i went pretty high on my resistors, taking the 12V source and hooked in 4x1M resistors but the 12V never came down significantly. I also tested out with few lower resistors like mutiple 100K, also with multiple 4K7 (all in series) but i only got 6V as lowest and 9V as highest (also that 9V sometimes peaked up to 11V). I did try to add more and more resistors to bring the 10V/12V scale down for arduino to handle but it never succeeded.

You aren't doing it correctly then. Two resistors are all you need. A voltage divider does not work by having a lot of 1 M resistors in series. You need two resistors only, and tap into the junction between them. For example, a 2 k and a 1 k would divide 12 V down to 4 V. See voltage divider calculator. Look carefully at how they are wired.

Many comparators come with open collector output. OC output means, it can pull down a potential, but cannot generate a voltage higher than ground.
If you have a high impedance input like your Arduino has, and you connect a OC output to it, nothing will happen unless you add a pullup resistor providing a positive voltage. Otherwise there won't be a closed electric circuit where any measurable voltages can be generatet.
Lucky you: Arduino input pins can generate a positive voltage by providing an internal pullup resistor. Read the documentation on input pins and pin direction to make use of this. This way you can connect an open collector output to your input pin without additional components.
But beware: This doesn't work with a comparator with a pullup output (I guess these are rather rare). In this case you have to provide an additional pulldown resistor to ground.
Caveat: You can use a comparator with totem pole or tristate output without pullup or down as long as its output swing does not exceed maximum allowable voltages of the input pin. I.e. you cannot connect a comparator supplied with 15 V and a totem pole output to the input of an arduino, because the high level will exceed 5 volts (I assume an Arduino Uno).
Now. How to learn from a datasheet, if the output is pulldown, pullup, totempole or tristate?
If a device features a pulldown stage, you will find a value for something called "Output Sink Current" in the section "electrical characteristics". For a pulldown stage this will likely be named "Output source current". A tristate output will be denominated somewhere in the datasheet for sure, because this is an extra feature.
Have a look at lm339!

thank you for really good explanation, will check it out with PDFs. the reason to arduino is this led is actually neo pixel, and in arduino î have multiple animations for these pixels


text:
Can arduino create a file in its memory?
I am an arduino enthusiast and i am new to it.just wanted to know weather the micro processor itself could create a file in its memory while its is running. I know that it is possible to read a write from a file in c++ but is it possible to do so in an arduino (while it's running).

Can you explain what you're trying to achieve? Are you just looking for a way to store long-term data on the Arduino, or do you want another device to be able to read the file as well?

You can connect a SD-card, and communicate to it via SPI.

I am trying to save the output from a sensor as a text file temporarily which I can later tansfer to a PC

You can save it in a buffer in RAM, and if you maintain power and avoid reset then list it out on the debug serial interface and capture it on the PC side.  Or if it is bigger or you want it to last longer, you can use an SD card as already described.  An on-board SPI flash would be cheaper, but requires you to build the functionality for dumping the data over the serial and capturing it.

To answer the original question: Basically, yes, you can write libraries to implement a file system using the memories of an embedded microcontroller.
However, if it's feasible highly depends on the controller architecture and its peripherals.
Some of them (e.g. the one on Arduino Due) allow Flash reprogramming while an application is running from Flash.
Others require to have the application running in a special boot block or even in RAM when accessing the Flash for writing (this should be the case on an Arduino Uno)
And others don't allow Flash accesses from application at all.
Anyway:
The use of this for your purpose is very little, because the interface to the PC would also have to support the file system (for example, you could implement a FTP server and use an Ethernet connection...).
Therefore, the SD card approach is surely a very good suggestion.


text:
The Arduino robot tutorials describe a cord comming with the official robot, now I'm confused
I recently got the Arduino Robot and have been looking at the examples for the RobotLibrary. As I looked, I found something quite confusing (for me at least), a few of them describe connecting a sensor (like an IR sensor or Ultrasonic sensor) to a port with a cable that was provided with the robot. But I never received a cable. Which got me to question, what type of cable is this, because it is not the same cable you would use on an UNO, at least not according to the pictures. So does anyone know what type of cables these are and/or where I can get them? Thanks :smiley-mr-green:
Here are the pictures btw:

And the next one:

Usually, Arduino gives you the minimal board and sends you on your way. Reading over the instructions, I think they mean a cable that would have come with the IR sensor. That three-tone cord you see in the pictures are actually just three wires. You connect them as described if they came with the sensors. More likely, if they did not, you can use your own wires to connect these. Just be sure that you understand which is the ground (GND), power (+5V or some other +V), and signal. Usually, ground is denoted by the darkest color: black or brown; power is usually red, and signals can be any light color. USUALLY (READ about your device before you plug it in) ground and power are side-by-side for IR sensors, and signal is on the outside. Take a few minutes to Google up your device before plugging it in if you don't have documentation.
Good Luck!


text:
Pneumatic cylinders with sensors with Arduino Uno
I'm working on my own project with Arduino Uno. There are controlled 4 pneumatic cylinders via 4 coils. Every pneumatic cylinder has got their own coil which switch air to the pneumatic cylinder. Every pneumatic cylinder has got 2 magnetic sensors (when the pneumatic cylinder is retracted and extended).
I created a program for arduino but it doesn't work correctly. When I write there that I want to control only 2 pneumatic cylinders, it works correctly. If I write there the others, it skip the second if statement, do the third if statement and then do the previous if. I don't know why. The behaviour is random. What's wrong with my code? Thank you for help!
// Constants for pneumatic valves
   const int dvere = 2;
   const int davkovani = 3;
   const int lisovani = 4;
   const int vyhazovani = 5;
// ----------------------------------------
// Constants for sensors
   const int vyhazovaniZasunute = 6;
   const int vyhazovaniVysunute = 7;
   const int lisovaniVysunute = 8;
   const int lisovaniZasunute = 9;
   const int dvereZasunute = 10;
   const int dvereVysunute = 11;
   const int davkovaniVysunute = 12;
   const int davkovaniZasunute = 13;

void setup() {
  // Pneumatic cylinders set as output
  pinMode(dvere, OUTPUT);
  pinMode(davkovani, OUTPUT);
  pinMode(lisovani, OUTPUT);
  pinMode(vyhazovani, OUTPUT);

  // Sensors set as input
  pinMode(vyhazovaniZasunute, INPUT);
  pinMode(vyhazovaniVysunute, INPUT);
  pinMode(lisovaniVysunute, INPUT);
  pinMode(lisovaniZasunute, INPUT);
  pinMode(dvereZasunute, INPUT);
  pinMode(dvereVysunute, INPUT);
  pinMode(davkovaniVysunute, INPUT);
  pinMode(davkovaniZasunute, INPUT);

  // Set pneumatic cylinders as they are retracted
  digitalWrite(dvere, HIGH);
  digitalWrite(davkovani, HIGH);
  digitalWrite(lisovani, HIGH);
  digitalWrite(vyhazovani, HIGH);
}

void loop() {

  if(digitalRead(dvereZasunute) == HIGH)
  {
      digitalWrite(dvere, LOW);      // extend the first pneumatic cylinder when the sensor is lighted on because the pneumatic cylinder is retracted
  }

  if(digitalRead(dvereVysunute) == HIGH && digitalRead(davkovaniZasunute) == HIGH
  )
  {
      digitalWrite(davkovani, LOW);      // extend the second pneumatic cylinder
      delay(4000);
      digitalWrite(davkovani, HIGH);    // retract the second pneumatic cylinder after 4 seconds,
      // this code works when it is alone there, the next if statements not
  }

  if(digitalRead(dvereVysunute) == HIGH && digitalRead(davkovaniZasunute) == HIGH && digitalRead(lisovaniZasunute) == HIGH)
  {
      digitalWrite(lisovani, LOW);    // extend the third pneumatic cylinder
      delay(3000);
      digitalWrite(lisovani, HIGH);   // retract the secondthird pneumatic cylinder after 3 seconds
  }

  if(digitalRead(dvereVysunute) == HIGH && digitalRead(davkovaniZasunute) == HIGH && digitalRead(lisovaniZasunute) == HIGH)
  {
      digitalWrite(dvere, HIGH);      // retract the first pneumatic cylinder
  }

  if(digitalRead(dvereZasunute) == HIGH && digitalRead(davkovaniZasunute) == HIGH && digitalRead(lisovaniZasunute) == HIGH && digitalRead(vyhazovaniZasunute) == HIGH)
  {
      digitalWrite(vyhazovani, LOW);    // extend the fourth pneumatic cylinder
  }

  if(digitalRead(dvereZasunute) == HIGH && digitalRead(davkovaniZasunute) == HIGH && digitalRead(lisovaniZasunute) == HIGH&& digitalRead(vyhazovaniVysunute) == HIGH)
  {
      digitalWrite(vyhazovani, HIGH);    // retract the fourth pneumatic cylinder
  }

  // sensors - HIGH - light on, LOW - light off,
  // pneumatic cylinders - HIGH - retracted, LOW - extended.
}

This is what I refer article. But, the language may be barrier for you to read. There is an alternative method this article's author mentions a library, TimeAction.h. The library has the same method as I mentioned. You can google it. Otherwise, the "interrupt controlling" about Arduino you may interest. Please refer to the relative articles. I don't know your practical hardware architecture. Here just want to provide what I know information for you. Hope these are helpful. TimeAction.h
[interrupt contrlling](https://www.arduino.cc/en/

If you're using multiple conditions, i.e. &&, you need to watch the parentheses.

this code works - please define "works". What actually happens?

can i get your configuration on board. I am designing same project but with single solenoid valve.
Please share your Circuit configuration if possible.

void loop() {

...

  if(digitalRead(dvereVysunute) == HIGH && digitalRead(davkovaniZasunute) == HIGH
  )
  {
      digitalWrite(davkovani, LOW);      // extend the second pneumatic cylinder
      delay(4000);
      digitalWrite(davkovani, HIGH);    // retract the second pneumatic cylinder after 4 seconds,
      // this code works when it is alone there, the next if statements not
  }

...
}

If the condition is met, then davkovani is going to be LOW 99.999% of the time. It will only briefly go HIGH, as there is no delay there. The loop will iterate and set it LOW again. So it may seem to be "not working" whereas the problem is that it "works" very briefly.

Why the delay doesn't work there?

The delay works, but you need two delays. You need: LOW / delay / HIGH / delay if you are going to have any hope of noticing the HIGH state.

Hi~ The synchronized method is below. The function millis() you can refer Arduino.org. It is a function to show you current time. Here I use it to create a time interval to run synchronization.
Declaration the variables are below:
/* Declaration time interval variables for synchronizing pneumaticValve1 and pneumaticValve2. The interval is 1000ms.  */
long perviousTimepneumaticValve1 = 0;
long perviousTimepneumaticValve2 = 0;
long previousTimeLocal = 0;
long interval = 1000;

The loop() function is below:
void loop() {
checkPneumaticValve1();
checkPneumaticValve2();
}

void checkPneumaticValve1() {
  if (millis()-previousTimeLocal>interval) {
    printPneumaticValve1();
    previousTimeLocal=millis();
   }
 }

void printPneumaticValve1() {
     //Here write your code for PneumaticValve1
   }

void checkPneumaticValve2() {
   if (millis() - previousTimeLocal > interval) {
     printPneumaticValve2();
     previousTimeLocal=millis();
   }
  }

void printPneumaticValve2() {
  //Here write your code for PneumaticValve2
  }

Neither of the ways doesn't work.

Your code's variable names must be meaningful. You mention "2 magnetic sensors (when the pneumatic cylinder is retracted and extended)"-I guess it is solenoid valve. I hope I don't guess wrongly. This help us to understand your code. Otherwise, do you have any procedure diagram-it is like square and prismatic shape to illustrate your programing and its sequence.

Yeah, they are solenoid valves. You're right.

Hello,
Sorry for that I just see you have comment on this program, so I review the code. Otherwise, I have a bit longer not to contact Arduino. What I say it's just for a reference. I wish I can help you.

Hello, Sorry for that I just see you have comment on this program, so I review the code. Otherwise, I have a bit longer not to contact Arduino. What I say it's just for a reference. I wish I can help you. Your evert statements are all clear. The problem you mention it's on loop function. I see on No.4 if  statement the "dvere"  this pneumatic valve is extended. But, the No.1 if statement is already on LOW to extend. I also see in No.4 statement you add a logical operation on "lisovaniZasunute" this sensor if it is "HIGH" level. No.3 and No.4 if statement are same description on its writing.

I continue to say that the No.3 and No.4 statement is same as its condition.
if(digitalRead(dvereVysunute) == HIGH && digitalRead(davkovaniZasunute) == HIGH && digitalRead(lisovaniZasunute) == HIGH){}
Do you want to use a nest loop to write your code? The No.5 and No.6 are similar to NO.3 and No.4..

Yeah, in the if statement no. 4 should be HIGH, because I need retract the pneumatic valve. Statements no. 5 and no. 6 aren't the same. The last operation is different there.

Sorry I miss the last item. No. 5 and No. 6 are different. No. 4 and No. 3 are the same. You can combine them together. You can combine No. 5 and No. 6 together also.
if(digitalRead(dvereZasunute) == HIGH && digitalRead(davkovaniZasunute) == HIGH && digitalRead(lisovaniZasunute) == HIGH) {
if (digitalRead(vyhazovaniZasunute) == HIGH)
digitalWrite(vyhazovani, LOW);
if (digitalRead(vyhazovaniVysunute) == HIGH)
digitalWrite(vyhazovani, HIGH);}
The method get rid of many codes.

Okay, thanks. But there is problem when the program go to if no. 3 the valves are extended all 3 in one moment. When I comment the rest and leave there only the if no. 1 and no. 2 it is works correctly.

Okey~
Why do you delay 4 seconds on No.2 if statement before pneumatic retract? Does this pneumatic cylinder trigger any sensors? The No.3 and NO.4 if statement are exactly same and just only different inside of their content statement. "The valves are extended all 3 in one moment," said you. Are these three valves deere, davkovani and lisovani? "I comment the rest and leave," said you. What do you want to specify "the rest" ?

Because I need to pneumatic valves "davkovani" and "lisovani" stay extended some time. If I write only the first two if statements, it works correctly, but when I write there the third condition, all 4 valves are extended at the same time. The Arduino ignore the if statements.

Hi~
The synchronized method is below.
Declaration the variable below:
long your_pneumatic_valve_1 = 0;
long your_pneumatic_valve_2 = 0;
long previousTimeLocal = 0;
long interval = 1000;
void loop()
{
checkPneumaticvalve1();
checkPneumaticvalve2();
}

Thank you, I will try it. But why the function "delay()" doesn't work there?

Hi~
The synchronized method is below.
Declaration the variables are below:
long perviousTimepneumaticValve1 = 0;
long perviousTimepneumaticValve2 = 0;
long previousTimeLocal = 0;
long interval = 1000;
The loop() function is below:
void loop()
{
checkPneumaticValve1();
checkPneumaticValve2();
}
void checkPneumaticValve1()
{
if (millis()-previousTimeLocal>interval)
{
printPneumaticValve1();
previousTimeLocal=millis();
}
}
void printPneumaticValve1()
{
//Here write your code for PneumaticValve1
}
continuing on next ~~


text:
Posting data with ESP8266 module?
I have an ESP8266 module attached to an Arduino Uno that is connected to my local network. On the network, at address 192.168.1.13, I have a nodejs/express server running on port 3000. How would I go about posting an eight digit number from the Arduino to the webserver? In my current attempts the server console isn't receiving any data when using AT+CIPSEND while connected to it.
EDIT: My Code is as follows:
     #include <SoftwareSerial.h>

const byte rxPin = 9; // Wire this to Tx Pin of ESP8266
const byte txPin = 10; // Wire this to Rx Pin of ESP8266

// We'll use a software serial interface to connect to ESP8266
SoftwareSerial ESP8266 (rxPin, txPin);

void setup() {
  Serial.begin(9600);
  ESP8266.begin(9600); // Change this to the baudrate used by ESP8266
  delay(1000); // Let the module self-initialize
  Serial.println("Sending an AT command...");
  ESP8266.println("AT+CWMODE=1");
  delay(1000);
  ESP8266.println("AT+CWJAP=\"username\",\"pass\"");
  delay(10000);
  ESP8266.println("AT+CIPMODE=1");
  delay(1000);
  ESP8266.println("AT+CIPSTART=\"TCP\",\"192.168.1.13\test\",3000");
  delay(1000);
  GetData();

}
void loop() {
 while (ESP8266.available()){
     String inData = ESP8266.readStringUntil('\n');
     Serial.println("Got reponse from ESP8266: " + inData);
  }
}
void GetData(){
  ESP8266.println("AT+CIPSEND=4");
  ESP8266.print("test");
}

and My output is this
  Sending an AT command...
Got reponse from ESP8266: AT+CWMODE=1

Got reponse from ESP8266:

Got reponse from ESP8266: OK

Got reponse from ESP8266: AT+CWJAP="surveillancevan4","7073199495"

Got reponse from ESP8266: AT+CIPSEND=4

Got reponse from ESP8266: testI

EDIT 2: I modified my code to this
    #include <SoftwareSerial.h>

const byte rxPin = 9; // Wire this to Tx Pin of ESP8266
const byte txPin = 10; // Wire this to Rx Pin of ESP8266
// We'll use a software serial interface to connect to ESP8266
SoftwareSerial ESP8266 (rxPin, txPin);

void setup() {
  Serial.begin(9600);
  ESP8266.begin(9600); // Change this to the baudrate used by ESP8266
  ESP8266.println("AT");
  delay(1000);
  ESP8266.println("AT+CIPSTART=\"TCP\",\"192.168.1.13\",3000");
  delay(20000);
  String request = "POST /test HTTP/1.0 \r\n";
  ESP8266.println("AT+CIPSEND=19");
  delay(5000);
  ESP8266.println(request);

}

void loop() {
 while (ESP8266.available()){
     String inData = ESP8266.readStringUntil('\n');
     Serial.println("Got reponse from ESP8266: " + inData);
  }
}

and now my output claims it posted successfully, but I'm still not seeing any data in my nodejs server. Here is the output:
Got reponse from ESP8266:
AT

Got reponse from ESP8266:

Got reponse from ESP8266: OK

Got reponse from ESP8266: AT+CIPSTART="TCP","192.168.1.13",3000

Got reponse from ESP8266: CONNECT

Got reponse from ESP8266:

Got reponse from ESP8266: O

Got reponse from ESP8266: busy sytes

Got reponse from ESP8266:

Got reponse from ESP8266: SEND OK

I can confirm that it is connecting to my web app because when I run the code on the module without the server running it returns an error.

Avoid "" in URL, these are not standard separators, in addition these are escape characters in C and C++ strings. Your "192.168.1.13\test\" should probably be replaced with "192.168.1.13/test\".

I think it would help us (and yourself too) if you traced the response of all AT commands sent to the ESP8266, so that we could check that all of them succeed as expected.

 ESP8266.println("AT+CIPSTART=\"TCP\",\"192.168.1.13\test\",3000");

That line is going to fail miserably for a number of reasons:

You need to provide an IP address or domain name - NOT a URL
Even if you could provide a URL this bit 192.168.1.13\test would end up, after C escaping, as 92.168.1.13        est since \t is a TAB character.

And then on top of all that I assume you are connecting to a HTTP server, yet you aren't sending a HTTP request, you are just sending the word "test", which the HTTP server has no hope of ever understanding.
You need to formulate and send a proper HTTP request and send it to the server. I suggest you go and look at a few tutorials and maybe look up how HTTP Servers actually operate and what the protocol looks like.