Setting an array pointer to null on declaration How can I set an array pointer to null?

I have a pointer to a 3 int array that I am trying to set to null.

  int (*EXCLUSIVE_COLOR)[3];

Per this link I was trying to set it to null upon initialization.
However this does not assign a null value to it. It assigns three 'random' integers to the array elements:

  {128, 447, 451}

How can I make it point to a null or empty value?

Here is a full example that shows you all thing things you have been asking over the past few days:

int colors[][3] = {
    {255, 0, 0},
    {0, 255, 0},
    {0, 0, 255}
};

#define NCOLOR (sizeof(colors) / sizeof(colors[0]))

int *EXCLUSIVE_COLOR = NULL;

void setup() {
    Serial.begin(115200);
    Serial.print("You have ");
    Serial.print(NCOLOR);
    Serial.println(" colors defined.");
    reportColor();
    EXCLUSIVE_COLOR = colors[2];
    reportColor();
    EXCLUSIVE_COLOR = NULL;
    reportColor();
}

void loop() {

}

void reportColor() {
    if (!EXCLUSIVE_COLOR) {
        Serial.println("Color is not set");
    } else {
        Serial.print("Color is set to ");
        Serial.print(EXCLUSIVE_COLOR[0]);
        Serial.print(",");
        Serial.print(EXCLUSIVE_COLOR[1]);
        Serial.print(",");
        Serial.println(EXCLUSIVE_COLOR[2]);
    }
}

You have an array of colours. You have a pointer that can point at a colour or at nothing. It starts off pointing at nothing. The code recognises that it's pointing at nothing and reports it. It gets assigned to a specific colour in your colours array. The code recognises that it's now a valid value and reports it. The pointer then gets pointed to nothing again. Again the code recognises that and tells you.

The result:

You have 3 colors defined.
Color is not set
Color is set to 0,0,255
Color is not set


Measuring 12 V via voltage divider: choosing the right resistors I want to measure a 9 V battery via one of the analog input ports of my Arduino Nano. From all the schemes of this great answer, I choose the simplest one, the voltage divider. Assuming the maximum input voltage to be 12 V (just to be safe) and maximum divider's output voltage to be 5 V, I've solved it against R₂:R₁ proportion. It turns out that R₂:R₁ = 5:7.

simulate this circuit – Schematic created using CircuitLab

With the values above, the input of A0 pin will be exactly 5 V.

The problem is that it could be any values. 5 Ω and 7 Ω or 5 MΩ and 7 MΩ!

I understand, that there should be another equation to take into account that will give me the values of those two resistors. Another brilliant answer demonstrates, that the values depend on the current I want to flow through the branches:

  So the point is when determining the resistance of the resistors, we should take into account the input resistance of the load and the two voltage divider resistors should be as small as possible.

  On the other hand, let's compare the current going through the divider in the circuit with large resistors on the divider and the circuit with small resistors on the divider. As you can see, the large resistors have current of just 2.5 μA going through them and the small resistors have current of 25 mA. The point here is that the current is wasted by the voltage divider and if this was for example part of a battery operated device, it would have a negative impact on the battery life. So the resistors should be as large as possible in order to lower the wasted current.

9 V batteries are known to have a little of energy canned inside, with the most popular 6LR61 having only about 550 mA·h. I do not want to waste it on heating the resistors, so, probably, I need to use large resistors. But how large? Too large R₁ will let only a little current to flow to the A0 pin and I've read somewhere that small currents may lead to analogRead measurement errors (underestimations?) due to ADC's internal capacitor.

Trying to find the right answer, I've read on the Arduino's forum that:

  The ATmega328P datasheet has this info way in the back: Table 28-16 (page 328). The analog input resistance is claimed to be 100 Mohms.

  During an actual sample, the input resistance is temporarily a lot lower as the sampling capacitor is charged up so it is recommended that whatever you connect to the A/D have an output impedance of 10k or less for best accuracy.

And here, I am stuck. I understand that I am connecting a voltage divider to the A/D, but what is it's "output impedance"? It should depend on R₁ and R₂ somehow, and solving that equation (F(R₁, R₂) == 10 000) will give me the exact value…

P.S. I saw some cunning schemes in the Internet with capacitors, diodes and op-amps (everybody say it's super easy and safe to use them for this task), but, please:

I am just trying to understand the basics and making my first steps with electronics.
The device I'm making should be lightweight and compact (although I should be able to compose it without any PCB magic). Two resistors seems to be fine.
I'm going to read the voltage only once when the device is turned on, so I don't actually need super-fast op-amp's speed.
I'll try not to plug negative voltage, so I do not need a protection. Yet.

What you are looking for is called the Thévenin equivalent source.
For the schematic you are showing, and assuming you can neglect the
output resistance of the battery itself, the output resistance of the
voltage divider is the same as the two resistors in parallel. If you
want the maximum allowed resistance (minimum current) you have then to
solve:

1/R1 + 1/R2 = 1/(10 kΩ)
R2 / (R1 + R2) = 5/12

which gives:

R1 = 12/5 × 10 kΩ = 24 kΩ
R2 = 12/7 × 10 kΩ ≈ 17.1 kΩ

You can then round the values down to the closest standard values,
taking care that the rounding does not impose more than 5 V on the
analog pin. For example, if you restrict yourself to the E6 series, you
could choose

R1 = 22 kΩ
R2 = 15 kΩ

which would give you a Thévenin equivalent output resistance of
8.9 kΩ, and a maximum output voltage of 4.86 V.


Declare for loop as an array of variables My goal is to store the variable in the for loop as an array rather than as a single 'ultrasoundValue'. Can some one help me structure the code?

I have this code:

int ultraSoundSignalPins[] = {5,7};
int tx = 4;
char *pingString[] = {"Ping1 ","Ping2 "}; // just something to print to             indicate direction

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

void loop()
{

 unsigned long ultrasoundValue;
 for(int i=0; i < 2; i++)
 {
   ultrasoundValue = ping(i);
   Serial.print(pingString[i]);
   Serial.print(ultrasoundValue);
   Serial.print("cm, ");
   delay(500);

 }
}

//Ping function
unsigned long ping(int i)
{
 unsigned long echo;

 pinMode(ultraSoundSignalPins[i], OUTPUT); // Switch signalpin to output
 pinMode(tx, OUTPUT);
 digitalWrite(ultraSoundSignalPins[i], LOW); // Send low pulse
 digitalWrite(tx, LOW);
 delayMicroseconds(2); // Wait for 2 microseconds
 digitalWrite(ultraSoundSignalPins[i], HIGH); // Send high pulse
 digitalWrite(tx, HIGH);
 delayMicroseconds(5); // Wait for 5 microseconds
 digitalWrite(ultraSoundSignalPins[i], LOW); // Holdoff
 pinMode(ultraSoundSignalPins[i], INPUT); // Switch signalpin to input
 digitalWrite(ultraSoundSignalPins[i], HIGH); // Turn on 0pullup resistor
 echo = pulseIn(ultraSoundSignalPins[i], HIGH); //Listen for echo
 return (echo / 29.1); //convert to CM then to inches
}

You don't even have to add any lines, just modify a couple!

unsigned long ultrasoundValue [2]; //creates an array of unsigned longs of size 2

...and inside your for loop:

ultrasoundValue[i] = ping(i);

It appears you are acquiring 2 separate ultrasound values. If you'd like to store multiple sets of these 2 values, you could use a two-dimensional array:

unsigned long ultrasoundValue [10][2]; //an array of 10 pairs of long unsigned values

...and you could modify your for loop to have a pair of nested for loops:

 for (int i = 0; i < 10; i++)
 {
   for (int j = 0; j < 2; j++)
   {
      ultrasoundValue[i][j] = ping(j);
      //do whatever else
   }
 }


Volatile variable not updating from timer ISR I know this is a problem that has come up many times but I can't seem to get this code fragment to update the count variable on an ATMEGA328P. I am using an Arduino Uno as a development board, with the LED on pin 13 set to flash for debugging. I have confirmed the timer and LED part work by toggling port B pin 5 in the ISR routine.

#include <avr/io.h>
#include <avr/interrupt.h>

volatile uint8_t count;

void init_100us_tick(void) {
    TCCR0A = _BV(WGM01) | _BV(WGM00);       // WGM mode 7 with OCRA as top
    TCCR0B = _BV(WGM02) | _BV(CS01);        // CLK / 8 prescaler
    TIMSK0 = _BV(OCIE0B) | _BV(TOIE0);      // Interrupt enabled on OCR0A
    OCR0A = 200;                            // 16 MHz / 8 / 200 = 100 us
    sei();                                  // Enable interrupts
}

ISR(TIMER0_COMPB_vect) {
    count++;
}

int main(void) {
    DDRB |= _BV(DDB5);                      // PB5 output
    init_100us_tick();                      // Initialise 100 us tick
    count = 0;                              // In case of micro reset

    for (;;) {
        if (count >= 100) {                 // Every 10 ms
            count = 0;
            PORTB ^= _BV(DDB5);             // Toggle PB5
        }
   }
   return 0;
}

This is being compiled and burned to an Arduino Uno with the following:

avr-gcc -Os -DF_CPU=16000000UL -mmcu=atmega328p -c -o test.o test.c
avr-gcc -mmcu=atmega328p test.o -o test
avr-objcopy -O ihex -R .eeprom test test.hex
avrdude -F -V -c arduino -p ATMEGA328P -P /dev/ttyUSB0 -b 115200 -U flash:w:test.hex

I have tried disabling the optimisation with no effect. AVR-GCC is version 4.9.2

You want CTC mode for that to work. As in:

#include <avr/io.h>
#include <avr/interrupt.h>

volatile uint8_t count;

void init_100us_tick(void) {
    TCCR0A = _BV(WGM01);       // CTC mode 2 with OCRA as top
    TCCR0B = _BV(CS01);        // CLK / 8 prescaler
    TIMSK0 = _BV(OCIE0B) | _BV(TOIE0);      // Interrupt enabled on OCR0B
    OCR0A = 200;                            // 16 MHz / 8 / 200 = 100 us
    sei();                                  // Enable interrupts
}

ISR(TIMER0_COMPB_vect) {
    count++;
}

int main(void) {
    DDRB |= _BV(DDB5);                      // PB5 output
    init_100us_tick();                      // Initialise 100 us tick
    count = 0;                              // In case of micro reset

    for (;;) {
        if (count >= 100) {                 // Every 10 ms
            count = 0;
            PORTB ^= _BV(PORTB5);             // Toggle PB5
        }
   }
   return 0;
}

That toggles every 10 ms.

(Edited to add)

The PWM mode you chose will work providing you enable the correct interrupt. This also outputs 10 ms pulses:

#include <avr/io.h>
#include <avr/interrupt.h>

volatile uint8_t count;

void init_100us_tick(void) {
    TCCR0A = _BV(WGM01) | _BV(WGM00);       // Fast PWM mode 7 with OCRA as top
    TCCR0B = _BV(WGM02) | _BV(CS01);        // CLK / 8 prescaler
    TIMSK0 = _BV(OCIE0A);                   // Interrupt enabled on OCR0A  ***
    OCR0A = 200;                            // 16 MHz / 8 / 200 = 100 us
    sei();                                  // Enable interrupts
}

ISR(TIMER0_COMPA_vect) {                    // Compare A vector ***
    count++;
}

int main(void) {
    DDRB |= _BV(DDB5);                      // PB5 output
    init_100us_tick();                      // Initialise 100 us tick
    count = 0;                              // In case of micro reset

    for (;;) {
        if (count >= 100) {                 // Every 10 ms
            count = 0;
            PORTB ^= _BV(PORTB5);           // Toggle PB5  ***
        }
   }
   return 0;
}

Changed lines indicated by ***

Note that you should not have enabled _BV(TOIE0) because you have no interrupt handler for Timer 0 overflow. Without an interrupt handler the compiler probably generated code to jump to the reset vector.

The interrupt occurs when the timer matches the Compare A amount (not Compare B) so you need an interrupt on the A side.


Why my code isn't working? I wrote this code, but it doesn't work (what I want is that the program choose a random color and turn on or off an RGB led) I use transistors to turn the led strip on or off and analogWrite(pin, random(0, 255) doesn't work
int red = 11;
int green = 10;
int blue = 9;

int color = 1;
int stat = 1;

void setup() {
pinMode(red, OUTPUT);
pinMode(green, OUTPUT);
pinMode(blue, OUTPUT);
}

void loop() {
  color = random(1, 3);
  stat = random(0, 1);

  if (color == 1 and stat == 0) {
    digitalWrite(red, LOW);
  }

  if (color == 1 and stat == 1) {
    digitalWrite(red, HIGH);
  }

  if (color == 2 and stat == 0) {
    digitalWrite(green, LOW);
  }

  if (color == 2 and stat == 1) {
    digitalWrite(green, HIGH);
  }

  if (color == 3 and stat == 0) {
    digitalWrite(blue, LOW);
  }

  if (color == 3 and stat == 1) {
    digitalWrite(blue, HIGH);
  }

  delay(1000);

}

From Arduino reference: random
In short:

Syntax
random(max)
random(min, max)
Parameters
min: lower bound of the random value, inclusive (optional).
max: upper bound of the random value, exclusive.
Returns
A random number between min and max-1. Data type: long.

Basically your first random returns values {1,2} and second one is even better {0}


Why does the battery eliminator connected to the wall provide a better spin to my dc motors than my battery of the same voltage? Using a H-bridge, I've connected my DC Motors to an Arduino. When I accept the external power source from a wall, using a 9V battery eliminator, the motors spin well and consistently. However, when I connect it to a 9V battery, the motors spin slower, and the speed deteriorates till the motors stop. This happens in approximately 5 minutes. I checked with multiple 9V batteries of the same type. I have tested the batteries to check if they're dead after the motors stop. They are not, and if I reconnect the motors to them, the same process occurs all over again. I have checked for short circuits, and there are none. Any possible ideas as to why this is happening?

First off, never use 9V batteries to power motors or any device that consumes more than a few hundreds mA. Those batteries are just too weak.

Now a battery eliminator is not a pure equivalent as it can typically supply 800 mA or more, depending on the model you get.

The only commonalities between the battery and the eliminator are the 9V voltage and the socket.

If you want to power DC motors with batteries then rather use several 1.5V batteries in series.


How does Peggy2 drive rows with 74HC154 Decoder? Trying to program Evil Mad Scientist's Peggy 2 board without their Library.
The board drives a LED Matrix with

Source  74HC154 Decoder
Sink    STP16CPSO5  LED Sink Driver

Schematic

What has me confused is the 74HC154 Outputs can only have one output set to Low at at time. See table below. This means all but one row is "on". Isn't this backwards?  Shouldn't all outputs be low except one that is high?  Selecting what row you want on, rather than selecting what row you want off.  It looks more like the 74HC154 is a Sink.  Thanks.

If you look into the datasheet of 74HC154, you can see that each output has an Active Low State. Also in the schematic, the leds row part use a pnp transistor (see page two). As so, they will be active if the input is low.

  This means all but one row is "on". Isn't this backwards?

Since they are PNP, the only active row is the one with Low value and the current of that row is sink through the selected column(s) in the STP16CPS05


Following on ESP8266 Board pins, how do they map on the motor shield? Here is the answer: All pins corresponding to the G row are connected to ground. All Pins corresponding to the V row are connected to NodeMCU's 3V3 pin.

D row pins tagged from 0 to 8 correspond to NodeMCU's D1-D8 pins. D row pins tagged with SD2, SD3 corresponds to NodeMCU's SD2, SD3 pin
UTART/SPI section:

Tags corresponding to the pins are self explanatory.
Near the white-colored power switch we have a pin called "AD". I couldn't figure how this motor shield's "AD" pin is interfaced to NodeMCU. Do you have any idea?

Following on Basic Question - ESP8266 Board Pins, I can't seem to map the pins on its motor shield to software (the ones named UART/SPI, the GPIOs and the Analog Inputs). See the third image, with a NodeMCU installed.

The GPIOs seem to conflict with the motors on Arduino, and I have no idea what to do here. Documentation is pretty much useless.

You see the pins marked PWMA, PWMB, DA and DB? Those are the pins that control the motors (PWMx is the speed, Dx is the direction). Whatever pins on your ESP8266 board plug into those holes are the pins you need to use in your code. How those pins map to names and numbers in the Arduino API depends entirely on what the board is you're plugging in and what the author of the board definition files was thinking at the time.

In short, look at your board (which we cannot see) and see what GPIO pins are in the same location as the pins I pointed out. Then control those pins in your software.


What happens if there is a runtime error? What happens if there is a runtime error in a program? Will execution of the program just stop? Is there some way I can get the Arduino to tell me what the error is?

First, let's see a few examples of what can go wrong.

Uninitialized local variables

void setup() {
  int status;
  pinMode(13, OUTPUT);
  digitalWrite(13, status);
}

As pointed out by Edgar Bonet in the comments, local variables like status in the code above are not implicitly initialized by the C++ compiler. So, the outcome of the code above is indeterminate. To avoid that, make sure you always assign values to your local variables.

Things are a bit different with global and static variables:

  Global and static variables are guaranteed to be initialized to 0 by the C standard.

Source:
AVR Libc Reference Manual - Frequently Asked Questions - Shouldn't I initialize all my variables?

That means you shouldn't worry about initializing them to 0 in your code. In fact, you should really avoid it, as the initialization may waste memory. Only initialize them to values other than 0.

Memory overflow

int array[10];
int v = array[100];
array[-100] = 10;

The first problem here is that you don't know what will be assigned to v, but worse is that you don't know what you messed up with the assignment to position -100 of array.

Jump to an illegal instruction

void doSomething( void ) {
    for (int i = 0; i < 1000; i++);
}

void setup ()
{
    void (*funcPtr)( void );

    funcPtr = &doSomething;
    funcPtr(); // calls doSomething();

    funcPtr = NULL;
    funcPtr(); // undefined behavior
}

The first call to funcPtr() will actually be a call to doSomething(). Calls like the second one may lead to undefined behavior.

Other bad things that may happen

Well, you can run out of RAM, for example. What else. In any case, I think your program will keep running, probably not the way you intended it to.

Kinds of Protection

In computer systems, problems like these are usually dealt with at various levels:

By the compiler
By the programming language runtime (as in Java for example).
By the operating system or the processor (if your memory access a position outside the boundaries of the address space reserved to your program, the OS or the processor may have safety mechanisms to prevent that)

Arduinos only have limited protection of the compiler, and probably nothing else. The good news is that they aren't multi-tasked, so the only program being affected is yours. In any case, any of those bugs will lead to erratic behavior.

The Answers

The assumptions are the all of the problems I stated above are runtime problems.

  What happens if there is a runtime error in a program?

The program will continue and what happens will depend on the side-effects of the runtime error. A call to the null function pointer will probably make the program jump to an unknown location.

  Will execution of the program just stop?

No, it will keep going as if nothing extraordinary happened, probably doing what you didn't intend it to do. It may reset or act erratically. It may turn some inputs into outputs and burn a sensor or two (but that's highly unlikely).

  Is there some way I get the Arduino to tell me what the error is?

I don't think so. As I said earlier, the protection mechanisms aren't there. There's no runtime support from the language, no OS, no hardware checks for out-of-bounds memory access (the bootloader doesn't count as either). You just have to be careful with your program and probably set your own safety nets.

The reason for the lack of protection is probably because Arduino controllers are too cheap, have too little memory, and should not run anything too important (yes, there seems to be a disclaimer by AVR somewhere for you not to use the MCUs normally used by Arduino in life support systems).


ESP8266 spend 10mA, even though It is in the deep sleep mode I am using Nodemcu ESP8266. I want to know how much my ESP board consume the battery during sleep mode.
as the Mannual said it spend about micro-ampere, but my multi meter said it spend 10 mili-ampere, I cannot believe the result.

so please see My arrangement is right and give some advice

arrangement image

red line is for vin, black line is for GND.
black pin is COM, red pin is mA.

I set multimeter on 20mA, 200mA, it said it is 10mA.
when I change multimeter to 10mA, 1mA, microAmpere, number was overflowed.

I already connected to RST - D0, so It is properly sleep & wake up automatically. and here is my running code in the board

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <EEPROM.h>

void setup() {

}

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

ESP.deepSleep(60e6);

}

ESP.deepSleep(60e6, WAKE_RF_DEFAULT); Try this code, it should decrease it a bit.


Arduino Uno not including two header files at the same time I have an Arduino Uno and I am trying to control a stepper motor with it. I also have an RF transmitter and receiver (433MHZ). I need to transmit data about motor status.

For RF I am following this page. Individually both are working great. I am able to send data from one Arduino (TX) to another (RX). And also I am able to control the motor. But when I am merging these projects, their header files are giving an error.

For RF, I need to include #include <RH_ASK.h> and for the motor I need include #include <Servo.h>. When I am including these headers files, they are giving me this error:

Arduino: 1.8.1 (Windows 10), Board: "Arduino/Genuino Uno"

libraries\RadioHead\RH_ASK.cpp.o (symbol from plugin): In function `RH_ASK::maxMessageLength()':

(.text+0x0): multiple definition of `__vector_11'

libraries\Servo\avr\Servo.cpp.o (symbol from plugin):(.text+0x0): first defined here

collect2.exe: error: ld returned 1 exit status

exit status 1
Error compiling for board Arduino/Genuino Uno.

I do not know what's wrong here. Can anyone please help me?

First of all, that page has a link to an old version of the RadioHead library.
This is a link to RadioHead: www.airspayce.com/mikem/arduino/RadioHead. You will find the newest library on that page.

The Servo library uses TIMER1.
The RadioHead in RH_ASK mode uses TIMER1.
Both use the same interrupt of TIMER1. That is what the compiler is trying to tell you with: "multiple definition of _vector_11".

You could move one of them to TIMER2.
There are alternative Servo libraries that use TIMER2.
The RadioHead can set a define for TIMER2. The explanation is in the library files in RH_ASK.h, you have to set "#define RH_ASK_ARDUINO_USE_TIMER2" in RH_ASK.cpp.

Why are you using the Servo library for a stepper motor ?


TMP36 probe reading 0 on analog I've designed this system which is supposed to turn on the LEDs when the temperature of a particular probe exceeds 32 degrees. From what I can tell, this should be functional but the analog sensor is always reading 0 when calling analogRead() on the pin.

Here is an image of my circuit:

and my code:

int length = 5;
float airTemp = 32;

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

void loop()
{
  // loads current temperature into array
  int reading;
  float voltage;
  float temp[length];
  for (int i = 0; i < length; i++)
  {
    reading = analogRead(i);
    Serial.print(reading);
    voltage = reading * 5.0;
    voltage /= 1024;
    temp[i] = (voltage - 0.5) * 100;
  }

  // turns on/off fans based on current temperature
  for (int i = 0; i < length; i++)
  {
    pinMode(i, OUTPUT);
    if (temp[i] > airTemp)
    {
      digitalWrite(i + 8, HIGH);
    }
    else if(temp[i] <= airTemp)
    {
      digitalWrite(i + 8, LOW);
    }
  }
  delay(1000);
}

I learned how to read the temperature from here. It's probably a dumb mistake, but I just started working with Arduino yesterday and I couldn't find information anywhere so thanks in advance.

The image on the linked tutorial has the middle pin of the TMP036 going to the analog input, whereas you have it going to 5V, so that is not going to help one bit.

In other words, it is wired wrongly.


How to properly process large arithmetic just a question that requires a simple answer. How do I process a large number of arithmetic steps in arduino efficiently and precisely?

For example I have this code function setup:

void calc() {
  batterymoment = input*batterymass;
  totalmoment = 149650+batterymoment;
  buoyancymoment = buoyancymass*centrebuoyancy;
  wheelmoment = totalmoment - buoyancymoment;
  wheelweight = totalmass - buoyancymass;
  cgwheels = wheelmoment/wheelweight;
  maindistance = mainarm - wheelweight;
  nosedistance = wheelweight - nosearm;
  mainmass = (((wheelweight)*(1-((maindistance)/(maindistance+nosedistance))))/2);
  nosemass = (((wheelweight)*(1-((nosedistance)/(nosedistance+maindistance))))/2);
  mainmoment = mainmass*mainarm;
  nosemoment = nosemass*nosearm;
  netmoment = buoyancymoment+mainmoment+nosemoment;
  netcg = netmoment/totalmass;
  staticmargin = adc - netcg;
  answer = staticmargin/meanadc;

}

Now I've properly setup up data types for all of these variables and they are a combination of float, int and long. I don't think it's a problem with the data type. What I'm getting when I print final answer in the serial is the same number regardless the input the user enters.

I'm guessing I need to format the code in such a way that it performs each line step by step and verifies the answer before proceeding to the next arithmetic line. If so would I need a function for each arithmetic step? Or is there a simpler way to process this that I'm missing.

Any guidance is appreciated. Thanks.

Here is the code in its entirety:

unsigned long batterymoment,num1,num2,input,totalmoment;
double buoyancymoment,wheelmoment,cgwheels,mainmass,nosemass,maindistance,nosedistance;
double mainmoment,nosemoment,netmoment,netcg,staticmargin,answer;
double centrebuoyancy = 14.164;
double mainarm = 14.3;
double adc = 11.4;
double meanadc = 22.65;
double nosearm = 1.8;
int totalmass = 12404;
int batterymass = 720;
int buoyancymass = 4401;
int batteryposition,wheelweight;
boolean mySwitch = false;

void calc() {
  batterymoment = input*batterymass;
  totalmoment = 149650+batterymoment;
  buoyancymoment = buoyancymass*centrebuoyancy;
  wheelmoment = totalmoment - buoyancymoment;
  wheelweight = totalmass - buoyancymass;
  cgwheels = wheelmoment/wheelweight;
  maindistance = mainarm - wheelweight;
  nosedistance = wheelweight - nosearm;
  mainmass = (((wheelweight)*(1-((maindistance)/(maindistance+nosedistance))))/2);
  nosemass = (((wheelweight)*(1-((nosedistance)/(nosedistance+maindistance))))/2);
  mainmoment = mainmass*mainarm;
  nosemoment = nosemass*nosearm;
  netmoment = buoyancymoment+mainmoment+nosemoment;
  netcg = netmoment/totalmass;
  staticmargin = adc - netcg;
  answer = staticmargin/meanadc;
 }

void setup() {
  Serial.begin(9600);
  num1=0;
  num2=0;
  Serial.println("Enter battery position");
 }

void loop() {
  while (Serial.available()){
    batteryposition = Serial.read();
    if(batteryposition>47 && batteryposition<58){
      if(!mySwitch){
         num1=(num1*10)+(batteryposition-48);
      }else{
         num2=(num2*10)+(batteryposition-48);
        }
       }

if(batteryposition==61){
  input=num1+num2;
  calc();
  Serial.print("Static margin is: ");
  Serial.println(answer);
  num1=0;
  num1=0;
  mySwitch=false;
  }
 }
}

So depending on the user input, the calculations will change the final output answer. For example if a 5 should be entered the output should be -4.22 based on my calculations in excel.

You're getting the same value every time because that is the value that is being calculated.

I think you have something wrong with how you have implemented your formula.  If you start from "answer = " and repeatedly substitute the variables with the formulae or values that make up those variables you end up with this:

  answer = (11.4 - (((4401 * 14.164) + ((((12404 - 4401)*(1-((14.3 - (12404 - 4401))/((14.3 - (12404 - 4401))+(12404 - 4401 - 1.8)))))/2) * 14.3) + ((((12404 - 4401)*(1-((12404 - 4401 - 1.8)/((12404 - 4401 - 1.8)+(14.3 - (12404 - 4401))))))/2) * 1.8)) / 12404)) / 22.65

There's nothing variable about that at all.

Your input value is being used to calculate batterymoment. batterymoment us being used to calculate totalmoment. totalmoment is being used to calculate wheelmoment. wheelmoment is being used to calculate cgwheels. cgwheels is never used for anything.


Is there a counter library in Arduino? I'm looking for a counter that can be incremented and will overflow with predictable behavior, preferably reset to 0 on overflow. I've tried using integers for counting but I'm getting weird overflow issues. Is there some library that provides an implementation of a counter?

Since you dont give the largest number your counter over flows at. You may want to look at libraries that implement arbitrary size integers. This means that there the integers can be bigger than usual - You would need to implement a counter, reset to 0 if the integer gets too big (just use a if statement if what youre doin is that simple-it sounds like it). So its entirely predictable for your purpose (whatever that is you didnt state). If you google around you will find libraries for arbitrary large integers for arduino e.g.

https://forum.arduino.cc/index.php?topic=85692.0

a library by Nick Gammon.


Can I connect an output pin to an input pin to measure it's voltage on a single board? So just bought an arduino Uno and I've been playing around with it. I want to connect one of the input pins to one of the PWM outputs and measure the output from there by sending it to my computer through Serial and then plot it in python.

Sorry if this is a basic question.
Thanks

PWM are digital output pins, and it seems that you wish to measure analog equivalent voltage generated by PWM output. If so, you'd need a filter.

Construct a unity gain op-amp based RC filter with cut-off frequency significantly smaller than PWM clock frequency. This will generate a analog waveform that can drive analog circuits. You could connect this to ADC input pin.

You could Google "Active low pass filter" for a lot of schematics and formula.

BUT

To be able to faithfully reproduce analog signal captured through ADC on a computer screen graph, your ADC sample rate must be more than ~2.5 times analog signal's bandwidth.

If your sample rate is close to Nyquist rates,  you'd need to filter (interpolate) your digitized signal in software to generate a smooth graph. This is a bit involved in maths and software. Otherwise you'd only get a "spikey" waveform.

Or preferably have a sample rate > 10 times analog bandwidth. This will give large enough sample counts to reliably show analog data without much processing.


How to connect Wi-Fi shield ESP-12E-ESP8266-UART-WIFI-Wireless-Shield with Arduino I have bought this shield from ebay and now I don't know how to use it, ESP 12E ESP8266 UART WIFI Wireless Shield for Arduino UNO R3 Bouclier Sans filfr:

There are no instructions in the box or anywhere on internet for this board. The only description I found everywhere is this:

  Description:

  Standard pin interface to achieve full compatibility with the pitch Arduino Uno, Mega and so on. (Unless the standard size Arduino, such
  as Nano, Mini)
  3.3V power supply using advanced chip (with the official expansion board power chip CC3000 same), so 3.3V Arduino board provided more
  accurate, so ESP8266 as official CC3000 chip work as normal, there is
  no gap.
  It leads to a WiFi module power supply / service interface to facilitate developers to extend the power supply and maintenance.
  Onboard ESP8266-12 stable industrial grade serial WiFi module, using an enhanced PCB antenna, signal better.
  You can quickly switch DIP switch ESP8266-12 industrial grade WiFi stable operation mode (such as operating mode and upgrade mode)
  module, integrated serial chip, quickly flashing the firmware.
  Built-in 5V to 3.3V TTL level converter to prevent high-pressure Arduino TTL level of the WiFi module damage.
  Onboard ESP8266-12 stable industrial grade WiFi module with a metal shield, immunity to interference.
  Onboard ESP8266-12 standard pitch leads to a stable industrial grade WiFi module all interfaces, enabling developers to easily
  develop deep.
  Use stackable design, it can continue to accumulate above the other modules, easy to use.
  Onboard four LED displays the status of ESP8266, namely PWR, DFU, AP, STA

What should be the board settings for this?

I am new to electronics please help me how can I connect this with Arduino.

There are some fake Modules on eBay! Only after changing the wiring can you use them. The fake modules have the wrong text printed on it.

  Moer info $ tech

instead of

  More info & tech

But when you change the wiring you can use the shield!

The two transistors which are connected to Arduino board pin 0 and 1 have to disconnected. Also the connection to the switches 1 and 2 have to change. Then you can stack ESP-12 shield on the Arduino. You can now flash the Arduino Uno when you switch off (switch 1 and 2) With the old wiring you can't use it because the transistors are wrong connected.

The voltage divider is need for 3,3 V ESP-12 RX pin


Arduino Uno 3: Stuck at 'uploading...' sketches I was playing around with my Arduino Uno R3 board with Sublime Text 2 & 'Stino' as IDE
I am not sure if it is my code is the problem or if I broke something...
I pressed upload while another sketch didn't finish uploading, even the original Arduino IDE can't upload new sketches anymore!

This is my code:

// singleServo.ino

#include <Servo.h>

Servo servo;
const int button = 2;
const int led = 13;
const int buzzerPin = 10;
const int duration = 180;

int stateLED = LOW;
int previous = LOW;

void setup() {
    pinMode(led, OUTPUT);
    pinMode(button, INPUT);
    pinMode(buzzerPin, OUTPUT);
    Serial.begin(9600);
}

void loop() {
    int stateButton;

    stateButton = digitalRead(button);

    if (stateButton == LOW && previous == LOW) {
        if (stateLED == HIGH)
        {
            stateLED = LOW;
            initAction(duration);
        }
        else
        {
            stateLED = HIGH;
        }
    }

    digitalWrite(led, stateLED);
    previous = stateButton;
    servo.detach();
}

void initAction(int time_iA){
    tone(buzzerPin, 523, 200);
    delay(200);

    shiftServo(180, time_iA);

    tone(buzzerPin, 262, 200);
}

void shiftServo(int angle, int time_sS) {
    servo.attach(9);
    delay(500);
    int position;

    for(position=0; position <= angle; position += 1)
    {
        servo.write(position);
        delay(time_sS / 180);
        Serial.println(servo.read());
    }
    // for(position=angle; position >= 0; position -= 1)
    // {
    //  servo.write(position);
    //  delay(time_sS / 90);
    // }
}

I am a newbie with all things Arduino - Please help!

EDIT:
After rebooting the system (Ubuntu Linux 14.04) everything was working just fine again!But I'm going to take the serial functions out too.

You have to wait for the first and all other uploads to fail.

If you are not sure, a reboot is the most reliable solution.

Also note that if your sketch sends a lot of data over serial, a manual reset of the board may be needed.


How to do weigh scale zeroing (tare weight)? I'm using the sketch below for a weighing scale. The sketch prints out the load-cell voltage just fine. I can't figure out how to let the scale run a couple seconds to stabilize, then use the current voltage reading (nothing on the scale) as the "Zero" voltage. Then subtract that "Zero" voltage from future readings to get the actual voltage for any weight placed on the scale. For example, let's say the nothing on the scale voltage is 0.5 volts. Then a 10 LB weight is added and the voltage goes up to 1.5 volts. So the actual voltage increase from the weight is 1.5 minus 0.5, or 1.0 volts.

#include <ads1262.h>

const float VREF = 2.50;  // Internal reference

ads1262 PC_ADS1262;  // ADC object

void setup() {
  // initialize the  data ready and chip select pins:
  pinMode(ADS1262_DRDY_PIN,  INPUT);   // data ready input line
  pinMode(ADS1262_CS_PIN,    OUTPUT);  // chip enable output line
  pinMode(ADS1262_START_PIN, OUTPUT);  // start
  pinMode(ADS1262_PWDN_PIN,  OUTPUT);  // power down output
  Serial.begin(9600);

  // initialize ADS1292 slave
  PC_ADS1262.ads1262_Init();
  Serial.println("ads1262 Initialised successfully....");
}

void loop() {
  // Nothing to do unless data ready is asserted.
  if (digitalRead(ADS1262_DRDY_PIN) == HIGH) return;

  // Get a reading and convert to voltage.
  uint8_t *buffer = (uint8_t *) PC_ADS1262.ads1262_Read_Data();
  signed long reading = (uint32_t) buffer[1] << 24
                  | (uint32_t) buffer[2] << 16
                  | (uint32_t) buffer[3] <<  8
                  | (uint32_t) buffer[4] <<  0;
  float voltage = VREF / (1UL<<31) * reading;

  // Report a smoothed-out reading.
  Serial.println(voltage, 8);
}

You start out with a variable named Tare initialized to zero float Tare = 0.0; put in a conditional like if (millis() > 2000 & Tare == 0.0) Tare = voltage; and always report voltage - Tare.

float Tare = 0;

void loop() {
  // Nothing to do unless data ready is asserted.
  if (digitalRead(ADS1262_DRDY_PIN) == HIGH) return;
  // Get a reading and convert to voltage.
  uint8_t *buffer = (uint8_t *) PC_ADS1262.ads1262_Read_Data();
  signed long reading = (uint32_t) buffer[1] << 24
    | (uint32_t) buffer[2] << 16
    | (uint32_t) buffer[3] <<  8
    | (uint32_t) buffer[4] <<  0;
  float voltage = VREF / (1UL<<31) * reading;
  if (millis() > 2000 & Tare == 0.0) Tare = voltage;
  // Report a smoothed-out reading.
  Serial.println(voltage-Tare, 8);
}

If you want to make it smarter, add a button for tare and maybe if you have a calibration weight, add a button for calibrating.

float scale= 1.0;
const float calib_weight = 500.0; // grams?
...
if(tareButton | (millis() > 2000 & Tare == 0.0)) Tare = voltage;
if(calibrateButton) scale = calib_weight / (voltage-Tare) ;
...
Serial.println((voltage - Tare)*scale,8);
...


Infrared interruption counter Is it possible to create a infrared based interruption counter with an Arduino Uno? If yes, then what additional hardware would be necessary?

You can use photo any transmissive or reflective photo interrupter (wire or TH) ideally with integrated Schmitt trigger and connect to IRQ driven AVR input to have quick trigger reaction. For production is cheaper photo interrupter with external Schmitt but for prototyping it does not matter.
Don't forget serial resistor to limit current.

Search e.g. "photo interrupter Schmitt" at Farnell.


Reading states of multiple toggle switches I'm working on modifying this example from the Arduino website to read the state of 3 toggle (SPDT) switches. If I have one toggle switch hooked up, my sketch works as expected...the sketch will log the state of the switch in the serial debugger every-time the state changes, and only when the state changes.

However, if I add in two more switches, the serial debugger will continuously output my log messages, without detecting if the state has changed.

Here's the code from my sketch:

const int  switchOnePin = 2;    // digital in 2 (pin the switch one is attached to)
const int  switchTwoPin = 3;    // digital in 3 (pin the switch two is attached to)
const int  switchThreePin = 4;  // digital in 4 (pin the switch three is attached to)

int switchOneState = 0;         // current state of the switch
int lastSwitchOneState = 0;     // previous state of the switch

int switchTwoState = 0;
int lastSwitchTwoState = 0;

int switchThreeState = 0;
int lastSwitchThreeState = 0;

void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);

  int switchOneState = 0;         // current state of the switch
  int lastSwitchOneState = 0;     // previous state of the switch switch pins as an input
  pinMode(switchOnePin, INPUT);
  pinMode(switchTwoPin, INPUT);
  pinMode(switchThreePin, INPUT);
}

void loop() {

  // read the switch input pins:
  switchOneState   = digitalRead(switchOnePin);
  delay(50);
  switchTwoState   = digitalRead(switchTwoPin);
  delay(50);
  switchThreeState = digitalRead(switchThreePin);

  // compare the switchState to its previous state
  if (switchOneState != lastSwitchOneState) {
  // if the state has changed, increment the counter
    if (switchOneState == HIGH) {
    // if the current state is HIGH then the button
    // went from off to on:
    Serial.println("Switch one is on");
  }
  else {
    // if the current state is LOW then the button
    // went from on to off:
    Serial.println("Switch one is off");
  }

  if (switchTwoState != lastSwitchTwoState) {
    if (switchTwoState == HIGH) {
    Serial.println("Switch two is on");
  }
  else {
    Serial.println("Switch two is off");
  }

  if (switchThreeState != lastSwitchThreeState) {
    if (switchThreeState == HIGH) {
    Serial.println("Switch three is on");
  }
  else {
    Serial.println("Switch thre is off");
  }
 }
}
  // Delay a little bit to avoid bouncing
  delay(50);
}
// save the current state as the last state,
//for next time through the loop
lastSwitchOneState   = switchOnePin;
lastSwitchTwoState   = switchTwoPin;
lastSwitchThreeState = switchThreePin;
}

And here's what my circuit looks like:

Does anyone have any insight into what I may be doing wrong? I'm not quite sure if it's a circuit or a sketch issue (or both).

EDIT I tried adding a delay of 50ms between each digital input read, but that still did not seem to help the problem.

The problem was two pronged---both the copy/paste error that @Gerben pointed out, as well as the incorrect if-else statements that @BrettAM pointed out. Below is the working code:

const int  switchOnePin = 2;    // digital in 2 (pin the switch one is attached to)
const int  switchTwoPin = 3;    // digital in 3 (pin the switch two is attached to)
const int  switchThreePin = 4;  // digital in 4 (pin the switch three is attached to)

int switchOneState = 0;         // current state of the switch
int lastSwitchOneState = 0;     // previous state of the switch

int switchTwoState = 0;
int lastSwitchTwoState = 0;

int switchThreeState = 0;
int lastSwitchThreeState = 0;

void setup() {
    //initialize serial communication at 9600 bits per second:
    Serial.begin(9600);

    int switchOneState = 0;         // current state of the switch
    int lastSwitchOneState = 0;     // previous state of the switch switch pins as an input
    pinMode(switchOnePin, INPUT);
    pinMode(switchTwoPin, INPUT);
    pinMode(switchThreePin, INPUT);
}

void loop() {
    // read the switch input pins:
    switchOneState   = digitalRead(switchOnePin);
    switchTwoState   = digitalRead(switchTwoPin);
    switchThreeState = digitalRead(switchThreePin);

    // compare the switchState to its previous state
    if (switchOneState != lastSwitchOneState) {
        // if the state has changed, increment the counter
        if (switchOneState == HIGH) {
        // if the current state is HIGH then the button
        // went from off to on:
            Serial.println("Switch one is on");
        } else {
            // if the current state is LOW then the button
            // went from on to off:
            Serial.println("Switch one is off");
        }
    }

    if (switchTwoState != lastSwitchTwoState) {
        if (switchTwoState == HIGH) {
            Serial.println("Switch two is on");
        } else {
            Serial.println("Switch two is off");
        }
    }

    if (switchThreeState != lastSwitchThreeState) {
        if (switchThreeState == HIGH) {
            Serial.println("Switch three is on");
        } else {
            Serial.println("Switch thre is off");
        }
    }

    // Delay a little bit to avoid bouncing
    delay(50);

    // save the current state as the last state,
    //for next time through the loop
    lastSwitchOneState   = switchOneState;
    lastSwitchTwoState   = switchTwoState;
    lastSwitchThreeState = switchThreeState;
}


Generating PWM using Arduino Uno and Simulink (interfacing) pins 5 and 6. What's the maximum frequency? I am building a boost converter using a mosfet. The mosfet is driven by PWM generated by an Arduino Uno through Matlab Simulink. In Simulink I am giving 10 KHz pulse width 50%. Practically 10 KHz available at pins 5 and 6. Up to how much frequency can pins 5 and 6 handle?

See my page about timers. The maximum frequency the hardware can output is 8 MHz if you are running a 16 MHz clock.

10 kHz should be easily achievable if you tweak the hardware registers, as Gerben said.


How can i develop a fish tank automation using arduino As a part of my final year Engineering project I would like to develop a  fish tank automation system. In my project I need to check the quality  of water concurrently and also I need to check the sedimentation of my fish tank. Which are the different types of sensors  used for this?
How can i connect it to my arduno uno?

You're starting from the wrong end of the problem (the electronics).
First, you need to decide the requirements for your system.

Write down what your system is supposed to do: measure something? When & how often? Save or display the measurements? Control something based on the data? How precise must that control be (e.g. +/- .5 degC) (precision can be expensive)? Control something based on something other than measurements (except, perhaps, time?

Once you understand the requirements, then you can write down the steps the system should take to meet them; it doesn't need to be code (and probably shouldn't be, just yet).

Decide on what to measure and how to measure it. Can't figure out a sensor for something? Maybe you can infer it from something you can sense. Or perhaps learn how quickly or how often that 'something' goes out of spec and restore it without a measurement (e.g. you presumably already know how often and how much to food to dispense).

Now you can start thinking about electronics, sensors, and code, having a pretty good idea of what you will need to know, to acquire, and to create, to build your project (whether or not you'll be expected to actually build one).

This is an Engineering approach to design and it is almost certain your project is intended to show that you know how to do this, much more than to show you can run a fish tank.


Append to .h file through arduino code I'm at the stage where I can #include headerFiles.h into my arduino sketches.

I'm just beginning to wonder whether it's possible to append strings that are concatenated from integers which are analogRead from sensors to a .h file?

It'd make the arduino a lot more portable and would negate having to buy an SD card module.

How would the data be extracted? EEPROM is too small for datalogging past what you'd rack up in text over a reading every minute for a few hours.

Any clever clogs got ideas for this?

Header files are part of your source code. The result of a build is a set of ones and zeros which are sent to your arduino and written in its Flash memory (the program space). The way you put these zeroes and ones together is completely up to you. You could write C and/or C++ code (where you have header files), you could write assembly code or you could write the zeroes and one directly on the disk, if you are crazy enough.
Header and Source files live only in the world of the developer and its toolchain, Arduino doesn't know they exist at all.

That being said, if you want to store log data you could use a SD card like you said, or send it over the network, or you could use a serial connection. But I'm sure there are plenty of other options.


continuous print of button Pushed When pushing a button I want to read the value...once.
If I push(hold) the button I get a continuous print of button1Pushed
    if(button1State == LOW) {
     Serial.println("button1Pushed");
  }

But if I try to solve it like this, nothing happens, not a single print. What am I missing?
 int button1State = digitalRead(button1);
  int lastButton1State;

  if(button1State != lastButton1State){
      if(button1State == LOW){
        Serial.println("button1Pushed");
               }
        }

  lastButton1State = button1State;

lastButton1State is not initialized and therefore has no strictly defined value. In your case, it appears to have a value of 0 (which is random, it's not due to implicit initialization, which is only done for global variables). The condition if(button1State != lastButton1State) becomes true only if the button is released.
You can check that by changing
if(button1State == LOW){
  Serial.println("button1Pushed");
}

to
if(button1State == HIGH){
  Serial.println("button1 released");
}

The following should work:
int last_button_state=HIGH; // initialize to HIGH, so the button does not teigger on very first iteration
void setup () {
  // whatever you want to do here
}
void loop() {
  int button_state=digitalRead(button1);
  if (button_state!=last_button_state && button_state==LOW) {
    Serial.println("button pressed");
  }
  else if (button_state!=last_button_state && button_state==HIGH) {
    Serial.println("button released");
  }
  last_button_state=button_state;
}


NodeMCU run sensor code while listening for wifi input? Is it possible to have code running while also listening for local inputs via ip address? I thought it would go in the 'while' portion but I presume that only responses when the ip is loaded.

void loop() {

  WiFiClient client = server.available();
  if (!client) {
    return;
  }
  while (!client.available()) {
    delay(1);
  }
  String query = client.readStringUntil('\r');
  client.flush();

  if (query.indexOf("/open") != -1)  {
    open_fast();
  } else if (query.indexOf("/close") != -1)  {
    close_fast();
  }

  sensor = analogRead(A0);
  sensor = map(sensor, 0, 1023, 0, full);

  Serial.print(sensor);
  Serial.print("  ");
  Serial.println(pos);

  if (sensor > pos) {
    open_slow();
    delay(1000);
  } else if (sensor < pos) {
    close_slow();
    delay(1000);
  }
  delay(100);

}

The problem is that at

while (!client.available()) {
  delay(1);
}
// your wifi code

you wait for a wifi event and in that time you obviously can't read the sensor. Just poll for incoming requests by doing it like

if (client.available()) {
  // your wifi code
}

This way your loop skips the wifi-routine if there is nothing to do and proceeds with reading the sensor.

As mikrocontrollers usually don't run a OS, you don't have multitasking which you have to implement yourself.
Generally you have to avoid using delay loops when you want several tasks being executed "parallely".


Basic Serial Transmission Protocol I have a small piece of code here that I hope to run on Arduino. Basically what this code is doing is, it takes a nibble from the user, appends a startbit to it, and transmits the code through a transmitter module. The receiver end receives the bits and checks if startbit is being received. If startbit is not being received, then it prints out whatever was transmitted. If startbit is received, then it doesn't print the startbit, just the nibble all in one line.

My question is: is it convention/clever to use the bool array or should I not do that? Second, is there a way to make my code more efficient? Where can I clean it up? Also, is my code legible or very convoluted?

#include <Arduino.h>
#include <WirelessComm.h>

int tx_pin;
int rx_pin;
WirelessComm::WirelessComm(int rxPin, int txPin)
{
    pinMode(rxPin, INPUT);
    tx_pin = txPin;
    rx_pin = rxPin;
}

int countDigit(long n)
{
    int count = 0;
    while (n > 0)
    {
        n /= 10;
        count++;
    }
    return count;
}

void getDigit(bool *data, long num)
{
    int cd = countDigit(num);
    long shift = 1;
    for (int i = 0; i < cd; i++)
    {
        data[i] = (num / shift) % 10;
        shift *= 10;
    }
}

int WirelessComm::writeTx(long nibble)
{
    int i;
    bool data[11]; // warning: I didn't check for buffer overrun!
    int32_t startBit = 110101L; // larger than 32767, so cannot be in int
    if(nibble != 0)
    {
        int sbLen = countDigit(startBit);
        for (int i = 0; i < (int)(sizeof(data) / sizeof(data[0])); i++)
            data[i] = 0;
        getDigit(data, startBit);
        getDigit(data + sbLen, nibble);
    }
    else
        return -1;

    for(i = 0; i < 10; i++)
    {
        if(data[i] == 1)
        {
            digitalWrite(tx_pin, HIGH);
        }
        else
        {
            digitalWrite(tx_pin, LOW);
        }

    }
    return 1;
}

int WirelessComm::readRx(long nibble)
{
    bool first = 0;
    bool second = 2; //initially set to some random value
    bool third = 2;
    bool fourth = 2;
    bool fifth = 2;
    bool sixth = 2;
    bool counter = 0;
    bool val = 0;
    while(true)
    {
        first = digitalRead(rx_pin);
        if(first == 1);
        {
            second = digitalRead(rx_pin);
            if(second == 1)
            {
                third = digitalRead(rx_pin);
                if(third == 0)
                {
                    fourth = digitalRead(rx_pin);
                    if(fourth == 1)
                    {
                        fifth = digitalRead(rx_pin);
                        if(fifth == 0)
                        {
                            sixth = digitalRead(rx_pin);
                            if(sixth == 1)
                            {
                                while(counter < 4)
                                {
                                    val = digitalRead(rx_pin);
                                    Serial.print(val);
                                    counter++;
                                }
                                Serial.println();

                            }
                            else
                                Serial.println(first);
                                first = digitalRead(rx_pin);
                        }
                        else
                            Serial.println(first);
                            first = digitalRead(rx_pin);
                    }
                    else
                        Serial.println(first);
                        first = digitalRead(rx_pin);
                }
                else
                    Serial.println(first);
                    first = digitalRead(rx_pin);
            }
            else
                Serial.println(first);
                first = digitalRead(rx_pin);
        }
        else
            Serial.println(first);
            first = digitalRead(rx_pin);
    }
}

What you are doing is called "bit-banging" (wikipedia link) but you have no guarantees about the timing of your bits.

In your writeTx routine you are changing tx_pin at some rate which depends on:

the clock speed of your MCU
the code that the C compiler generates

Moreover, the timing will be all screwed up if you happen to get an interrupt while sending the bits.

The same applies to your read routine.

The Arduino (really the Atmel MCU) has special hardware to perform both synchronous and asynchronous serial IO. The set up is rather complex because the hardware
is very versatile and capable of a lot of different functions.
In particular, it can deliver the bits at a specific baud rate for you so your code doesn't have to do it. It can also read in a serial stream and set a flag or invoke an interrupt when a complete word has been received.

This article can give you an idea of what the USART in an Atmel processor is capable of:

http://maxembedded.com/2013/09/the-usart-of-the-avr/


How to add the Wiring S board to Arduino IDE v.1.6.2? My Arduino Uno is running out of memory to support my script (yes, I've tried several ways of optimize it already: PROGMEM, EEPROM, no Strings, and so on), so I would like to upload my script to my Wiring S board.

However, instead of "porting" all libraries to Wiring, I would like to compile my script in Arduino IDE and upload it to my Wiring S. It used to be "easy" in Arduino v.1.0.x. because somwhere I got a Wiring folder (containing, among other things, a boards.txt file) and copied it to Arduino's hardware folder getting the Wiring S board listed in Arduino IDE.

Since Arduino 1.5 the specification for adding other boards changed. I'd say it's more complex now. I simply cannot understand most of the new specification (yes, I'm new into electronics), so I haven't been able to add my Wiring S board.

Running my script in Arduino 1.0.x doesn't seem to be an option, since it throws lots of errors (although the script compiles in Arduino 1.6.2).

Do you have any experience adding other boards (like Wiring S) to Arduino IDE? Could you please give me some hint?

There are two things I do; I use the Serial.print(F("string/n")); which prints the data from flash rather then copying it to ram.  Keep as many of your variables local as possible, that will save ram.  This is done by defining then in the function, the added advantage nothing outside the function can change them.

Global and Static variables are the first things loaded into SRAM. They push the start of the heap upward toward the stack and they will occupy this space for all eternity.

Variables created in functions, are dynamically allocated objects and data. Unlike Global and Static variables, these variables can be de-allocated to free up space at function exit. But Every function call creates a stack frame that makes the stack grow toward the heap. This data is usable within the function, but the space is 100% reclaimed when the function exits!


Ideal settings for regulated power using Arduino Uno VIN? Is there a downside to providing a lot of amps to Arduino UNO's VIN? Is there any advantage to only supplying a limited amount of amps? I have a regulated power supply and I'm curious what I should set it to when going through the 5v port?

Also, should I stick with 5 volts? I've seen some tutorials say if powering the board through VIN it should ideally be much more than that?

Is there a spec sheet of sort that tells you this?

Honestly, it doesn't matter how much power (amps) you make available, it will only draw what it needs.

However, there is definitely something to be said for limiting how much power you provide.  If something in your circuit is miswired or otherwise shorts out, limiting the circuit to something reasonable (wisely including a fuse in your design as well) means that you won't have some enormous current suddenly passing through burning stuff out and possibly injuring someone. :)

As far as what to provide in terms of volts and amps, the data sheet for your particular arduino is the place to go.  As long as you are providing that you are in good shape.


Can I use two sensors with different baud rate without problems on arduino? One sensor has a baud rate of 115200, the other 9600. I think this will create problems in the serial because I can only choose one baud rate.

What do you think?
The first sensor is the pulse sensor, while the other is the gsr sensor by grove.
Link: http://pulsesensor.com/
Link 2: http://www.seeedstudio.com/wiki/Grove_-_GSR_Sensor

You can only have one sensor on one serial port, and the baud rate is set on the serial port.

So as long as you have two serial ports, or SoftwareSerial ports (I wouldn't, it causes more problems that it solves - get a board with multiple UART interfaces) then yes you can have two baud rates.


Maintaining time in Arduino I am working on development of alarm clock using Arduino.

No doubt RTC will be the best but it increases the Price of the project. Also I opened a digital clock (which I purchased online) and I see that there is only one IC (obviously it is covered with something black wax). But there was that one patch only.
So it seems it used only a controller or RTC. But with only RTC its not possible to control LCD. So it must be only a microcontroller

Now I have three options for maintaining time

I use RTC like DS3231
I use millis() function
I use timer and timer interrupts of micro controller for free running timer.

Can I get accurate time using micro controller.

I see from eBay that you can get the DS1307 for around 10 cents. Is that really too much to pay? You also need a crystal and a backup battery (eg. CR2032). Without a battery the device cannot possibly remember the time if it is powered off.

If your device is battery powered then you could conceivably just use millis(), however you would need to have a way of setting the time. The resonator used on a Uno is not as accurate as a crystal, however that might be good enough depending on your project.

If you are trying to save money I wouldn't use a Uno or Micro, but the bare chip, with a few extra components (eg. decoupling capacitors, a couple of resistors, and a crystal).


NodeMCU ESP32s can't get Vin to work? Trying to power the board with a 9V battery through VIN. As the documentation says, it can take input voltage of 6-12 Volts, but when I connect the 9V battery, all it does is power the board on and nothing else happens.

Anyone know what I am doing wrong?

EDIT: I am stupid had the ground connected to the wrong pin thanks for the help everyone.

Assuming you are using a 9V block battery: They don't deliver the current you need for the esp32 to run/create an access point/act as a client. What you can do is connect 6 AA batteries in a row (6*1.5V = 9V) and they will deliver a higher current than the 9V block.


Print string and integer LCD How do I print a string and integer on an LCD? Here is what I have tried:

int number = 2;
int result = (number + number);
lcd.print(number, DEC + " plus " + number, DEC + " equals " + result, DEC);

And the result is an error.  When I try:

lcd.print(number + "look");

or

lcd.print("1234 " + number);

Then the result on the LCD is "34 ", as it deleted the first two numbers!

I want it to print:

1234 2

Please help!  Thanks!

The lcd.print() method takes a string or a number as an argument, but not both at once. Using the + operator for concatenation is not native to C strings. C strings are basically stored as pointers to the first character of the string. So when you tried lcd.print("1234 " + number) and got "34 ", what most likely happened is that you advanced the pointer, pointing to the first character of "1234 "(i.e. '1') by number (i.e. 2), thus making the pointer point to the 3rd character in the string and thus making lcd.print() display "34 ".
In order to print something that contains both strings and integers, the most straightforward way is to convert each piece to an Arduino string and then concatenate them, using the + operator like you did earlier.

    lcd.print(String("1234 ") + String(number));
    lcd.print(String(number) + String(" plus ") + String(number) + String(" equals ") + String(result));

These are some examples. You could also use create a sufficiently large char buffer and use sprintf() from stdio.h to build a string made up of integers and strings. Look up a textbook on C/C++ for more details.


How to get response of issued AT command for ES266 on Arduino programatically? I'm successfully running AT commands via the Serial Monitor. But now I'm issuing AT commands via Arduino code and facing problems getting the correct response.

Goal: After issuing AT commands programatically, knowing whether these run successfully or not.

Microcontroller: Arduino Uno

#include<string.h>
#include<SoftwareSerial.h>

#define OK "OK"
#define SERVER_PORT 1234
#define RX_PIN 2
#define TX_PIN 3

SoftwareSerial ESP(RX_PIN, TX_PIN);

void setup() {
  Serial.begin(115200);
  Serial.println("First serial");
  while(!Serial);
  ESP.begin(115200);
  Serial.println("Second serial");
  while(!ESP);
  //Enabling multiple connections
  ESP.println("AT+CIPMUX=1\r\n");
  while (!ESP.available());
  String muxResponse = ESP.readString();
  Serial.print("muxR:");
  Serial.println(muxResponse);
}

void loop() {
  if (ESP.available()) {
    String val = ESP.readString();
    Serial.println(val);
  }
}

After running the above code I get the response in the Serial Monitor like:

muxR:AT+CIPMUX=1

busy p../

OK

I'm getting special characters too.

change

AT+CIPMUX=1\r\n

to

AT+CIPMUX=1


Use SPI and I2C in the same circuit (ATtiny85/84) There is a previous question about this same topic here, but it does not answer my question.

I want to use a generic I2C OLED 128x64 px display and an SPI RF24 radio in the same sketch. I know that it's theoretically possible to do so as long as they're not used at the same time - my question concerns the implementation of this circuit. Can I just leave the two devices as-is without needing some kind of external apparatus to switch power to each one of them?

I know that for SPI a chip will just ignore everything when its CS pin is pulled high, and from my tests the SPI communications don't affect the SDA line of the I2C - the problem comes when I try and use the CLK and SCL line with this setup. The pullup resistor in my circuit is stopping the I2C SCL line from working. When I remove the wire (green in the breadboard schematic shown) that connects the CLK to one end of the diode the I2C starts working and the display updates, but the radio doesn't work. If I remove the pullup resistor from the circuit the I2C starts working again, but the radio doesn't work anymore. I tried switching the CLK signal with a transistor, but it doesn't look like the 2n2222 transistor I was using is fast enough to switch the CLK signal. Will I have to go with the tiny84, or is there a way to get this to work on the ATtiny85?

In the setup shown, you have 3 pins free, yes? Although hardware i2c may not be directly possible through software, the use of the other GPIO pins can be used for either a logic circuit to switch around the pull up resistor/green wire/whatever OR you can just use software i2c which is a lot easier to do.


Burn bootloader to Arduino Uno using ARM-USB-OCD I have ARM-USB-OCD created by OLIMEX. I am interested in can I use this to burn a bootloader to Arduino Uno. As I know Atmega 328P can be programmed using JTAG protocol which has also ARM-USB-ODC, so if it really can anyone give the circuit or something like this.
Here is my device (ARM-USB-ODC) manual.

Probably, but likely not easily

To program an AVR chip you likely want to use the AVR ISP protocol, which is not JTAG, but like JTAG is a synchronous serial protocol with a clock, a data line in each direction, and one additional control pin compared to the several mode/status pins of JTAG.

According to your link, the ARM-USB-OCD is based on an FT2232C USB interface chip.

avrdude documentation indicates that this is an interface it knows how to use, though it will likely take some study to figure out how.

The final question would be wiring - you'll need to figure out which JTAG-style signal names map to which FTDI functional pins, and how those should best be connected to AVR ISP pins in a way which avrdude can use.  Additionally, you'd have to make sure that any buffering between the FTDI chip and the pins is compatible with your needs, both in terms of data direction and voltage level.

Note that you can easily use any ATmega328-based Arduino as an ISP programmer for a same-voltage target - not really production worthy, but if you just need to move your project along today it's a handy option.


Arduino Python to Serial command I am trying to send commands via serial from Python to Arduino with the code below.

If I save this code in a dedicated python file "Stepper.py" (Python2.7 on Mac OSX) , the code runs successfully but nothing happens (the code does not trigger a motor connected to Arduino).

If I start terminal and run the same code from the interactive shell it works as expected.

How can I run it via a dedicated file ?

import serial
import time

ser = serial.Serial(port="/dev/cu.usbmodem144231", baudrate=9600, timeout = 0)
ser.write("200+")
time.sleep(1)
print ser.read()

Majenkos comment (above) solved the problem:

"You need to wait after opening the serial port for the board to finish resetting and the bootloader to run and exit before you can send any commands."

import serial
import time

ser = serial.Serial(port="/dev/cu.usbmodem144231", baudrate=9600, timeout = 0)
time.sleep(1)
ser.write("200+")
print ser.read()


ESP32 WiFiClient request missing response I am facing problem with ESP32. I use basic example for WiFiClient and making request to my server. The problem is that the response should be 15000 bytes long, but very often I got only 2750 or less.

char buffer[15000];
while (client.available()) {
  char c = client.read();
  buffer[i++] = c;
}
Serial.println(i);

You are assuming that all 15000 bytes are available all the time.

They won't be.

Instead of "while available read something" you need to "While not enough has been read, then if available read something".

When reading from (assuming) HTTP you first need to read and interpret the headers (the lines before a single blank line).  One of these will be the "Content-Length:" header, which will tell you exactly how many bytes are in the body of the response. Then you use that to read the right number of bytes from the body.

So the sequence is:

Read line by line for the headers interpreting the ones you need to, until:
You receive a single blank line
Read the data byte-wise until you have read the number of bytes indicated in the Content-Length header.

If you aren't reading from an HTTP server and you are certain that the data is exactly 15000 bytes in length then you need to skip to point 3 above. Never assume that all the data is there. If there is data then read it, and repeat until you have totalled 15000 bytes.


Arduino Pro mini to CH340G Connection problem I have worked with Arduino UNO but recently I bought a new Arduino Pro mini 5v 16M and a CH340G converter to work with. I have searched google to connect pins but I found examples that explains this way :
GND to GND
VCC to VCC
Converter RDX to Arduino Pro Mini TXO
Converter TDX to Arduino Pro Mini RXI
My problem is that my Arduino Pro Mini (328p) has pins TXD and RXD (not RXI , not TXO) or maybe I have no knowledge about TX,RX, IN and OUT.
Can someone please help me to connect these wires?

try reversing the tx/rx lines, if the PRO Mini and serial adapter are chinese, you may want to try using your UNO as ISP programmer. See here for a hint/ex:
https://www.arduino.cc/en/Tutorial/ArduinoISP


Passing HardwareSerial and SoftwareSerial as a Class Property I wish to know if there is a way to use a single property Serial0 to hold a HardwareSerial or a SoftwareSerial or other class instances supporting basic methods such as available(), read() and write(), in order to make a CustomSerial Class (polymorphism?).

class CustomSerial{
    <GenericSerial??> Serial0;
    char c;
    void read(void){
        c=Serial0.read();
    }
};

The calls should be:

CustomSerial SerialCus;
int n=SerialCus.available();
char c=SerialCus.read();
SerialCus.write(c);

What should I use as GenericSerial class, or what should be the proper use? I tried the Stream class (as the answer pointed), but for some reason the functionality is not preserved (it writes unknown characters). Should indeed Stream be the generic class I need for this?

A base type for Arduino hardware serial classes, SoftwareSerial and other software serial classes and some other Arduino classes is Stream (reference). Stream.h on GitHub

class CustomSerial {

private:
  Stream &stream;

public:
  CustomSerial(Stream &_stream) : stream(_stream) {}

  int read() {
    return stream.read();
  }

  int available() {
    return stream.available();
  }

  int peek() {
    return stream.peek();
  }

  void write(byte b) {
    stream.write(b);
  }

};

SoftwareSerial Serial0(10, 11);
CustomSerial SerialCus(Serial0);

void setup() {
}

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


Which LCD Pins, if any, require PWM? In the Arduino Tutorial Page named "Hello World" aimed to help people connect a 16x2 LCD Display compatible with Hitachi HD44780 driver to an Arduino Uno. The pins used to connect the Arduino Uno and LCD Module are as follows:

LCD RS pin to digital pin 12
LCD Enable pin to digital pin 11
LCD D4 pin to digital pin 5
LCD D5 pin to digital pin 4
LCD D6 pin to digital pin 3
LCD D7 pin to digital pin 2

Pins 3,5 and 11 are connected to PWM Pins, however, I'm wondering if they actually need these PWM capabilities or does this tutorial just pick random pins and the LCD's D6, D4 and Enable pins doesn't actually need the PWM capabilities available of these pins.

I'm asking this as I'm considering on using an Arduino Mega for my next project and it would be much easier and neater for all the pins of the LCD to go onto the digital pins instead of some being on the digital and others on the PWM pins.

Likely all programmable pins on modern embedded processors are able to perform digital I/O.  In addition, many can also perform other tasks such as PWM, or Analog to Digital Conversion (ADC).  This is true for many of the different processors used on different Arduino boards.

Often, the nice people who write the C++ driver class of programs or Arduino Libraries offer the user the ability to change pin assignments used by the Arduino Libraries when instantiating an instance of the driver.  This is true for the LiquidCrystal driver in the tutorial in the question.  This can be an advantage as processor's resources are limited.  For example, if you need PWM controlled pin to dim LEDs, you can move LCD controlling pins to other non-PWM pins.

The LCD specified in the tutorial linked to in the above question uses a common Hitachi HD44780 interface.  Such assemblies only need embedded processor Digital I/O pins for control.  Had the LCD no electronic driver, the segments need to be directly driven by very low alternating current (AC).  This is difficult for embedded processors.  However, it may be possible using enough PWM pins and some clever software & hardware.


Controlling Dynamixel MX24T, MX64T servo wirelessly using Arduino Mega? I am planning to control multiple Dynamixel servos (MX28T or MX-64T) wirelessly using an Arduino Mega. Since this servo uses serial communication, I need an additional serial port to interface with XBee module. Although it seems to be very common application controlling these servos wirelessly based on Arduino, I could't find any of them in web. I found the two very well constructed libraries.

https://code.google.com/p/slide-33/downloads/list. This library is for MX28T servo, which is the same servo I am trying to use, but it uses UNO;therefore, I cannot interface with XBee.
The Arduino/Dynamixel Resource Page... This library uses UART1 (serial1) to interface with servo (AX-12) motors. Therefore, I can connect XBee module to UART0. But, the problem is that this library is outdated and not compatible with MX64-T servo anymore.

So my questions are:

Is there any one who has experience in controlling Dynamixel MX24T, MX64T servo series using XBee module simultaneously? If you have experience, please share with me.
Is it possible for Arduino Mega can interface with Xbee module using Serial1 (i.e., RX18 TX19)? If it can, I might be able to use the library1 without any modification.

I know, Although it is not ZigBee, ROBOTIS Arduino Shield(https://emanual.robotis.com/docs/en/parts/interface/dynamixel_shield/) can use BLE module (BT-410). My recommendation is Arduino compatible OpenCM 9.04(https://emanual.robotis.com/docs/en/parts/controller/opencm904/).
Arobotix-M(https://www.trossenrobotics.com/p/arbotix-robot-controller.aspx), you can use ZigBee.


How to add numbers to a position when controlling a seven-segment display I'm recently having a hard time with my Arduino project. I'm trying to control a seven-segment display (it has a microcontroller on it) with an encoder, and I'm trying so that everytime I rotate the encoder it adds 5 to the number on the display. What am I doing wrong here???

P.S: there are some parts that are for controlling relays, they are not related to the issue. I removed them on this thread on purpose.

Code (without any attempts to change the added amount to the display):

#include <RotaryEncoder.h>
#include <TM1637Display.h>

// Module connection pins (Digital Pins)
#define CLK 10
#define DIO 11

// Setup a RoraryEncoder for pins A2 and A3:
RotaryEncoder encoder(A2, A3);

// The amount of time (in milliseconds) between tests
#define TEST_DELAY   1000

TM1637Display display(CLK, DIO);

void setup()
{
    Serial.begin(57600);
    Serial.println("SimplePollRotator example for the RotaryEncoder
    library.");
}

// The Interrupt Service Routine for Pin Change Interrupt 1
// This routine will only be called on any signal change on A2 and A3:
//exactly where we need to check.
ISR(PCINT1_vect) {
    encoder.tick(); // just call tick() to check the state.
}

// Read the current position of the encoder and print out when changed.
void loop()
{
    static int pos = 0;
    int newPos = encoder.getPosition();
    if(newPos > -1)
    {
        if (pos != newPos) {
            Serial.print(newPos);
            Serial.println();
            pos = newPos + 4;
            display.setBrightness(0x0f);
            // All segments on
            // Show decimal numbers with/without leading zeros
            display.showNumberDec(newPos, true); // Expect: 1234
            delay(100);
        }
    } // if
} // loop ()
// The End

In your code, you call:

newPos = encoder.getPosition();

which grabs the absolute position of the encoder. When you rotate this one step, the value of newPos goes up (or down) by one.

Then, you make pos = newPos + 4, which simply adds 4 to the value that is going up or down by one step at a time.

newPos: 1    pos: 5
newPos: 2    pos: 6
newPos: 3    pos: 7
newPos: 4    pos: 8
newPos: 5    pos: 9

Instead, it sounds like you wish the display to always read 5 times the encoder position. If so, then you should write pos = newPos*5.

newPos: 1    pos: 5
newPos: 2    pos: 10
newPos: 3    pos: 15
newPos: 4    pos: 20
newPos: 5    pos: 25

Then, when you write to the display, you do so as:

display.showNumberDec(newPos, true); // Expect: 1234

But newPos is not the newly calculated value. Instead, call

display.showNumberDec(pos, true); // Expect: 1234


Mega  esp8266 comms sending baffling data I have Wemos Mega-ESP8266 board. I have uploaded a simple WebSocket server on the ESP...

#include <ESP8266WiFi.h>
#include <WebSocketsServer.h>

const char* ssid     = "SKYNET";
const char* password = "yourdogsfavouriteauntysmaidenname";

WebSocketsServer webSocket = WebSocketsServer(81);

void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t lenght) {

    //Serial.printf("[%u] get Message: %s\r\n", num, payload);

    switch(type) {
        case WStype_DISCONNECTED:
            break;

        case WStype_CONNECTED:
            {
              IPAddress ip = webSocket.remoteIP(num);
              Serial.printf("[%u] Connected from %d.%d.%d.%d url: %s\r\n", num, ip[0], ip[1], ip[2], ip[3], payload);
            }
            break;

        case WStype_TEXT:
            {
              String _payload = String((char *) &payload[0]);
              Serial.print(_payload);
            }
            break;

        case WStype_BIN:
            {
              hexdump(payload, lenght);
            }
            // echo data back to browser
            webSocket.sendBIN(num, payload, lenght);
            break;

    }
}

void setup() {

  // Set up serial comms
  Serial.begin(115200);

  // Set up WiFi
  WiFi.begin(ssid, password);
  while(WiFi.status() != WL_CONNECTED) {
     Serial.print(".");
     delay(200);
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

  delay(500);

  // Set up web socket
  Serial.println("Start Websocket Server");
  webSocket.begin();
  webSocket.onEvent(webSocketEvent);
}

void loop() {
  webSocket.loop();
}

I upload via the Arduino IDE & everything looks fine except the ESP doesnt send any information back through the serial monitor (yes I have the DIP switches correct for serial <> ESP comms).

I tried to see if was sending anything through the Mega via Serial3, the mega code (DIP switches set accordingly & ESP serial switch set to RX3). Mega code...

// Input buffer from ESP8266
String temp;

void setup() {
  // Set up serial comms
  Serial.begin(115200);   // Debug to Serial Monitor
  Serial3.begin(115200);  // From ESP8266
}

void loop() {
  while (Serial3.available()) {
      Serial.println(".......");
      Serial.println("In from ESP8266");
      temp = Serial3.readString();
      Serial.println(temp);
      Serial.println(".......");
  }
}

So now I get 2 one time messages to the serial monitor..

.......
In from ESP8266
[WS-Server] Server Started.

.......
.......
In from ESP8266
pm open,type:2 0

.......

I have no idea where these messages are being generated or why the ESP isnt sending the serial messages on set up eg the IP address for the ESP etc.

Any idea what's going on here?

Edit 1: Addition info asked for in comments (or at leat I think this is what was asked for)

Edit 2:

DIP switch settings for flashing the ESP - OFF, OFF, OFF, OFF, ON, ON, ON

DIP switch settings ESP > serial monitor - OFF, OFF, OFF, OFF, ON, ON, OFF (RX switch to TX0)

DIP switch settings for ESP > Mega > serial monitor - ON, ON, ON, ON, OFF, OFF, OFF (RX switch to TX3)

Edit 3 I have to press the red reset button after flashing the ESP8266 & it works BUT as soon as I unplug & restart nothing again! The client connects, sends the same data but it doesnt get echoed back via the serial comms. The only way to get to work again is to reflash the ESP8266 and hit the reset button.

Edit 4 Swapped out the board & now nothing works again. Uploads look fine but no serial comms at all from the ESP8266.

The esptool auto-reset feature by default sets io 0 LOW over the RST line and then makes a reset over the DTR line to put the esp8266 into flashing mode. After the upload the esptool resets the board over the DTR line.

On this board Mega+WiFi, only the DTR line is wired like for AVR MCU. For flashing the io 0 pin is put LOW with the pin 7 of the DIP switch manually. So the reset after upload sets the esp8266 back to flashing mode.

The esp8266 arduino package changed from version 2.5.0 the upload tool to the python version of the esptool which makes this reset after upload. This reset can be turned off by changing the command line of the esptool in platform.txt (--after no_reset in tools.esptool.upload.pattern before write_flash)


Getting RGB values from camera I have a camera I'm planning on attaching to an arduino uno, that I want to take pictures and extract the average RGB value from each image.
This is the camera I have, but I've now realized that it takes pre-compressed JPEG images, and so I cannot make use of the data it's giving me.

I realize that an arduino is not the optimal tool to use in this case, but I'm curious as to whether there would be any way to decompress the images and convert them to a format I could use. It does not need to be fast, and I do not need to take the pictures quickly. I have experience with programming but have not done many projects with the arduino, so any help or advice is appreciated.

No. The Arduino (or not the "normal" Arduinos) doesn't have enough memory to decompress JPEG.

I made a JPEG decompressor for chipKIT boards the other day, and it uses the absolute bare minimum memory possible, and still comes it at close to 128kB. Far more than any "normal" Arduino board.

You can possibly do it with one of these new-fangled Linux-based Intel boards that are being sold as Arduino these days, but they are not your normal run-of-the-mill Microcontroller but closer to a Raspberry Pi.

Speaking of which, the Raspberry Pi is probably a much better choice than any Arduino board for the kind of thing you are trying to do.


Detecting the presence of a specific smartphone I would like you to give me some clues about a projet I have: I want to make sure that my little brother's smartphone stays in a shelf overnight and during school hours in order to monitor the time he spends with it.

In order to fulfill my needs, I thought of using an Arduino to detect that the smartphone stays in proximity at certain hours.

Since this is my first Arduino project, I'm not quite sure what I could do, and what is possible to do.

Hence I've got a lot of questions:

Can I easily detect that a specific smartphone is in range?
Can I use the smartphone's NFC (RFID) to do so?
What kind of output could I possibly get from an Arduino? I would like to make statistics, so it must be stored somewhere, and I know Arduino doesn't have a lot of memory.
Is it possible to write on a USB key?
Which Arduino is best suited for my needs Should I consider buying an Arduino with Ethernet in order to send emails?

Thanks a lot!

Can I easily detect that a specific smartphone is in proximity ?

It can be done, yes. How "easily" depends on how much money and expertise you have to throw at it.

  Can I use the smartphone's NFC (RFID) to do so ?

It is possible to use that, yes - if you add the right hardware and software to the Arduino.

  How long can an Arduino run on battery using a 9V battery from the market ?

A couple of hours if you're lucky. They are useless batteries.

  What kind of output could I possibly get from an Arduino ? I would like to make statistics, so it must be stored somewhere, and I know Arduino has not a lot of memory.

Whatever you want. Again, it's SMOP / SMOH.

  Is it possible to write on an USB key ?

Sure, if you get the right hardware for that.

  Which Arduino is best suited for my needs ? Should I consider buying an Arduino with Ethernet in order so send email ?

The Arduino that provides the facilities your project requires - and that depends on how you are going to decide on how to do it. Remember: the Arduino is just the "brain" of the operation. You need to decide what "organs" the brain needs to control and in what way.

There's a million and one ways of achieving what you want. You could even do it 100% in the phone in software (there's probably an app for that...) without need of an Arduino...


redefining delay and delaymicros as personal function Is it possible to redefine delay and delaymicros function with #define ?
I want to use timer2 interrupt instead of these.

Something like this:

#define delay(unisgned long ms) countMicros(uint16_t top, uint16_t storageVar)

setup(){}

loop(){
 delay();// function countMicros is called instead.
 }
void countMicros(uint16_t top, uint16_t storageVar){
//...}

Not exactly like that. You will have to manage the different sets of
parameters, i.e. convert the incoming ms into the top and
storageVar that would be appropriate for calling countMicros().
Maybe something like this:

#define delay(ms) mydelay(ms)

void mydelay(unisgned long ms) {
    uint16_t top = some expression;
    uint16_t storageVar = another expression;
    countMicros(top, storageVar);
}

where both expressions are a function of ms.

If the expressions are really simple, you could even put the whole thing
inside a single macro, as in

#define delay(ms) countMicros(some expression, another expression)


Boil water inside a small container with an arduino I am currently working with a sciene/electronic project where i need "steam". In order to create steam i need to boil water and i plan to boil it inside a very small container [around 5cmx5cmx5cm]. What i want to do is to control this with an arduino but I am very unsure on what step i currently need to make. Are there any "heating-up" modules out there? Or would I need to order a mini-mini kettle and connect that to my arduino?

I am very grateful for every advice i can get because as u can tell i am a bit confused as of right now!

Try to find a boiler pot on electricity (I doubt you can heat water to boiling temperature with like 5V (unless you use many amperes).

Use a relais to switch it on with an Arduino.

Use a temperature sensor (0-150 degrees or so) to decide when to switch it off.

Warning: Get first some electrical knowledge before you start with >200 volts projects since it can be deadly. And boiling water can be devestating for skin and your Arduino.


Flash size in boards.txt ATmega 328p 32u4 The ATmega328p and ATmega32u4 microcontroller have 32Kb of flash memory (as datasheet). Bootloader for each microcontroleer has different size (about 512 byte for 328p and 4kb for 32u4).

Why in boards.txt the "upload.maximum_size" parameters is 32256 for 328p and 28672 for 32u4?

I we have to consider bootloader size, the "upload.maximum_size" parameter for 328p must be about 31.5k and not 32k. And, if we do not have to consider bootloader size, as the default boards.txt configuration (above) for 328p, the "upload.maximum_size" parameter for 32u4 must be 32k not 28k. Correct?

Thank you

1KB is 1024 bytes, not 1000 bytes.

Therefore 32kb = 32768 bytes.

32768-512=32256, which is exactly the value used for upload.maximum_size for the 328p.

4kb=4096 bytes. 32768-4096=28672 which is the value for the 32u4.


Send custom HID values instead of keys I've been building a small macro keypad based on the ATmega32U4. So far, I've been able to send standard key presses to the host. But since I want a program on the host system to react to the key presses, I only send the keys to serial to avoid typing anything. For now, this does work.
I want to send custom HID values to the host which won't result in regular key presses. As I've been reading around different blog and forum posts, most of them are just about building a regular keyboard or gamepad but don't go into how to make use of anything else.
This is what I got so far:
#include <Keypad.h>

const byte rows = 3;
const byte cols = 5;

char keys[rows][cols] = {
  { '1', '2', '3', '4', '5' },
  { 'q', 'w', 'e', 'r', 't' },
  { 'a', 's', 'd', 'f', 'g' }
};

byte rowPins[rows] = { 10, 16, 14 };
byte colPins[cols] = { 9, 8, 7, 6, 5 };

Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, rows, cols );

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

void loop(){
  char key = keypad.getKey();

  if (key != NO_KEY){
    Serial.println(key);
  }
}

The only obvious way I see to achieve this is to change the keys array but I don't know to which values.

UPDATE
I changed the code according to the answer by Majenko:
#include <HID-Project.h>
#include <HID-Settings.h>

uint8_t rawhidData[255];

byte rows[] = { 10, 16, 14 };
byte cols[] = { 9, 8, 7, 6, 5 };

const int rowCount = sizeof(rows)/sizeof(rows[0]);
const int colCount = sizeof(cols)/sizeof(cols[0]);

void setup() {
  for (int row = 0; row < rowCount; row++) {
    pinMode(rows[row], OUTPUT);
    digitalWrite(rows[row], HIGH);
  }

  for (int col = 0; col < colCount; col++) {
    pinMode(cols[col], INPUT_PULLUP);
  }

  RawHID.begin(rawhidData, sizeof(rawhidData));
}

void loop() {
  for (int row = 0; row < rowCount; row++) {
    digitalWrite(rows[row], LOW);

    for (int col = 0; col < colCount; col++) {
      if (digitalRead(cols[col]) == LOW) {
        String coordinatesString = String(row+1) + String(col+1);
        uint8_t coordinates = coordinatesString.toInt();

        uint8_t megabuff[sizeof(coordinates)];

        megabuff[0] = coordinates;

        RawHID.write(megabuff, sizeof(megabuff));

        while (digitalRead(cols[col]) == LOW) {
          delay(50);
        }
        break;
      }
    }

    digitalWrite(rows[row], HIGH);
  }
}

I removed the serial output since I don't need that anymore. The code looks crude and needs further refactoring but it does work.

HID is a strange beast to get your head around.
It operates by way of "Report Descriptors". These are "maps" that lay out what the values you send mean. It's these descriptors that make a keyboard a keyboard and a mouse a mouse.
When you use Keyboard.h you attach a Keyboard report descriptor to the USB HID endpoint, and the computer knows to interpret the data coming in as keypresses. When you use Mouse.h you attach a Mouse report descriptor and the computer knows to interpret the data coming in as mouse movements and button presses.
If you want your computer to ignore the data that you send and allow your own program to be able to receive the raw data instead then you need to use a descriptor that the computer doesn't recognise. In such a case it just ignores the data.
There's a "Raw HID" library for Arduino that does that - it uses a "blank" report descriptor that just gives you a plain 64 byte block of data to do what you want with.
There's a good HID library by Nico Hood that implements the raw mode (as well as others).
For receiving the data on your computer you will have to have your program directly interface with the USB HID system. There's plenty of libraries for most languages to do this for you (hidapi in C / C++, hid in Python, hid4java for Java, etc).


Collecting data from a timer interrupt and storing it into an array My question is: how can I use an ISR and store the data I get from my analog inputs into an array for easier data analysis.
More specifically, I want to collect my data using an ISR function (internal timer interrupt), then store the collected data into an array. This way I can analyze the data more easily.
I have posted the code below. I have posted code showing how I implemented my ISR without storing the data into an array. I was wondering I anyone could help me out with this (how to store that data into an array). Thank you.
const int A0_pin = PC0;
const int A1_pin = PC1;

const uint16_t t1_load = 0;
const uint16_t t1_comp = 3173;

float count = 0;
float num = 0;

void setup() {

  //Set A0 and A1 pins as inputs
  DDRC &= ~(1 << A0_pin);
  DDRC &= ~(1 << A1_pin);

  //Reset Timer1 Control Reg A
  TCCR1A = 0;

  //Set CTC mode
  TCCR1B &= ~(1 << WGM13);
  TCCR1B |= (1 << WGM12);

  //Set to prescaler of 256
  TCCR1B |= (1 << CS12);
  TCCR1B &= ~(1 << CS11);
  TCCR1B &= ~(1 << CS10);

  //Reset Timer1 and set compare value
  TCNT1 = t1_load;
  OCR1A = t1_comp;

  //Enable Timer1 compare interrupt
  TIMSK1 = (1 << OCIE1A);

  //Enable global interrupt
  sei();

  Serial.begin(9600);
  Serial.println("CLEARDATA"); //clears up any data left from previous projects
  Serial.println("LABEL,TIME,TIMER,AVG,GAUGE0, GUAGE1"); //always write LABEL, so excel knows the next things will be the names of the columns
  Serial.println("RESETTIMER"); //resets timer to 0
}

void loop() {
}

ISR(TIMER1_COMPA_vect) {
  TCNT1 = t1_load;
  float Gauge0 = analogRead(A0_pin);
  float Gauge1 = analogRead(A1_pin); //44

  //conversion of read data, to voltage range (0-100 percentVolts)
  float gauge0 = Gauge0 * (100.0 / 1023.0);
  float gauge1 = Gauge1 * (100.0 / 1023.0);
  float add = gauge0 + gauge1;
  float AVG = ((gauge0 + gauge1) / 2);

  Serial.print("DATA,TIME,TIMER,");
  Serial.print(add);
  Serial.print(",");
  Serial.print(gauge0);
  Serial.print(",");
  Serial.println(gauge1);
}

In the code, I want to store the gauge1 and the gauge0 values into an array essentially.

Storing the data into arrays is not an end in itself. The question is:
what do you want to do with these arrays? The way to proceed depends on
that purpose.
If you want the data acquisition (analogRead()) and the processing
(computation and printing) to proceed in parallel, then you will need
the arrays for buffering the data between those two processes. As
mentioned by Michel Keijzers in his answer, you will have to research
the concept of ring buffer.
There is a ring buffer implementation in the Arduino core you can use as
inspiration: when reading data from the Serial port, the incoming bytes
are received by an ISR and stored in a ring buffer. The
Serial.read() method can then be used to retrieve these bytes
and process them outside the interrupt context.
Another option is to alternate between an acquisition phase and a
processing phase. This can be an interesting approach if the acquisition
rate is too fast for the processing to be performed in real time. In
this case, you do not need a ring buffer. Instead, you have the ISR fill
the arrays and, when they are full, the main program can take on and
start the processing. For coordinating these jobs, you just need a
boolean to keep track of whether you are performing the acquisition
phase or the processing phase. Note that, since accessing a boolean is
an atomic operation, you do not need to disable interrupts for this.
Here is an example implementation of this strategy. The variable
sampling_done is used to coordinate the two processes:
const size_t sample_count = 256;

volatile int gauge0[sample_count];
volatile int gauge1[sample_count];
volatile bool sampling_done = false;

ISR(TIMER1_COMPA_vect) {
    if (sampling_done) return;  // nothing to do

    static size_t sample_idx = 0;
    gauge0[sample_idx] = analogRead(A0);
    gauge1[sample_idx] = analogRead(A1);
    if (++sample_idx >= sample_count) {
        sample_idx = 0;  // prepare for next round
        sampling_done = true;
    }
}

void process_samples(int Gauge0, int Gauge1) {
    // Whatever needs to be done with the samples:
    // computation, printing...
}

void loop() {
    if (sampling_done) {
        for (size_t i = 0; i < sample_count; i++) {
            process_samples(gauge0[i], gauge1[i]);
        }
        sampling_done = false;  // start next sampling round
    }
}

Now some random remarks:

There is no need to sei() in setup(): interrupts have already been
enabled by the Arduino core initialization.

Do not reset TCNT1 within the ISR: this is handled automatically by
the CTC mode. If you do this in software, you risk missing timer
ticks.

Do not store the readings in float variables: they take twice the
memory of an int and all operations on floats are incredibly slow
compared to the equivalent operations on ints.

The scale factor for converting the readings to percent scale is
100.0/1024: the maximum possible analog reading (1023) is one ADC
step below the reference voltage: see the datasheet.

You should remove unused variables as soon as they become unused
(count, num, AVG). Once you do that you should notice you do not
need floats at all.