Steppers only vibrate, not rotate with I2C The goal of my project is to be able to control two steppers with 4 buttons. Steppers are connected to Adafruit Motor shield(the older one) which is stacked on Arduino UNO, buttons are connected to Arduino NANO. I'm using I2C between the two Arduinos. However, if I push a button, the steppers won't rotate, only vibrate, but if I'm using only Arduino UNO with the motor shield stacked on it, button connected directly to the motor shield, it's working well.
Arduino UNO is Master Reader, while NANO is Slave Writer. There is a fritzing image of the circuit.
I don't know where's the problem, if it's in the circuit, if it's because of my battery(i bought it like 10 minutes ago) or the code. Any help is apreciated.

Master code:

#include <Wire.h>
#include <AFMotor.h>
//define steppers
AF_Stepper motor1(48, 2);
AF_Stepper motor2(48, 1);

//define variables
int x = 0;
int y = 0;

void setup()
{
  Wire.begin(5); //begin i2c communication
  Wire.onReceive(receiveEvent);
  motor1.setSpeed(200);  // 10 rpm
  motor2.setSpeed(200);  // 10 rpm

  motor1.release();
  motor2.release();
  delay(1000);
}

void loop()
{
  delay(500); // wait 0.5 second
}

void receiveEvent(int howMany)
{
    //read x,y from slave
    x = Wire.read();
    y = Wire.read();

    if (x == 1) //stepper1 rotate forward
    {
      motor1.step(100, FORWARD, SINGLE);
    }
    else if (x == 2) //stepper1 rotate backward
    {
      motor1.step(100, BACKWARD, SINGLE);
    }
     else if (y == 1) //stepper2 rotate forward
    {
      motor2.step(100, BACKWARD, SINGLE);
    }
     else if (y == 2) //stepper2 rotate backward
    {
      motor2.step(100, BACKWARD, SINGLE);
    }
}

Slave code:

#include <Wire.h>

//define buttons
const int button1 = 2;
const int button2 = 3;
const int button3 = 8;
const int button4 = 7;

//define state of buttons
int buttonState1 = 0;
int buttonState2 = 0;
int buttonState3 = 0;
int buttonState4 = 0;

//define variables
int x = 0;
int y = 0;

void setup()
{
   //start i2c communication
   Wire.begin();
}

void loop()
{
  //read state of buttons
  buttonState1 = digitalRead(button1);
  buttonState2 = digitalRead(button2);
  buttonState3 = digitalRead(button3);
  buttonState4 = digitalRead(button4);

    //if button1 is pressed,send x to master
    if(buttonState1 == HIGH){
      x = 1;
      Wire.beginTransmission(5);
      Wire.write(x);
      Wire.endTransmission();
    }
    //if button2 is pressed,send x to master
    else if(buttonState2 == HIGH)
    {
      x = 2;
      Wire.beginTransmission(5);
      Wire.write(x);
      Wire.endTransmission();
    }
    //if button3 is pressed,send y to master
    if(buttonState3 == HIGH){
      y = 1;
      Wire.beginTransmission(5);
      Wire.write(y);
      Wire.endTransmission();
    }
    //if button4 is pressed,send y to master
    else if(buttonState4 == HIGH)
    {
      y = 2;
      Wire.beginTransmission(5);
      Wire.write(y);
      Wire.endTransmission();
    }
}

In both master and slave, you have x and y declared in the broadest scope possible. Different devices, shouldn't matter. But x and y usual mean coordinates, which is not what you are trying to say - properly named variables help with understanding and maintenance.

I think your biggest issue, and one that confuses your attempts to debug, is the underlying logic.

You have 4 independent buttons, but prioritise one button over the
other. What happens if both buttons are pressed together?
You have 2 independent motors but prioritise one after the other.
Your slave uses repeating code.
You use your slave as both a writer and  decider. In this case, your
writer is making the decisions over which motor to move and which
direction.
Your master only makes one move at a time - but you have two motors and 4 buttons, so you should be able to move both motors in one loop.
Your handler expects the number of bytes to be read but you don't use that to control your reading.
Your consecutive reading does not differentiate on where the data comes from. x could be filled with any of the button presses, and so could y.
If the event handler is doing the work, why have a blocking delay in the code?

Effectively, you are taking a random read and expecting the device to do something deterministic. Hence your jittering.

To help you debug your device, you can first clean up your code.

reconfigure your slave to send a single response each loop. You only need 4 bits, where each bit represents whether buttons 1-4 are pressed. Only 1 variable to be written.
Use your master to decipher the input. This is where you can put the safety in (e.g. if both 1&2 are pressed/HIGH then ignore). This also reduces the possibility that your code is sending a forward then backwards signal.
Use your master to determine how many bytes have to be read and use this properly.

You will find your code cleaner, easier to read and easier to debug. Perhaps you will also see a way to directly slave the NANO to the UNO without i2C in the middle, simplifying your set up even more.

EDIT (additional information):

You can use the built in functions (see Arduino function reference under "Bits and Bytes") such as BitWrite/BitSet/BitClear and BitRead to set/clear the relevant bits on the variable you create (e.g. Byte ButtonStates). Note the use of Byte instead of Int
You can then use the slave to write the information and the master to read the information (Wire.write and Wire.read), you then know that each byte is complete and reflects what you intend.


Can I run two function in arduino simultaneously? I'm new to arduino world and I don't have any background. I just want to ask if I can run two function in arduino simultaneously. I'm going to make an earthquake detector but at the same time, I want to receive an sms to my phone when its alarm. Is this possible?

You can imagine a program as a procedure that a CPU executes, reading and doing step by step.
When you compile any program, the compiler checks it, and when it finds some error it can tell you exactly where (the line) in which you made this error.
It can be done simply because the program is a series of commands.
Also if, in some cases (interrups, callbacks, asynchronous functions etc.), it seems to be different, the code is always executed step by step, like when you follow a recipe when you're cooking.
You don't have to worry about that, in fact these steps are done by the CPU very quickly and you can do many things as they would be done seemingly simultaneously.
The Arduino Uno (Atmega328) works at 16Mhz.
As you can read here: "an almost empty loop() is seen about 150k times a second".
So don't worry about the simultaneity of your functions.
You can write a function for detecting the earthquake that calls other functions (like alarms, procedures, etc.) without much time lapse (the best logic I think is: first check the event, then do stuffs).
The only thing I suggest you do is to reduce the code to let it become as small (and fast) as possible, but we are talking about a few milliseconds of lapse from earthquake to alarm.
If you need to register the exact time of the earthquake (absolute precision) you can use the micros() command.
In this case remember to do that as the first instruction (to reduce delay, of course).


How to setup HC05 Module to be distinguishable I'm not sure if this is a dumb question, but here goes  :

I am developing an Android app that uses a custom Bluetooth device as a companion. I'm using an HC05 module to interface the device with my app. What I need is a way for me to distinguish my HC05 module from, say, some other HC05 module that might be in range.

The obvious way of doing this would be to set the device name in a certain format. But I was wondering if there was a more better approach to this.

On searching, I found that UUID's are used for a similar purpose (i.e. service discovery), but I couldn't find any further info. Is it at all possible to set a custom UUID for the HC05 module so that I can filter devices in my Android app based on that?

Your options are:

As you guessed, you could set the name with AT+NAME=, and only use the names matching some pattern. It would work if you're only user so you just want to ignore other BT devices, but is problematic if you're having multiple independent users (each with its different set of *HC05*s) who might be in range (you could set different pattern for each user, though).
build a database of addresses (read-only with AT+ADDR?), and only access those devices that are belonging to that user. It would avoid problem above with multiple users, but would require some logistics on your part (for example, when you sell user the app and HC05s, in the registration process you'll need to assign exactly which HC05 address that user my access. Or you might want to allow user to pick which devices are his, by having him specify specify PIN for pairing set with AT+PSWD=)
third way is to use custom Inquire Access Code instead of GIAC so only that set of devices is scanned. HC05 allows setting it with AT+IAC=. However, as it is more complex and nonstandard that (2), and you'd probably still need to registration to differentiate which user is allowed which IAC, I'd recommend you do (2) instead.


analog serial read values are not equal I have not used the Arduino in over 2 years and have forgotten a bunch of stuff I was wondering if someone could help me out. I have two analog sensors both the same connected to the appropriate analog pins. I am getting a read on the serial monitor and when i test the sensors the values are changing so i know the circuit is correct and everything is in the right place. I just have an issue with my code.

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

// the loop routine runs over and over again forever:
void loop() {
  // read the input on analog pin 0:
  int sensorValue1 = analogRead(A0);

  // print out the value you read:
  Serial.println(sensorValue1);
   //Serial.print("val1 = " );
  Serial.print(sensorValue1);
  Serial.print(" ");

  delay(1000);        // delay in between reads for stability

   // read the input on analog pin 1:
  int sensorValue2 = analogRead(A1);

  // print out the value you read:
  Serial.println(sensorValue2);
  //Serial.print("val2 = " );
  Serial.print(sensorValue2);
  Serial.print(" ");
  delay(1000);        // delay in between reads for stability

 }

once i view this in the serial monitor it is not organized and the sensorvalue1 is skipping over to the next line. I would appreciate the help.

There are two sensors so there should be two values but in the picture the values are all messed up i would ideally like it to give me a two seperate values one for each sensor

val1= sensorvalue1
val2= sensorvalue2

Try something like this

void loop() {
  // read the input on analog pin 0 and 1 with delays for stability:
  delay(1000);
  int sensorValue1 = analogRead(A0);
  delay(1000);
  int sensorValue2 = analogRead(A1);

  // print out the value you read:
  Serial.print("val1 = " );
  Serial.print(sensorValue1);
  Serial.print(" val2 = " );
  Serial.println(sensorValue2);

 }


Help with arduino car project So in computer engineering I've got to make a arduino based car, I've added a whole bunch of features such as IR tracking, obstacle avoidance(proximity sensor), optical tracking(follow a black line), and remote control through an android based phone.

Since I'm a total newbie to technology I'm having trouble. I would appreciate it if You guys can point me towards resources and arduino libraries(for coding) that will work for me. Right now for coding I've only got basic pseudo-code setup since I do not know what libraries to use. I have searched up many sketches online and looked at them but didn't really understand any of the code.

Here's the basic pseudo-code I got setup on the things that I've got to work on:

DC Motor (4 of em for the wheels) (I also plan to add a stepper motor for turning right and left so if you could direct me on that as well)

//Import necessary library
//Setup the motors and pins

//If signal for forward received
//Code for moving forward
//Set speed

//Else If signal for backward received
//Code for moving backward
//Set speed

//Else If signal for right received (keep turning right till stop signal received)
//Code for moving right
//Set speed

//Else If signal for left received (keep turning left till stop signal received)
//Code for moving left
//Set speed

//Else If signal for stop is received (Should we slow down to a stop or just stop?)
//Code for stop
//Set speed

IR (I've got transmitting and recording diodes)

//Import Library

//Declare Pin for the IR Sensor

//While loop: Move Right
//If IR signal is received
//move forward
//Else
//Jump back to top of loop

Proximity Sensor (obstacle avoidance mode) (I might either use the one from Lego kit or buy a separate one )

//Import Library

//Declare Pin for proximity sensor

//While Loop: Send out sonar(echolocation or whatever) every second
//Is there any obstacle?
  //Yes, turn right so many degrees, and go back to while loop
  //No, move on forward at set speed

//If you’re surrounded and cannot exit send out a message through flashing LED's

I'm not asking for the code or for any of you to do all my stuff for me, I'm just asking for direction and resources.

Thank You

1) start simple - adding extra features will not help you, especially if you have a deadline

2) implement and test code for each low level function separately - however, in case you use libraries and or snippets, make sure that if a library/snippet requires exclusive use of a certain feature (ex: a timer), others do not need it.

3) test the overall logic elsewhere, where it easier to debug (ex: on a PC), by replacing the actual function calls to low level actuators/sensors with mockup functions that do I/O through either a file or a console.

Said this, what do you mean that you didn't understand the examples you found? To understand most of them, you need at least to read the API/interface of the libraries they use. And also reading the reference manual of the ATMega328P for the HW blocks referred by each library will help getting an overall feeling of what the library does.

About the basic physical model: once you have 4 DC motors (but 2 plus a caster would be enough), why do you want to add a stepper? Youc could do all of it with just 2 stepper motors , which will give you a simpler way to control precisely the orientation of the robot.

I'd suggest you to get the basic movement sorted out, before worrying about the rest. Just make sure that it doesn't make exclusive use of the microcontroller.


How much current does an Arduino Mega draw from a LiPo battery (5,000 mAh)? I went through Sparkfun's website on how to power a project because I wanted to calculate how much battery capacity I needed for my project. I saw an ATmega 328 micro-controller that is used as the brains for the circuit: it draws about 20mA under normal conditions.

So that got me thinking: how much current will an Arduino Mega draw from a LiPo battery of 7.4V with 5,000 mAh 2s 25C under normal condition? Please anyone do help me out and pardon me, I am new to this.

The important thing to realize here is that the capacity of the battery does not affect the amount of current drawn. Your Mega will draw the same whether it is connected to a 1000 mAh battery or a 5000 mAh battery. The larger battery will just last longer.

Tests on my Mega2560 Arduino show that (with no peripherals connected) it draws about 70 mA from a 7V supply, and slightly more (72 mA) from a 12V supply (the voltage regulator has to throw away some of the extra voltage as heat). (However, see below)

The exact amount it would draw in practice would be strongly correlated to what things you have connected. For example, LEDs, motors, shields, other devices.

I have a page about power saving that you might find useful if your objective is to minimize power usage.

Edited to add more about power consumption

It appears that my initial claim that the current consumption goes up with an increase in voltage was wrong. With Majenko's help I made up a detailed set of automated tests, increasing the Mega2560 power input by increments of 200 mV, taking a reading from both the power supply and my multimeter, averaging each one over ten readings, and plotting the results. This is what I got:

The two measurements seem to be consistently different by 0.2 mA. What this shows is that at 7V, the current consumption is 65.3 mA, and at 12 it is 64.1 mA, about a milliamp less.

I do, however, stick by my original assertion that the capacity of the battery will not affect consumption, and a larger battery will just last longer.


Can't see second Arduino port on Ubuntu I have connected two arduinos to /etc/ttyUSB0 and /etc/ttyUSB1.

Only one is visible in Arduino IDE. Why and how to force second?

UPDATE

$ ls -l /dev/serial/by-id
total 0
lrwxrwxrwx 1 root root 13 Jan  6 23:32 usb-1a86_USB2.0-Serial-if00-port0 -> ../../ttyUSB1

I.e. it shows port, which IS NOT SHOWN in Arduino IDE (only /dev/ttyUSB0 is shown.

ALSO

I can see both ports if run arduino with sudo. Should I run it with sudo?

Permissions are same

$ ls -l ttyUSB?
crw-rw-rw- 1 root dialout 188, 0 Jan  6 23:26 ttyUSB0
crw-rw-rw- 1 root dialout 188, 1 Jan  6 23:39 ttyUSB1

You have to add use your user to the dialout group, as explained in the installation instructions for Linux.

sudo usermod -a -G dialout $USER

Then log out and back in again.


Is it necessary to reduce the size of libraries? For example RTClib library have codes for DS1307, DS3231, PCF8523 and softRTC. but I'm only using DS3231 and don't need the extra codes there to occupy my Arduino flash memory.

Does Arduino IDE only "upload" those parts of libraries that is being used in the sketch or just uploads the whole library?

Normally a library supports various kinds of components; because mostly those components share a lot functionality, so it prevents to make very many different libraries.

Note that all functions that you do not call within your program (and are not called from within the library), will NOT end up in your sketch, thus also will not affect your flash memory usage.

If the library is full of if statements to make a difference between models, that code is in (if a function is called, the entire function is stored in flash). (Unless the if statement can be evaluated compile time, see remark of Edgar Bonet below about link time optimization).

So if you want to remove that 'unnecessary' code (for you at least), than copy the library into your project and remove the unnecessary code yourself.

However, I would not do that until you run out of flash memory.

You can do an easy test:

Include a library, and compile your sketch. You will see (possibly) some difference.
Now call a function from the library. Compile the sketch again, you will see the flash memory usage has increased. This means, before that, that function was not part of your compiled sketch.

A thing I would worry more about, is SRAM memory usage, but mostly buffers are created depending on the model, and SRAM is not wasted (since the Arduino Uno has only 2 KB for example).


NodeMCU successfully uploaded sketch but it does not work from Arduino IDE NodeMCU successfully compiled and uploaded a simple blink sketch on board, no errors at all, but the LED stays on constantly and does not blink. Also I have checked the power is enough. I have checked this with all pins but the red LED only stays on and doesn't blink. I have no idea what could have gone wrong. And how to fix this?

Fixed it....
turns out that in the tools, the board was selected to be NodeMCU 0.9
when it should actually have been NodeMCU 1.0
so i just changed it to NodeMCU 1.0 and it worked!


ArbotiX-M Problem uploading to the board I have an ArbotiX-m Arduino board, and have followed the setup guide on Trossen robotics all the way to the 5th step. I have a Mac running OS X 10.10 and use Arduino 1.0.5. I installed the necessary drivers and copied the files to the Sketchbook directory. When I try to load the sample ArbotiXBlink program:

// Pin 0 maps to the USER LED on the ArbotiX Robocontroller.
int led = 0;

// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);
}

// the loop routine runs over and over again forever:
void loop() {
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second
}

It verifies just fine, but when I click upload, I get:

Binary sketch size: 1,088 bytes (of a 65,536 byte maximum)
avrdude: stk500_recv(): programmer is not responding

Any ideas?

EDIT: The board was trying to get power from the 5V instead of USB

I figured why my board wasn't responding! Apparently, the power pin was connected to the 5V supply instead of usb. Silly me!


mega2560- Interrupts reading digital input Hi I am very new to Arduino, with very little programming experience.

I am using mega 2560 and trying to understand how interrupt works.

I have a code written, it is very similar as the example code Memsic2125, so i am gonna use that in here.

For my case, I am reading from my hardware, 5x5 array of sensors.

What I would like to do is to have it --   print out x and y using interrupts   , I want to print outputs the x and y every 10ms. Instead of printing it continuously right now.

I will be sending it out in 16 bits. I tried some other example and read a lot of material. but still couldn't get it to work.

Any idea, suggestion, help, comment is appreciated.

const int xPin = 2;
const int yPin = 3;

void setup() {

  Serial.begin(9600);
  pinMode(xPin, INPUT);
  pinMode(yPin, INPUT);
}

void loop() {

  int pulseX, pulseY;

  int x, y;

  // read pulse from x- and y-axes:
  pulseX = pulseIn(xPin, HIGH);
  pulseY = pulseIn(yPin, HIGH);

  x= ((pulseX / 10) - 500) * 8;
  y= ((pulseY / 10) - 500) * 8;

  // print x,y
  Serial.print("x,y= ( ");

  Serial.print(x);   Serial.print(,);
  Serial.print(y);   Serial.println(")");

  delay(100);
}

There isn't any interrupt code in what you posted. What exactly is the problem?  One important note is that you shouldn't try to print to Serial line in the interrupt handler as serial is itself driven from interrupts which are switched off during your handler code.  If all you really want to do is to print something every 10ms then you don't need any interrupt.  Just use the "Blink Without Delay" style of timing and keep the other code from blocking.


How much numerical precision can the ESP8266 achieve? Background: I am trying to port this solar tracker code by Gabriel Miller to run on the ESP8266. Now I'm not a particularly great coder, but I'd like to give it an honest try.

As of recently, the ESP8266 can be natively programmed using the Arduino IDE and code base. Which is pretty convenient.

SO. The solar tracker code written by Gabriel works on the Arduino Uno and the Arduino Mega. The Mega version of the code has a high-precision calculation library called 'BigNumber' to calculate the Sun's position in the sky to a pretty precise degree. My question is:

From what I've read, the ESP8266 is supposed to be a 32-bit microprocessor, so (I assume?) it should be able to handle high-precision numbers without using the BigNumber library; so, how do I check what's the highest numerical precision that the ESP8266 can support? That way I could theoretically just copy the equations over to the ported program rather than having to rewrite the BigNumber library.

There's not really any difference in numerical precision.  What you do get with 32-bit though is faster operations on larger data types.

For instance, to add two 32-bit numbers together (uint32_t) would take many operations on an 8-bit CPY, whereas on a 32-bit CPU it would just take a couple (only one to do the actual addition - a couple to load/save the values to memory).

One key difference, though, is that (to save space) the AVR system has double precision float values turned off and aliased to single precision float values.  This is purely a software feature and has nothing really to do with the hardware.  On 32-bit systems that is normally not done, so you can use double instead of float to increase precision.

However: While double is more accurate than float, it is still not precise.  All floating point values, regardless of precision, are only ever an approximation.  For that reason it is often preferred to use integer mathematics, and that is where libraries like BigNumber come in handy.  They allow you to (as the name suggests) work with much bigger numbers, which is good when dealing with integers when you want a high precision.

For instance, you could measure distance in km.  Say something is 18.329846283746km away.  You could store that as a single precision floating point value and it would end up as 18.329845428467.  As a double precision it would end up as 18.3298462837, which is closer, but still not right.

So you could represent it as meters instead of km.  So your 18.329846283746km would be 18329.846283746m.

How about if you represented it as mm instead?  18329846.283746mm

Say, why don't we go smaller?  Micrometers? 18329846283.746µm

I don't like that decimal point still.  What's smaller than µm? nanometers of course!  That would be 18,329,846,283,746nm.

Oh look, we have an integer value.  However that integer value is too big to fit in a 32-bit number even, which has a maximum of 4,294,967,295.  You could try using a 64-bit number (uint64_t) if the compiler you have supports it, which on both 8-bit and 32-bit systems would need multiple operations to work with (though less on the 32-bit), or you could use a library like BigNumber to deal with it all for you.

By using that method you start out by stating "I want to work in this fixed resolution and I want 100% precision within that resolution", rather than saying "I want to work with these values and I hope you'll get it vaguely right", which is far from ideal.

Also working with integer values is generally considerably faster than working with floating point values unless the CPU has a floating point unit available to do the heavy work for you.

So the difference between an 8-bit and a 32-bit system has nothing to do with the precision that is available to you, but everything to do with how fast operations at different precisions take to perform.


Unable to set up Intel Edison on Windows I am new to hobby electronics and have hit a dead end with my Intel Edison (which hopefully will not join the pile of useless components I have wasted my money on), and would appreciate some help with the setup procedure. The main problem is that I cannot connect to my Edison via the middle (lets call it "A") micro-USB port in order to get it into a working condition.

My objective is to connect to it's build-in Linux via SSH with the USB cables connected after installing the latest flash image.

I am using an Edison with an Arduino breakout board.

Here is the sequence of steps I followed:

I connected a 12V 2.6A AC to DC adapter to power the board. (Via the barrel connector). The green light came on to indicate it is powered.
I connected the "A" micro-USB port (i.e. not the one on the edge) to my computer.

At this point I could access the drive through Windows Explorer, however this changed when I executed the next step:

I installed the software from step 2 at https://software.intel.com/en-us/iot/library/edison-getting-started.
Something went wrong during the subsequent installation process. I don't know what.

At this point I could no longer access the drive. It would only appear as an "Unknown device" in Windows Device Manager. In order to try and fix this I gave up on the option where it is mounted as a Windows Drive.

I connected to the micro-USB port at the edge of the Arduino board and disconnected A.
I went to Windows Device Manager and found the connected device on COM6
I installed Putty and connected to COM6 with a baud of 115200.
The console showed a blank screen with a green cursor in the top left.
I waited 30 seconds for it to boot.
I hit Cntrl+C because I still saw the same screen from step 9.

I then saw this on the console:

Unknown boot mode: boot
Saving Environment to MMC...
Writing to MMC(0)... done
Resetting to default boot mode and reboot...
resetting ...

******************************
PSH KERNEL VERSION: b0182b2b
                WR: 20104000
******************************

SCU IPC: 0x800000d0  0xfffce92c

PSH miaHOB version: TNG.B0.VVBD.0000000c

microkernel built 11:24:08 Feb  5 2015

******* PSH loader *******
PCM page cache size = 192 KB
Cache Constraint = 0 Pages
Arming IPC driver ..
Adding page store pool ..
PagestoreAddr(IMR Start Address) = 0x04899000
pageStoreSize(IMR Size)          = 0x00080000

*** Ready to receive application ***

U-Boot 2014.04 (Jun 19 2015 - 12:05:55)

       Watchdog enabled
DRAM:  980.6 MiB
MMC:   tangier_sdhci: 0
In:    serial
Out:   serial
Err:   serial
Hit any key to stop autoboot:  0
Target:ifwi
Partitioning already done...
Partitioning already done...
Saving Environment to MMC...
Writing to redundant MMC(0)... done
GADGET DRIVER: usb_dnl_dfu

I have no idea what to do next.

I fixed it by following these steps (through trial and error, I don't really understand what I did but it works ...)

I am using Windows 8.1, 64 bit edition.

Download the Edison firmware from https://software.intel.com/en-us/iot/hardware/edison/downloads. For me it was http://downloadmirror.intel.com/25028/eng/edison-image-ww25.5-15.zip.
Extract the zip file.
Start the Windows Command Prompt as Administrator.
The extracted archive should contain a file called "flashall.bat". Change to the directory containing the file.
Connect all micro-USB ports and the barrel connector. At this point Windows did not recognize the Edison as a flash disk. This is part of what I was fixing.
Follow the steps in my question until the output on the console (also from my question) appears.
Run "flashall --recovery"
Run "flashall". When "Please plug and reboot the board" appears, disconnect the A (or middle) USB port and the barrel connector for the power. At this point everything is switched off. Then reconnect A and the barrel connector to reboot the board.
Wait about 5 minutes for the rest of the process to run automatically.

At this point everything should work again.

You should see this on the command line in Windows:

C:\Users\_\Desktop\edison-image-ww25.5-15>flashall --recovery
Starting Recovery mode
Please plug and reboot the board
Flashing IFWI
!!! You should install xfstk tools, please visit http://xfstk.sourceforge.net/

C:\Users\_\Desktop\edison-image-ww25.5-15>flashall
Using U-boot target: edison-blankrndis
Now waiting for dfu device 8087:0a99
Please plug and reboot the board
Dfu device found
Flashing IFWI
Download        [=========================] 100%      4194304 bytes
Download done.
Download        [=========================] 100%      4194304 bytes
Download done.
Flashing U-Boot
Download        [=========================] 100%       237568 bytes
Download done.
Flashing U-Boot Environment
Download        [=========================] 100%        65536 bytes
Download done.
Flashing U-Boot Environment Backup
Download        [=========================] 100%        65536 bytes
Download done.
Rebooting to apply partiton changes
Dfu device found
Flashing boot partition (kernel)
Download        [=========================] 100%      6111232 bytes
Download done.
Flashing rootfs, (it can take up to 5 minutes... Please be patient)
Download        [=========================] 100%    566330368 bytes
Download done.
Rebooting
U-boot & Kernel System Flash Success...
Your board needs to reboot to complete the flashing procedure, please do not unplug it for 2 minutes.

C:\Users\_\Desktop\edison-image-ww25.5-15>


Compiling code via terminal How can I compile my code via terminal? I am working on a Chrome app that allows you to write, compile, and upload code to an Arduino, and I need to know this so I can use the command line compiler on my Linux server. Mac or Linux terminal, it doesn't matter.

Assuming an AVR-based Arduino, you would need the avr-gcc compiler, the
avr-libc and the Arduino libraries. Also avrdude if you want to upload.
The only issue is that the commands used for the build process are quite
long (lots of options). You can see them by enabling verbose compilation
in the IDE. Thus you will probably want some way to automate the whole
thing.

There are several options for this. The most straightforward seems to be
the arduino-builder command-line tool. This is part of the Arduino
project and should ensure maximum compatibility. Otherwise you could use
a plain old Makefile. I personally use Sudar Muthu' Makefile. It can
be installed on a Debian-based Linux distribution by:

sudo apt install arduino-mk

It is not fully compatible with the classic Arduino build process
though: it does automatically include <Arduino.h> into your sketch,
but it does not add forward declarations. Some prefer it this way, as
the automatic inclusion of forward declarations is somewhat buggy and
does not play well with some C++ features.


Brand new to Arduino, and can't even make an LED blink So I'm going through Getting Started With Arduino. I skipped to making a LED blink when you press a button.

First I wrote the code, then I copied it directly from the .pdf I have, neither has worked.

The code is here:

// Example 02: Turn on LED while the button is pressed
const int LED = 13;   // the pin for the LED
const int BUTTON = 7; // the input pin where the
                      // pushbutton is connected
int val = 0;          // val will be used to store the state
                      // of the input pin
void setup() {
  pinMode(LED, OUTPUT);   // tell Arduino LED is an output
  pinMode(BUTTON, INPUT); // and BUTTON is an input
}
void loop(){
  val = digitalRead(BUTTON); // read input value and store it
  // check whether the input is HIGH (button pressed)
  if (val == HIGH) {
    digitalWrite(LED, HIGH); // turn LED ON
  } else {
    digitalWrite(LED, LOW);
  }
}

Other than what what Nick Gammon said that you need the resistor from the board to led, as that will cause your microcontroller pins to get damaged.

The other possible problem is the two breadboards you have put together, the power rails have not been bridged between the two boards. This means that the switch is not providing any logical state to the microcontroller.

Also the only reason why the led is show in the book as a separate thing is that it is meant as an educational exercise to make you build something, the L led will do the same thing.


How to start Arduino programming? I am totally new to and don't know where to start, I am interested in building new system with combination of hardware and software and every time I search how to make that embedded system it finally reaches to Arduino and don't know anything about that what to buy and I also have some more question like

Is one Arduino device required for each Arduino project ?
Should I have to buy more then one device for each project ?
If not then how I will make that project run without Arduino ?

An Arduino is basically a Microcontroller on a handy PCB with built-in programming interface.  It also has a simple programming environment to get you up and running quickly.

The chip on the board can be thought of as the "brain" of the system.  It's what you program and it's where you upload your software to.

  Is one Arduino device required for each Arduino project?

Yes and no.  You can't "remove" your Arduino from your project and expect it to still work - it'd be like beheading someone - they cease to function without their brain.  However you can replicate the Arduino in your system fairly easily so you don't have to embed the whole Arduino into it.  You can get a blank chip the same as is on the Arduino reasonably cheaply and program the bootloader (the serial interface for programming it) into the chip using your existing Arduino, then build a new circuit around it.  More information here:

http://www.arduino.cc/en/Main/Standalone

  Should I have to buy more then one device for each project?

That depends if your project is complex enough to warrant more than one "brain".  Using the "standalone" instructions above you could make multiple chips from one Arduino and embed them all in your one project.

  If not then how I will make that project run without Arduino?

There are other Arduino boards available that are designed to be embedded in your project.  These are much smaller than the "development" boards like the Uno etc.  They are also cheaper, being typically the absolute bare minimum you need to get you going.  These can be a great way of saving time compared to the Standalone system above, and at the same time saving money compared to using the full blown Arduino boards.  Boards include the Mini and Nano range of boards.

http://www.arduino.cc/en/Main/ArduinoBoardMini
http://www.arduino.cc/en/Main/ArduinoBoardNano


Nokia 5110 Screen Pixel by Pixel I have got this LCD screen

I'd like to be able to decide every pixel status of the screen. Do I need to work directly with the buffer or is there another method?

The 5110 Nokia LCD display is based on PCD8544. It is not possible to read the device display memory. The controller has only serial data input.

Typically a graphical device driver for that display will use an offscreen bitmap (buffer). To check the pixel status you would need to check the status in the offscreen bitmap.

Some device drivers use only text and copy font bitmap directly to the display memory. In that case you cannot check the status of the pixel (if the text is not buffered).


Having some issues with an array I am having an issue that I can't seem to get my head wrapped around.  What I am trying to accomplish is to have a minutes worth of sensor data in an array (reading every 5 seconds) so I'll have 12 values in this after one minute.

I want to keep the array to 12 values so I need to keep moving all the values in it down one index per new value hitting index [0] to make sure that each reading has a lifetime of 60 seconds on the array.  Here is my code so far:

void add_readings_to_averages() {
  // At this point, I am moving values down the array to make room at the beginning.
  for (int a = 11; a >= 0; a--) {
    Serial.print("The value at temperature_c_minute_avg[");
    Serial.print(a);
    Serial.print("] is ");
    Serial.print(temperature_c_minute_avg[a]);
    Serial.println();
    if (a == 11) {
      Serial.println("At 12 so need to overwrite this value");
    }

    if (a <= 10) {
      Serial.print("a is ");
      Serial.println(a);
      temperature_c_minute_avg[a] = temperature_c_minute_avg[a + 1];  // This moves each entry down one index in the array creating an empty space at index[0]
    }

    if (a == 0) {
      temperature_c_minute_avg[a] = temperature_c;
    }
  }

I've loaded my array at the time of initialization with some dummy data so I could see what was going on.  First run displays as you would expect.

The value at temperature_c_minute_avg[11] is 120.00
At 12 so need to overwrite this value
The value at temperature_c_minute_avg[10] is 110.00
a is 10
The value at temperature_c_minute_avg[9] is 100.00
a is 9
The value at temperature_c_minute_avg[8] is 90.00
a is 8
The value at temperature_c_minute_avg[7] is 80.00
a is 7
The value at temperature_c_minute_avg[6] is 70.00
a is 6
The value at temperature_c_minute_avg[5] is 60.00
a is 5
The value at temperature_c_minute_avg[4] is 50.00
a is 4
The value at temperature_c_minute_avg[3] is 40.00
a is 3
The value at temperature_c_minute_avg[2] is 30.00
a is 2
The value at temperature_c_minute_avg[1] is 20.00
a is 1
The value at temperature_c_minute_avg[0] is 10.00
a is 0
2018/11/2 11:4:39  -  Running for a total of 0 hours 0 minutes and 7         seconds

But the second time through the loop() my array is trashed.

The value at temperature_c_minute_avg[11] is 120.00
At 12 so need to overwrite this value
The value at temperature_c_minute_avg[10] is 120.00
a is 10
The value at temperature_c_minute_avg[9] is 120.00
a is 9
The value at temperature_c_minute_avg[8] is 120.00
a is 8
The value at temperature_c_minute_avg[7] is 120.00
a is 7
The value at temperature_c_minute_avg[6] is 120.00
a is 6
The value at temperature_c_minute_avg[5] is 120.00
a is 5
The value at temperature_c_minute_avg[4] is 120.00
a is 4
The value at temperature_c_minute_avg[3] is 120.00
a is 3
The value at temperature_c_minute_avg[2] is 120.00
a is 2
The value at temperature_c_minute_avg[1] is 120.00
a is 1
The value at temperature_c_minute_avg[0] is 0.00
a is 0
2018/11/2 11:4:44  -  Running for a total of 0 hours 0 minutes and 12     seconds

The entire array was overwritten with the last value and the new value was not added.  The array itself is setup as a global variable.  The initialization at the top.

float temperature_c_minute_avg[12] = {10.0,20.0,30.0,40.0,50.0,60.0,70.0,80.0,90.0,100.0,110.0,120.0};

What am I missing here?  Been staring at this for some time, but this is the first time I've tried to use an Arduino array so I can totally believe the issue is PBKAC! :)

Your issue is a C programming issue and has nothing to do with the Arduino specifically.  You should research how to implement a circular buffer.  You don't want to move around the values within the array, but rather just increment array index values.  Keep two index values, one of the current index position (the place where the next recorded value will be placed) and another of the number of values recorded.  Eventually the number of values recorded will be equal to your maximum array size and only the index position will increment.  When the array index exceeds the maximum array size it wraps back to 0.


Arduino and solar panel How can I charge 12V Li-ion or lead acid batteries using a solar panel? I also wish to interface the three, i.e. the Arduino, the solar panel and the battery, together so that the Arduino is basically driven by the battery but as the battery discharges, the solar panel would charge it. What circuitry do I need? Also tell the specifications of the solar panel.

There are lots of circuits for charging a SLA battery from a solar cell.  You need 14.4V input, so you need to ensure that the output of you solar cells is going to be at least 14.4 for enough hours to charge your battery. This means you will need to know the output current of your charging circuit and do a fair bit of maths.

Charging a lipo battery will probably be more tricky.  I would look at using a USB to LiPo charge regulating circuit and then generate a constant 5v from you solar cells.

You could also look at getting a COTS solar charge regulator, that allows you to connect the cells, load and battery and it does all the hard work for you.


Converting TinkerKit to native Arduino pins Over the years, I have acquired many TinkerKit modules for my Arduino Uno. My only issue is that I need to find a way to code using the native syntax, and not the less-powerful TinkerKit variation. To do this, I need to know if TinkerKit maps its 3-pin connector to the Arduino Board's pins (ex: 1, 3, 5). If it does, what are the mappings?

Thanks in advance!

The TinkerKit Sensor Shield helps understand the mapping. There is also the TinkerKit Header File with symbol mapping.


Rechargeable USB "AA" Batteries. Has anyone used them? I have a cosplay project where I'm creating a "Megaman" aka Rockman type of arm cannon (it's actually based on DC's Cyborg). Anyhoo, I've been weighing options like using 3xAA alks or 4xAA nicd (or otherwise 1.2V)--inclcuding various combinations of less or more cells with a voltage regulator; boost up or step down as appropriate.

there are 4 lighted segments (15 leds of WS2812B x 4). I also of course have to power the Arduino Nano as well. I'm flexible on led brightness so I'm just going to tune it [code it] to whatever looks adequate for my purpose. I am aware of the 50ma draw of these units at full brightness

My original plan was to just keep it easy (read lazy) and use 3 AA alks per 2 segments, and another 3 so the nano can have it's own supply. So 9 cells in total (without any additional regulation). Before you judge me--weight, volume, and especially area are definitely big factors in my decision.

So that's a long way to get to my actual question. Has anyone used these new types of USB rechargeable batteries? They seem to have the best of both worlds with the power of an alkaline but the consistency and sustainability of a NiMH /NiCD as they have internal regulators that produce a steady 1.5v (until they don't--which I'm more than cool with)

Short of having a properly regulated 5v power supply, are these a good option if I want to be slightly more responsible than throwing in whatever other AAs I have lying around? They definitely check the box on my space/mass requirements. I'm sure they do fine with most consumer electronics, but as far as arduino and any other custom/hobby 4.5-5v applications how reliable are these? Even if you haven't used them before I'd be curious of your thoughts. I'm a novice at best when it comes to elec engineering.

Yes, they are expensive. Thanks all!

examples:
https://www.amazon.com/Rechargeable-Batteries-Quick-Charge-Integrated-Protection/dp/B07F27PK2M/ref=sr_1_5?crid=1RTQUCZYG4KBM&dchild=1&keywords=usb+aa+batteries+1.5v&qid=1588280164&sprefix=usb+aa%2Caps%2C242&sr=8-5

https://www.amazon.com/Blackube-Rechargeable-Batteries-Lithium-1500mAh/dp/B07D9K2H9H/ref=sr_1_11?dchild=1&keywords=usb+aa+batteries+1.5v&qid=1588282813&sr=8-11

Those "batteries" are actually a 3.7V¹ ~750mAh Lithium rechargeable cell with a 1.5V switching regulator and 5V charge circuit built in.

In about the same space as one of those, if you throw away the charge circuit and switching regulator, you can get a single 18650 Lithium rechargeable cell at 3.7V¹ (nominal) and three times the capacity. Two of those plus a small 5V switching regulator² would give you more power capacity and longer run time in a smaller space than the equivalent voltage of these strange "batteries".

¹ Nominal

² Use a good one with a Li-Ion battery protection circuit and maybe a built in 2S charger too for convenience


How can I receive signal from remote control using tcrt5000 sensor module how can I use tcrt5000 sensor module instead of TSOP31238 (TSOP1738) IR receiver to get signal from remote control? I want to create remote control for my PC to navigate through my slide shows. Thanks in advance.

The TCRT5000 and the TSOP31238 are very different. The TCRT5000 is actually a reflective distance sensor. It has an IR LED and a simple IR phototransistor, not more. The TSOP31238 in contrast is meant to receive data from IR remotes. IR remotes work with modulation of IR light. The IR LED is pulsed with a frequency of 38kHz (in the case of the TSOP31238). This frequency is modulated with the actual data, meaning there are different time lengths were there is no IR signal and where there is a 38kHz IR signal.

The TSOP31238 detects the IR light with a phototransistor, like the TCRT5000 has. But then the signal is processed with an amplifier, a band pass to filter out all frequencies but the 38kHz and then demodulated, so that you don't see the 38kHz signal on the output, but only the pulse lengths.

The demodulation should actually be the least complex part to build yourself. That can be even done by code. But to get good results, you also need the other parts. You would have to build an amplifier circuit with an opamp. And would have to build the bandpass (for example with an LC element).

You can build these things yourself, but: The sensor, that you have, is not meant for receiving IR remote signals. The parts, that you would need to make the signal usable, will cost way more, than just buying a TSOP. Also it will be a lot easier and most likely better working (processing the signal from a phototransistor can be tedious). I suggest, that you buy a TSOP chip fitting to your remote control.


Multiple upload/ Synchronization problem I am trying to do an experiment with Arduino Uno r3 board plus a 2-channel relay shield. What I need to do is to alternatively turn on and off the relay shields. So, it requires multiple compile and upload of the program to assign values to corresponding pins. What I have seen by now is that uploading the program to Arduino is a kind of painful process and it requires nothing to be connected to pins 0 and 1 to prevent synchronization errors. So, I was wondering how I can do my experiment without having to mount/unmount relay shield each time I want to upload a new program into it.

Thanks in advance

Well, you can write a program that takes numbers out of Serial input.

int pin1 = Serial.parseInt();
int pin2 = Serial.parseInt();
// etc., etc.

Simple.


Bare Metal Programming of Due I don't know much about Arduino but I am interested in buying a Due 32bit board. I was wondering if you can program it bare-metal and if this requires a separate debugger or not?
Thanks

In my understanding all ic in general can be hardwired but at a cost which is that some greater expense is incured say time or additional accessories also the datasheet and instruction set are a big must


Interfacing with SPI I am attempting to program an Arduino to interface with a DAC, specifically the AD7390 made by Analog Devices.

I have tried using the SPI library as a means of realising the interface but am confused by the PIN layout of the DAC. It provides me with SCK, SDI, CLR and LD pins.

The LD (Load Strobe) PIN is used to transfer buffers from the chip's on-board shift register to its DAC register.

The CLR PIN is used to forcibly clear the DAC register.

The documentation claims that the device is SPI compatible but, using these PINs with the Arduino Mega2560 as a micro-controller, only partially works and I am concerned that the circuit requirements of the SPI library are not being satisfied. In SPI documentation, a SS (slave select) PIN is universally mentioned but is not present with my device.

As I have managed to get the CLR PIN working, consistently and as expected, I wonder if a manual approach - i.e. using shiftIn() instead of the SPI library - is the way to go.

Any suggestions or advice would be appreciated.

The AD7390 data sheet timing diagrams show that /LD is in effect a slave select, but an active high one.

Specifically, it says that while /LD is high, each rising clock edge causes "Shift-Register-Data Advanced One-Bit", while when it is low, the shift register data is transferred to the DAC.

So basically you would need to use SPI in a mode where the slave select is controlled by software and asserted with the opposite of the usual polarity, but the actual shifting of the data can be accomplished with the hardware SPI engine.

It does not seem that you are always required to use the /CLR input - if you don't want to use it, wire it high.  Otherwise, you can connect it to a GPIO, take it low, and then raise it so that the rising edge causes an asynchronous clear.


Can Arduinos keep a 500mu timer? I need to output a serial message on a 500 microsecond interval (10 bytes), can be a little slower but no more than 1 milisecond between messages.

Can it be done with an Arduino? I know there is a delayMicro(), but not sure if it has the resolution.

It's not related to the delayMicro, but to the max speed of the Serial/UART driver, which is not documented, but according to some people it can reach 500 kbps.

However, 10 bytes, each 500 us (2000 Hz) means 10 * 11 (including some stop/start bit) * 2000 = 220.000 bits, so you have some headroom left. Maybe there is also some timing overhead.

Anyway, probably the only way to go is using an interrupt, and expect the Uno is not able to do anything else.

A better option might be to send less or send smarter (i.e. not 10 bytes, but maybe some compressed/binary form if not already thought about).


Connecting battery and LED to Arduino Due I am brand new to Arduino/robotics and am trying to take baby steps. First I'd like to just power an Arduino and an LED from a 9V battery like so:

No programming, just simple circuitry. The battery powers the Due, and the Due in turn powers the LED.

A few concerns here:

Will the 9V battery fry the Due, which I believe is expecting 3.3V? If so, what can I do to reduce the voltage/amps?
Will the 9V battery fry the resistor and/or LED?
As you can see by my question marks, I'm not real sure where to connect the battery to the Due (both positive & negative terminals) as well as the where to connect the breadboard to the Due (again, both terminals).

Any ideas?

What you want is something like this (ignore the fact that my mini breadboard is stuck to a shield):

My starter Arduino kit came with the connector for the 9 volt battery into the power socket on the Arduino, you may need to make one.  You cannot connect the 9V battery to any other part of the Due that I am aware of (without damaging it!).

It is perfectly safe to power your Arduino with 9V this way, there is circuitry to step the voltage down to the 5V and 3.3V that the board requires.

In the connector strip nearest this power socket (labelled Power on my board) there are a couple of Gnd connections and 5V and 3.3V connectors perfect for what you want to do.  I have used the 3.3V connector in my photo, but the 5V one should also be fine with the right resistor.

In your picture you don't appear to have anything connecting the LED to ground, but other than that, if you were to connect the battery up as I have shown and the red and black LED connectors to 3.3V and Gnd respectively, it should work as desired.

As a next step, you could load the sample sketch Examples->01Basic->Blink, write it to your Due, move the red LED connecting wire to pin 13 on the opposite side and your LED would flash (along with one of the LEDs on the Due board itself).

Edit (to specifically address your concerns):

The 9V battery will not fry the Due if it is connected through the power socket, which has circuitry to drop the voltage to safe levels.
The 9V battery will not damage the LED or resistor as they are connected to 5V or 3.3V that the Due outputs, not the 9V from the battery.
Only connect the battery through the power socket.  If you have a good quality steady 5V power supply, you can power the board through a 5V pin (at least I have been able to), but you bypass the voltage regulation circuitry that way and it is not recommended.  Connect the black wire from your LED to any Gnd pin, connect the red wire from the LED to 3.3V or 5V.

Additional edit:
You can connect the battery directly to the Arduino Due board without needing a plug to connect to the power socket.  Connect the red battery wire to the Vin pin and the black battery wire to a Gnd pin.


Fading from color to color using for-loop FastLEDs I'm attempting to fade a strip of ws2812 7 pixels in length. Below I am using a for loop to increment the color red. I can fade it to red (from blue) but it will do it one pixel at a time or it just stays blue, depending where I move my r for-loop to. I need it to fade from color to color all 7 LEDs at once.

I get no errors.

I don't understand the process of getting NUM_LEDS leds all into x then proceeding with my color changing. Seems like I'm grabbing one pixel, fading it to red, then another...

fastLeds 3.03 library, arduino 1.0.6

#include <FastLED.h>
#define DATA_PIN 6
#define NUM_LEDS 7

#define BRIGHTNESS 45
#define COLOR_ORDER GRB
#define g 50
#define b 100
int r;
CRGB leds[NUM_LEDS];

void setup(){
  FastLED.addLeds<WS2811, DATA_PIN, GRB>(leds, NUM_LEDS);
}

void loop(){
  for(int x = 0; x < NUM_LEDS; x++){
    delay(10);
    leds[x] = CRGB(r,g,b);
  }
  FastLED.show();
  delay(10);

  //-------------------------

  for(int x = 0; x < NUM_LEDS; x++){
    for(int r = 0; r < 254; r++) {

if NUM_LEDS is holding the number 7 why can't I just do it like this below: leds[NUM_LEDS]?

      leds[x] = CRGB(r,g,b);
      FastLED.show();
      delay(100);
    }
  }
}

If you want to fade all the LEDs form blue to red at the same time, I think you want code like this (explanatory comments embedded)...

#include <FastLED.h>
#define DATA_PIN 6
#define NUM_LEDS 7

#define COLOR_ORDER GRB

CRGB leds[NUM_LEDS];

void setup(){
  FastLED.addLeds<WS2811, DATA_PIN, GRB>(leds, NUM_LEDS);

}
void loop(){

  // Let's take 256 steps to get from blue to red
  // (the most possible with an LED with 8 bit RGB values)

  for( int colorStep=0; colorStep<256; colorStep++ ) {

      int r = colorStep;  // Redness starts at zero and goes up to full
      int b = 255-colorStep;  // Blue starts at full and goes down to zero
      int g = 0;              // No green needed to go from blue to red

      // Now loop though each of the LEDs and set each one to the current color

      for(int x = 0; x < NUM_LEDS; x++){
          leds[x] = CRGB(r,g,b);
      }

      // Display the colors we just set on the actual LEDs
      FastLED.show();

      delay(10);
  }

}


How does WiFiServer.status() work? What are the possible outcomes of calling status() on a WiFiServer from ESP8266WiFi.h? The only documentation I could find only says it returns uint8_t. Here's the link.

The basic set of functions of the esp8266 WiFi object follows the API of the Arduino's first WiFi library for Arduino WiFi Shield. It is documented here.

The esp8266 implementation of status() focuses on state of the STA and maps SDK status to some of Arduino documented codes.

wl_status_t ESP8266WiFiSTAClass::status() {
    station_status_t status = wifi_station_get_connect_status();

    switch(status) {
        case STATION_GOT_IP:
            return WL_CONNECTED;
        case STATION_NO_AP_FOUND:
            return WL_NO_SSID_AVAIL;
        case STATION_CONNECT_FAIL:
        case STATION_WRONG_PASSWORD:
            return WL_CONNECT_FAILED;
        case STATION_IDLE:
            return WL_IDLE_STATUS;
        default:
            return WL_DISCONNECTED;
    }
}


How to interface ESP8266-01 Wifi Module with Arduino Uno I have an Arduino Uno and ESP8266-01 Wifi module with me currently. So I'm going to use ESP8266 to connect to the MQTT broker to allow me publish data to other devices. However, I have a problem with uploading my sketch due to the following error:

error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

I uploaded the example sketch WIFIScan provided by Arduino IDE to test ESP8266 whether working or not, so the code is not a problem. This is how I connect ESP8266 to the laptop.

The Arduino Uno is connected to my laptop through USB port.


Am I Running Out of RAM Or Not? I'm attempting to drive 300 TM1803 RGB LEDs from an Arduino Uno using the FastLED library. My code works fine for 100 LEDs, but when I go to 150, the arrays that store LED values and my sensor data get corrupted, causing the LEDs to flash colors randomly every few seconds. From what I've read these are exactly the symptoms of running out of RAM, leading to something overwriting the RAM that contains my arrays.

However, with 150 LEDs, the MemoryFree library says I'm only using 920 bytes of RAM, no matter where in my code I measure, and the IDE says 880. Does anybody know what's going on? Is there something using 1100 bytes of RAM for a very short amount of time, so that I can't measure it?

My code:

#include "FastLED.h"
#include <MemoryFree.h>

const byte ledsPin = 3;
const byte sensorPin = A1;

const int numLeds = 300;
const int ledTime = 1000;

const int sensorMin = 0;
const int sensorMax = 512;

const CRGB correction = CRGB(80,255,70); // Cool white
//const CRGB correction = CRGB(160,255,20); // Warm white
const byte hOffset = 170; // baseline hue value
const int8_t hDirection = -1; // 1 or -1, direction of rainbow
const byte s = 255; // saturation (colorfulness)
const byte v = 255; // value (brightness)

const unsigned int arrayLength = numLeds+1;
byte hues[arrayLength];

CRGB leds[numLeds];
byte h = 0; // hue (color)

unsigned long sensorSum;
unsigned int loopCounter;
unsigned int arrayCounterLed;
unsigned int updatesPerLed;
char sp = ' ';
int arrayCounter;

unsigned long time;
unsigned long timeNextLed;
unsigned long timeLeft;
unsigned long time1;
byte route;

void setup() {
  FastLED.addLeds<TM1803, ledsPin, RBG>(leds, numLeds).setCorrection(correction);
  FastLED.setDither(0);
  pinMode(ledsPin, OUTPUT);
  Serial.begin(115200);
}

void loop() {
  delay(10);
  time=millis();
  sensorSum += analogRead(sensorPin);
  loopCounter++;
  if(time >= timeNextLed) {
    timeNextLed = (time/ledTime+1)*ledTime;
    arrayCounter = (arrayCounter +1) % (arrayLength);
    hues[arrayCounter] = (constrain(map(hDirection*sensorSum/loopCounter, sensorMin, sensorMax, 0, 239), 0, 239)+hOffset)%256;
    updatesPerLed = loopCounter;
    loopCounter=0;
    sensorSum = 0;
  }
  for(int led = 0; led < numLeds; led++) {
    time1=micros();
    arrayCounterLed = pseudoMod(arrayCounter - led -1, arrayLength);
    timeLeft = timeNextLed-time;
    byte dist = abs(hues[arrayCounterLed]-hues[(arrayCounterLed+1)%(arrayLength)]);
    if(abs(hues[arrayCounterLed]-hues[(arrayCounterLed+1)%(arrayLength)])<=128) { // if it doesn't cross through 0
      h = (hues[arrayCounterLed]*timeLeft + hues[(arrayCounterLed+1)%(arrayLength)]*(ledTime-timeLeft))/ledTime;
    }
    else if(hues[arrayCounterLed] > hues[(arrayCounterLed+1)%(arrayLength)]) { // if it crosses through 0 forwards
      h = ((hues[arrayCounterLed]*timeLeft + (hues[(arrayCounterLed+1)%(arrayLength)]+256)*(ledTime-timeLeft))/ledTime)%256; // Causing flashing on red pixels?
    }
    else { // if it crosses through 0 backwards
      h = (((hues[arrayCounterLed]+256)*timeLeft + hues[(arrayCounterLed+1)%(arrayLength)]*(ledTime-timeLeft))/ledTime)%256;
    }
    time1 = micros() - time1;
    if(led == 0) {
      Serial.print(dist);
      Serial.print(sp);
      Serial.print(route);
      Serial.print(sp);
      Serial.print(timeLeft);
      Serial.print(sp);
      Serial.print(hues[arrayCounterLed]);
      Serial.print(sp);
      Serial.print(hues[(arrayCounterLed+1)%(arrayLength)]);
      Serial.print(sp);
      Serial.print(hues[arrayCounterLed]*timeLeft);
      Serial.print(sp);
      Serial.print(hues[(arrayCounterLed+1)%(arrayLength)]*(ledTime-timeLeft));
      Serial.print(sp);
      Serial.println(h);
    }
    leds[led] = CHSV(h, s, v);
  }
  FastLED.show();
  Serial.print(updatesPerLed);
  Serial.print(time1);
  Serial.println();
}

int pseudoMod(int a, int b) {
  if(a<0) {
    return a+b;
  }
  else {
    return a;
  }
}

I found it! I was returning an int8_t variable from my mod function, causing me to not be able to iterate over more than 126 LEDs. Now this little Arduino Uno is maxing out it's RAM at 409 LEDs!


MATLAB - Read from 2 SPI inputs synchronously I am using the MATLAB Arduino Support Package to create a setup where I can read force data from a load cell and positional data from an incremental encoder - then plot them on MATLAB. It must be done at the same time in order to produce a material stress-strain curve.

I am thinking of using the SPI Device functions to do this.

Can the data from the load cell and encoder be read synchronously?

Yes and No.
 Synchronously in development slang means step-by-step execution. Asyncronously mean by some event.

Arduino has only one core. Even if you use interrupt, Arduino can only execute one command at once.

Best way for you I guess would be read both on Arduino and combine into single value to read at once. Just reading both with readDigitalPin  would give huge latency.


Using the LED pin for input I have an Arduino-like device with few GPIO pins (DigiSpark clone). It is based on an 8-pin AtTiny85 IC so there are Power, Ground and six other pins, two of those six are being used for USB keyboard simulation which leaves 4 GPIO which I want to connect 4 buttons to with minimal circuitry. The normal way to do this is to enable the internal pullups and have the buttons connect the pin to ground. This works well for most pins.

The problem is the equivalent to Pin 13 (Pin 1 in this case) which is connected via a resistor and LED to ground. The internal pullup is too weak to raise the voltage enough. Consequently that pin always appears to be in a "button pressed" state.

One solution is to cut the tracks connecting the LED, but the board is so tiny and crowded that I doubt I have the eyesight and steadiness of hand to do this.

Problematic resistor + LED are at bottom right of AtTiny85 IC

It occurs to me I could either

Add an external pullup to this input,
Change the button wiring so when pressed, it connects the pin to 5v. Change the code to look for high, not low.

Are there any problems with either of these approaches?

In the end, stimulated by Majenko's advice to desolder the LED,  I instead carefully studied the PCB layout online, checked that it corresponded to my PCB, checked the location of nearby traces I didn't want to cut and then used multiple magnifying glasses and a fresh blade in my smallest utility knife and carefully cut the track leading from the LED to the IC. All was well.


C++ State Machine / Wpmf-convesion I'm quite a newbie using C ++. I am trying to implement in C ++, the state machine described in this link for C language:
https://barrgroup.com/Embedded-Systems/How-To/Coding-State-Machines.

I have created an Fsm class, which implements the behavior of the state machine, and a Machine class, whose methods will be the states.

The code works, but it generates a warning (-Wpmf-conversions) when I try to save the memory address of a Machine method, in State state__

class Fsm
{
public:
    typedef void (*State)();
private:
    State state__;
public:
    Fsm(State state);
    void dispatch();
};

Fsm::Fsm(State state)
{
    state__ = state ;
} //Fsm

void Fsm::dispatch()
{
    (*state__)() ;
}

class Machine : public Fsm
{
public:
    Machine() : Fsm((State)&Machine::initial) {}       // ctor
};

I'm using an Atmega2560, with AVR-GCC compiler.

A pointer to a member function is not allowed in C++. GCC can allow it, but moans at you because it's non-standard.

In C++ the normal way of dealing with the kind of thing you want is through class inheritance.

Typically you would create your base Fsm class that implements the basic functionality of your state machine control, then overlay over the top of that (create a new class that inherits the Fsm class) another class that implements your specific machine functionality.  You can declare functions in your base Fsm class that are pure virtual - that is, they exist, but have no body. It's then the job of the child class to actually implement that functionality.  The parent Fsm class then knows about those functions and can call them.

So you would have something like:

class Fsm {
    public:
        void dispatch();
    protected:
        virtual void initial() = 0;
};

void Fsm::dispatch() {
    initial() ;
}

class Machine : public Fsm {
    protected:
        void initial() {
             Serial.println("Here");
        }
};

Machine mach;

mach.dispatch(); // --> "Here"

Fsm knows about initial(), but the function hasn't been further defined.  Machine implements initial().  You then create an instance of Machine which contains everything needed.  Calling dispatch() runs the function in the Fsm parent class which then calls initial() in the child Machine class.


ESP8266-01 wrong flow control settings Changed ESP8266-01 to wrong settings by mistake. It was working ok
at 115200 (its default settings). It was connected like this:

PC->(USB)->Arduino->ESP8266.

Using Arduino as bridge

Pins 0 and 1 (RX/TX) connected directly to ESP8266 since I didnt have
USB to TTL adapter.
MCU removed so I could make that scenario work

It was just for testing AT commands. I did it like that because I realized that I was getting errors all the time trying to connect
using SerialSoftware (and different pins in Arduino).

Found out later that SerialSoftware does not work correctly at 115200...

So I issued the following AT command:

         AT+UART_DEF=9600,8,1,0,3

Now I cannot connect to the ESP8266 to correct that setting. All I get is garbage characters. I understand it's because of the flow control settings. I set it to both RTS and CTS which I also read later ESP8266 does not support?

Have tried:

Using Putty to change settings of COM port at connect. Have tried all speeps and flow control settings combinations I could think of. I get nothing or garbage characters.
Changing COM port setting from Device Manager (Windows 7)
Flashing ESP8266 using official tool (ESPFlashDownloadTool_v3.6.1.0).It won't sync with the ESP8266. It does not allow me to adjust speed to 9600. Minimun speed that show is 115200
Changing settings in ESPFlashDownloadTool_v3.6.1.0 so it will sync at 9600 (file: spi_download.conf)

I cannot think of anymore ideas. Have I completely messed up my ESP8266?

Is there a way that I'm not aware of that could fix this problem? How?

Thanks in advance!

Jorge

AT+UART_DEF=9600,8,1,0,3

Are you aware that this configuration (3) as a rule would require both RTS and CTS extra physical signals to work ? That means, if you do not connect anything there, the level present at some pin configured anywhere would prevent ESP8266 from receiving further data from serial.

In general people use "no flow control" (0)

AT+UART_DEF=9600,8,1,0,0


Arduino Yun's sample "Bridge" code not working I'm new to the Arduino world (or the electronics world for that matter).

I have the Arduino Yun and the WifiStatus code works fine (so does the HttpClient).
But every time I try to run the bridge sample code, all I see is the pin 13 led light up, and the browser commands don't work.

PS: I have updated the open-wrt to ver. 1.3.

Any thoughts on why this would be happening?

Edit 1:

I have tried to reboot arduino using the hardware switches as well as from the web console. The blink sketch works fine, so does the WifiStatus code and the HttpClient code.

The other problem I face after every few uploads is that the IDE is stuck at "Uploading...". I have tried to give it more time (even an hour). But then I had to unplug it from the Mac and restarted. Then it worked but only for a few times.

But this problem is not specific to the Bridge code. The uploading issue has occurred with other sample code as well. But at least the code worked.

Edit 2:

This is the result from the command ls /dev/tty.*

/dev/tty.Bluetooth-Incoming-Port    /dev/tty.usbmodem1431
/dev/tty.Bluetooth-Modem

I ended up doing two things. First I got a replacement hardware. That made the bridge code start working.

And I also changed the port from /dev/tty.usbmodem1431 to /dev/cu.usbmodem1431. As shown in the picture below. That fixed the issue with IDE getting stuck at "Uploading...".

Not sure if this fix will last.


How to serve multiple connections with an ESP8266 and an Adruino? I want to make a server using an ESP8266 (12e) and an Arduino Nano.
I have got everything hooked and I created a minimal "Hello World" example, based on a number of samples found on the web, which is working fine... as long as the ESP does not receive multiple requests simultaneously.

I am using SoftwareSerial on pins 8 and 9 of my Arduino Nano.

As long as I send one request at the time, things work fine.
If I use two browsers and send two requests with little interval, things go wrong, and that figures: the sendData() method just reads from the serial connection. It will consume the new request while waiting for an "OK" from the initial request...

Is there any sample code or library (for ESP + Arduino (nano)) that can handle correctly multiple concurrent connections?

Thanks

My code:

/*
  Software serial multple serial test
 */
#include <SoftwareSerial.h>

#define DEBUG true

SoftwareSerial esp8266(8, 9); // RX, TX

void setup() {

  Serial.begin(9600);
  esp8266.begin(9600); // your esp's baud rate might be different : 115200

  Serial.println("Setup...");

  /*
  sendData("AT+RST\r\n",2000,DEBUG); // reset module
  sendData("AT+GMR\r\n",1000,DEBUG); // get version
  sendData("AT+CWMODE=2\r\n",1000,DEBUG); // configure as access point
  sendData("AT+CIFSR\r\n",1000,DEBUG); // get ip address
  sendData("AT+CIPMUX=1\r\n",1000,DEBUG); // configure for multiple connections
  sendData("AT+CIPSERVER=1,80\r\n",1000,DEBUG); // turn on server on port 80
  */

  sendData("AT+RST\r\n", 2000,DEBUG);
  sendData("AT+GMR\r\n", 1000, DEBUG);

  sendData("AT+CWMODE=1\r\n",1000,DEBUG); // configure as station
  sendData("AT+CWJAP=\"******\",\"*******\"\r\n", 6000, DEBUG);
  sendData("AT+CIFSR\r\n",1000,DEBUG); // get ip address
  sendData("AT+CIPMUX=1\r\n",1000,DEBUG); // configure for multiple connections
  sendData("AT+CIPSERVER=1,80\r\n",1000,DEBUG); // turn on server on port 80

  Serial.println("Setup ready.");
}

//WIRE RESET TO HIGH!!?

void loop() { // run over and over

if(esp8266.available()) // check if the esp is sending a message
  {

    if(esp8266.find("+IPD,"))
    {
     delay(1000);

     int connectionId = esp8266.read()-48; // subtract 48 because the read() function returns
                                           // the ASCII decimal value and 0 (the first decimal number) starts at 48

     String webpage = "
Hello World!
";

     String cipSend = "AT+CIPSEND=";
     cipSend += connectionId;
     cipSend += ",";
     cipSend +=webpage.length();
     cipSend +="\r\n";

     sendData(cipSend,1000,DEBUG);
     sendData(webpage,1000,DEBUG);

     String closeCommand = "AT+CIPCLOSE=";
     closeCommand+= connectionId; // append connection id
     closeCommand+="\r\n";

     sendData(closeCommand,250,DEBUG);
    }
  }

}

String sendData(String command, const int timeout, boolean debug)
{
    String response = "?";
    int pos = -5;

    Serial.println("--------------");
    Serial.println(" sending "+command);

    esp8266.print(command); // send the read character to the esp8266

    long int _timeout = timeout + millis();

    while( (_timeout) > millis())
    {
      while(esp8266.available())
      {
        // The esp has data so display its output to the serial window
        char c = esp8266.read(); // read the next character.
        response+=c;
        pos+=1;
        if(pos>=0 && response.substring(pos) == "\r\nOK\r\n"){
          //WE GOT OK -> stop waiting
          _timeout=0;
        }
      }
    }

    if(debug)
    {
      Serial.println(" response: "+response);
    }

    return response;
}

I might not have understood what you are trying to do, but if it is to use the ESP8266 to allow the Nano to connect to WIFI and act as a web server then I believe you are doing this the hard way.

The ESP8266 is an 80 or 160MHz microprocessor with 64KB Program Ram + 96KB data RAM.  You are using a 16/32MHz microprocessor to generate pages and pass them to it.  I would recommend that you investigate using the Arduino IDE to program the ESP8266 in "Arduino C" it comes with a set of examples that include webservers (which is what I think you are trying to do).  Keep the Nano if the ESP8266s 10 digital and one analogue ports aren't enough to interface to you hardware.


ESP8266 (ESP-01) Not booting with load on IO pin 2 I'm using an ESP-01 to control a load (SSR), which is connected to IO pin 2. This pin needs to be HIGH at boot time, otherwise the module won't boot. I've tried driving the load with an optocoupler to avoid driving the pin LOW while booting, but it's not working. Do you know of any solution to make it boot correctly without changing the IO pin? (there's only two GPIO pins, both ocuppied, plus serial port pins).

Simply invert the logic - so that LOW turns the SSR on and HIGH turns it off.

Try something like this:

simulate this circuit – Schematic created using CircuitLab

The P-channel FET will invert the logic. Pull GPIO2 LOW and it will turn on the FET which will enable the SSR. The 10KΩ resistor keeps the GPIO pin (and the gate of the FET) HIGH at other times.

If the GPIO pin can sink enough current to directly drive the SSR you can leave out the FET:

simulate this circuit

Again the logic is inverted. Pull GPIO2 LOW to sink current through the SSR to turn it on. The resistor keeps the GPIO pin held HIGH when booting.


Arduino and WS2812 RGB LED Strip "freezing" I have been working on a project as a gift for my girlfriend for Christmas which involves some a bunch of standard "white" LEDs controlled by shift registers and darlington arrays, and also some RGB LED strips (WS2812B strip, 29 LEDs on strip). Everything is going fine with the white LEDs, but not so much with the RGB ones.

If I leave the RGB leds running for a while all of the LEDs on the strip turn red, except for the first one, which continues to change color. I am not sure how long "a while" is because in "short term" testing, approximately running continuously for an hour, it works fine and all of the LEDs change appropriately, but if I leave it running overnight I wake up with the issue of all red and one single RGB "working". I then have to reset to get it working again. These RGB LEDSs need to be run for long periods (24 hours) of time without "freezing". The rest of the program (with the normal LEDs) continues to work fine despite the RGB ones not.

Let me explain how I am controlling them. V_rgb is 5V (5V - 8A power supply), which it is also grounded to. Then the data line, C, is connected to an Arduino Uno, on pin 12, which is a PWM pin.

In software, I am using a Adafruit Neopixel Library to control the RGB LEDs and write their respective colors, based off the examples given in their git repo and the tutorial here.

I have pasted my code below in case that may help, but honestly I am not sure if it is software or hardware related. (unrelated code has been removed)

#include <Adafruit_NeoPixel.h>
#define rgbPin 11
#define numRGBleds 29

Adafruit_NeoPixel strip = Adafruit_NeoPixel(numRGBleds, rgbPin, NEO_GRB + NEO_KHZ800);
int colorStep = 0;
int rgbIndex = 0;

void shiftColor() {
  int i = 0;
  for (i = 0; i < numRGBleds; i++) {
    int idx = (rgbIndex + i) % numRGBleds;
    int colorVal = round(i * colorStep);
    strip.setPixelColor(idx, Wheel(colorVal & 255));
  }
  strip.show();
  rgbIndex++;
}

uint32_t Wheel(byte WheelPos) {
  WheelPos = 255 - WheelPos;
  if (WheelPos < 85) {
    return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3);
  } if (WheelPos < 170) {
    WheelPos -= 85;
    return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3);
  }
  WheelPos -= 170;
  return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0);
}

void setup()
{
  strip.begin();
  strip.show();
  rgbIndex = 0;
  colorStep = 255 / (numRGBleds - 1);
}

void loop()
{
  shiftColor();
  delay(1000); // Redo every second
}

My thoughts of what it could be are the following, let me know if any make any sense or are known issues:

Having issues with micros() value rollover
Overheating
Noisy power supply
Defective LED strip
black magic?

Thanks in advance for any help.

UPDATE

My current solution to the problem is to just reset the board using the watchdog functionality. It reboots in a few milliseconds and sometimes flashes in the process, but I would like to figure out the real problem.

UPDATE #2

So with the reset solution, I left it running overnight and it did not freeze which leads me to think it is definitely a software, not hardware, issue. I have changed some of the wiring and coding to make sure the watchdog reset is not noticeable. It resets every half hour or so. This will make sure all of the memory is cleaned, except stuff I store in the EEPROM (which I do use to make the reset less noticeable). This reset delays processing by a few milliseconds, but time is not critical, so it is not a big deal.

I still however, would like to know a more elegant way of doing this. The software reset is a bit "hacky"

Try changing rgbIndex++; to rgbIndex=(rgbIndex+1)%numRGBleds;. I thing the problem is the int rgbIndex rollover, which occurs after about 9 hours.

Also try changing delay(1000) to delay(1). That way the problem might pop up a lot faster.


Uploading a sketch causing an error message in Arduino Uno avrdude:

  no programmer has been specified on the command line or the config
  file
           Specify a programmer using the -c option and try again

On the "Tools" menu choose "Programmer:" and specify AVRISP mkII; be sure that you've also chosen the appropriate "Board:" entry for the Uno.


SSD1306 OLED LCD Library Errors Recently i bought an "Serial 128X64 OLED LCD Display SSD1306".

I searched for available libraries and tried to find the best one to use before actually experimenting with this device.

I came across a hackaday article mentioning a "HIGH SPEED SSD1306 LIBRARY"

So that drew my attention and got on with it. This is the link to the afforementioned library for the Arduino DUE.

DayOLED_SSD1306

Right from the beginning i had some trouble with the wiring.
I wired 3.3 volts to input, GND, RES, DC, CS pins are wired according to the library example..
But the library contains no info on how to wire D0 and D1 pins. Since this OLED works both I2C and SPI, i thought maybe these two pins are ommited.

So i hooked it up, load up the example code and got compilation errors.

Here are the errors:

C:\Users\User1\Documents\Arduino\libraries\DayOLED_SSD1306-master\DayOLED_SSD1306.cpp: In member function 'virtual void DayOLED_SSD1306::drawPixel(int16_t, int16_t, uint16_t)':

C:\Users\User1\Documents\Arduino\libraries\DayOLED_SSD1306-master\DayOLED_SSD1306.cpp:114:14: error: 'swap' was not declared in this scope

     swap(x, y);

              ^

C:\Users\User1\Documents\Arduino\libraries\DayOLED_SSD1306-master\DayOLED_SSD1306.cpp: In member function 'virtual void DayOLED_SSD1306::drawFastHLine(int16_t, int16_t, int16_t, uint16_t)':

C:\Users\User1\Documents\Arduino\libraries\DayOLED_SSD1306-master\DayOLED_SSD1306.cpp:598:16: error: 'swap' was not declared in this scope

       swap(x, y);

                ^

C:\Users\User1\Documents\Arduino\libraries\DayOLED_SSD1306-master\DayOLED_SSD1306.cpp: In member function 'virtual void DayOLED_SSD1306::drawFastVLine(int16_t, int16_t, int16_t, uint16_t)':

C:\Users\User1\Documents\Arduino\libraries\DayOLED_SSD1306-master\DayOLED_SSD1306.cpp:666:16: error: 'swap' was not declared in this scope

       swap(x, y);

Anybody got a clue what is going on with the swap() function?
Maybe it's deprecated?

Anyone has managed to get this library working?
Or maybe has managed to get this Display working even with another library?

I've had good success with the u8g2 library for the small I2C OLEDs.
u8g2 on GitHub


Lowest latency triggering multiple Arduinos using NRF24L01+ I'm building a rig with multiple DSLR cameras.  I need to synchronize the cameras to take a photos with lowest possible latency.  The only constraint is we want the ability to address each camera individually if needed.

I've seen in other posts:
Choosing wireless tech for lowest possible lag

NRF24L01+ seems to be a good choice.  An answer on that post states:
sending a 32 byte payload...283µs on 2Mbps mode.

Given the  esp8266 has a clock speed of 80MHz/160MHz I'm not too concerned about the lag involved in processing the signals.

Most multi-cast information out there is for sensor arrays, so multiple out single in.  I'm after resources on single out multiple in for NRF24L01+ networks.

Added bonus of esp8266 is that non timing critical tasks such as logging and error checking could be performed over wifi so NRF24L01+ would be purely for one -way triggering.

If each camera had it's own esp8266 based board with attached NRF24L01+ hardware and was given an address in software from 0-255, is it possible to broadcast a single 32 byte packet of data where each bit would represent a camera address and have all receiver devices receive the same signal, do an AND against it's address and trigger if needed?

Yes, that should work, however also think about the following issues:

What if one (or more) camera does not receive the signal? You might need to add an ACK signal, but of course this will reduce the latency (a lot). If you don't want an ACK signal
To prevent an ACK, you can send the signal many times (and cameras who already processed the signal not react for a fixed amount of time). Of course it will received by the other cameras (at least) 283 us later.
If reliability is important, you could try using a less high speed, the latency will go up, but reality too.

Also you probably can fire the cameras even faster, if you first send the address bytes (4 bytes). And than send the shoot signal which can be in principle 1 bit. You can use one of the bits for that in case 128 cameras would suffice. Or send one byte extra which contains the signal to shoot.


ACS712 sensor reading for AC current I'm trying to track down a clearly/simply articulated piece of code to take a reading from the ACS712 current sensor (link to download PDF data sheet).

I understand that these sensors are noisy, and that reading AC current is quite different to DC current.

After looking at a range of examples in a variety of forums etc., I've based the following on http://henrysbench.capnfatz.com/henrys-bench/acs712-arduino-ac-current-tutorial/

void ac_read() {
  int rVal = 0;
  int maxVal = 0;
  int minVal = 1023;
  int sampleDuration = 100; // 100ms

  uint32_t startTime = millis();
  // take samples for 100ms
  while((millis()-startTime) < sampleDuration)
  {
    rVal = analogRead(A0);
    if (rVal > maxVal)
      maxVal = rVal;

    if (rVal < minVal)
      minVal = rVal;
  }

  // Subtract min from max to determine the peak to peak range
  // 1023 = the max value we'll get on the input (1024, zero indexed)
  // 5.0 = 5v total on adc input
  double volt = ((maxVal - minVal) * (5.0/1023.0));

  // div by 2 is to calculate RMS from peak to peak
  // 0.35355 is factor to calculate RMS from peak to peak
  // see http://www.learningaboutelectronics.com/Articles/Voltage-rms-calculator.php
  double voltRMS = volt * 0.35355;

  // x 1000 to convert volts to millivolts
  // divide by the number of millivolts per amp to determine amps measured
  // the 20A module 100 mv/A (so in this case ampsRMS = voltRMS
  double ampsRMS = (voltRMS * 1000)/100;
  Serial.println(ampsRMS);
}

I unfortunately don't have sufficient test equipment at present to validate this, but I'm getting a value of around 8.9 for a 2300W device, which afaict is roughly accurate (based on this calculator http://www.rapidtables.com/calc/electric/Watt_to_Amp_Calculator.htm).

Is anyone able to confirm the above makes sense/is logical/sane?  Is there anything obviously incorrect?

Measuring the peak-to-peak current and scaling the result will get you an answer which will at least go up and down with the magnitude of your average AC current, so yes it is NOT incorrect.  As you suggested it will be sensitive to noise from the sensor - in fact as you are taking the highest and lowest single readings the noise will always cause the measurement to be higher than actual.

However, I think you could do better.  Given that the code is already having to take many samples (basically as fast as it can) for 100mS (which will sample 5 cycles of the waveform if it is 50Hz and 6 if it is 60Hz, depending on where you are in the world), then you could actually do the maths to measure the RMS value and by basing this on all of the signal the effect of the noise will be reduced.

You need to know the ADC reading when there is no current rZero (which should be around 511 but could be off a bit due to offset errors) - you could measure this with nothing connected to calibrate the sensor, or take a long term average even with the AC signal present.

As the henrysbench tutorial points out it is important that the Arduino samples the signal at a high enough frequency (say 1000Hz - hence 100 samples for your 100mS sample duration)- the count of the number of times that the while loop executes sampleCount will confirm if this still the case even with the extra computation time of this code.

Also if you increase the sample time please be careful that the unsigned long rSquaredSum can't overflow, but I would avoid use of doubles within the while loop as they will definitely slow it down a LOT.

void ac_read() {
  int rVal = 0;
  int sampleDuration = 100;       // 100ms
  int sampleCount = 0;
  unsigned long rSquaredSum = 0;
  int rZero = 511;                // For illustrative purposes only - should be measured to calibrate sensor.

  uint32_t startTime = millis();  // take samples for 100ms
  while((millis()-startTime) < sampleDuration)
  {
    rVal = analogRead(A0) - rZero;
    rSquaredSum += rVal * rVal;
    sampleCount++;
  }

  double voltRMS = 5.0 * sqrt(rSquaredSum / sampleCount) / 1024.0;

  // x 1000 to convert volts to millivolts
  // divide by the number of millivolts per amp to determine amps measured
  // the 20A module 100 mv/A (so in this case ampsRMS = 10 * voltRMS
  double ampsRMS = voltRMS * 10.0;
  Serial.println(ampsRMS);
}


char to String conversion in Arduino program I have started learning about Arduino and am well versed in Java and Python. In an Arduino program, I need a character input via Serial to be stored in a String variable. From my previous programming experience, I knew that a code like the one below would give an error as char can't be converted into String like this.

void loop() {
  if(Serial.available()) {
     String s=(char)Serial.read();
  }
}

As expected, the above code gives an error on compiling. But when I first defined s and then assigned its value in a separate step in void loop(), I got no error.

void loop() {
  if(Serial.available()) {
     String s;
     s=(char)Serial.read();
  }
}

The above code yields no error despite the fact that it is almost similar to the first code. What I suspect is that it has something to do with String being a class. Can one tell what is going on?

this isn't an arduino specific error what you're trying to do is declare and initialize the variable in one statement which is causing the problem. As you've figured it out already. Declaring the variable first

String s;

and initializing it another statement does the job for you

s=blabla

Hope this helps. PS, try posting the error that you get during build process next time :)

EDIT:
 I think this needs more explanation. Basically why you cant declare and initialize at the same time in this case is because Serial.read is a synchronous request. Declaring an object requires acquiring the space for it, running any constructors and whatsoever, and doing while Serial.read() is an IO blocking operation. You could declare and initialize a String class variable given it was a string constant but not with anything like get_input or Serial.read

EDIT 2:
Further here's what I've found for you.

http://www.cplusplus.com/reference/string/string/string/

Apparently the  String class has a copy constructor which means when declaring the variable you initialize at the same time it uses the copy constructor, and which requires ADDRESS to a valid string(know that you can use a constant because C++ deals with all strings as the address to their first char). In your case the constructor raised an error because you pointed it to an undefined(Serial.read() ).

String mystring=Serial.read(); //error, uses copy constructor

However this would work

String mystring="hey juliet!" ; //uses the copy contructor which takes address to a char

Doing the same thing in two different lines works for the same reasons, it uses a different constructor

String mystring; //uses empty string constructor - okay so far
mystring=Serial.read(); // uses the overloaded = operator  --okay


Can Arduino Uno's serial handle to foward push through 1-wire protocol? tl;dr on on digital ouput/input I would like to communicate with a 1-wire device, whose protocol requires precision to ~15 microseconds. My question is if Arduino Uno's serial communication can be as quick as to support to map the digital pin via serial->USB to my host computers app which should implement the 1-wire protocol?

long version
The mode in which I thought to use my Arduino was, to attach it to a host computer and run the logic of what should be done on the host computer, having the Arduino only receive the data (for the pins) and return the state of the pins.

The challenge which prompts me to this question is that the Serial communication is not really that quick, compared to the timing requirement of some protocols (e.g. 1 wire) I wish to implement.
For example: 1-wire-protocol's timing requirements (i.e. range of micorseconds) could easily be kept from code running on the Arduino Uno's Atmega328 directly, which at 16Mhz and assumed 2 cycles per command would allow somewhat a resolution of 2/16Mhz = 0,125 us.

If alternatively the data/instruction for the 1-wire protocol should be mapped via the serial interface to an application running on an PC attached to the Arduino I wonder if the time requirements of the 1-wire protocal can be reached?

It boils down to a question if the Serial communication can have a temporal granularity as small as the about 1 to 15 microseconds needed to implement the 1-wire protocol - not within arduino itself - but in the attached PC's application.

Ok, so there's two issues at stake here.

Can the Arduino generate a 1-wire protocol with enough accuracy?
Can you transfer the data fast enough through the UART to tell it to do that generation?

You can't just stream a 1-wire protocol through serial and expect it to work.  The low-level serial protocol would very much get in the way.  So you have to send instructions to the Arduino to say "Raise the IO pin" and "Lower the IO pin" and "Tell me when the IO pin changes level", and "Set the IO pin to input" etc.

Each of those actions would be a discrete item that you would have to send.  Given that you could have a single byte per action (send "I" for set to input, send "O" for set to output, send "L" for set to low, etc - Arduino sends "H" if the pin goes high, or "L" if it goes low, etc), what kind of response could you expect?

Well, at 8 bits + start + stop per byte (so 10 bits) at a good fast rate (say 1MBaud), you would expect one byte to take (1/(1000000/10) = 0.00001s (10µs) to transfer.  That's raw transfer speed.  On top of that you then have to add the processing of that incoming data - the Arduino adds it to a circular buffer to allow your sketch to read it, and that takes time, and your program then interpreting it, you could expect a latency of say 15µs.  At maximum stream rate (no breaks between characters being sent at all) you would have a basic granularity of 10µs (processing the last incoming character while the next one is being received).

That's not counting any other factors such as the UART buffers on your computer, latency before the character even gets to the USB port's endpoint, etc.

So all in all there might be a slim chance that you could do it, but it would be very slim and not easy to achieve a stable result.

Far better would be to implement the 1-Wire protocol on the Arduino and just send/receive the control information to tell it to go ahead and do the work and return the results.  After all, that's what the Arduino is designed for - low level interfacing like that.


If else statement not mutually exclusive? When I'm running some test on my encoder motors using the following provided code by Makeblock, it appears that the if..else.. statement is not mutually exclusive ie. I can control Encoder_1 and Encoder_2 at the same time. How come?

case ENCODER_BOARD:
      if(port == 0)
      {
        uint8_t slot = readBuffer(7);
        int16_t speed_value = readShort(8);
        speed_value = -speed_value;`

        if(slot == SLOT_1)
        {
          Encoder_1.setTarPWM(speed_value);
        }
        else if(slot == SLOT_2)
        {
          Encoder_2.setTarPWM(speed_value);
        }
        else if(slot == SLOT_3)
        {
          Encoder_3.setTarPWM(speed_value);
        }
        else if(slot == SLOT_4)
        {
          Encoder_4.setTarPWM(speed_value);
        }
      }

int16_t readShort(int16_t idx)
{
  valShort.byteVal[0] = readBuffer(idx);
  valShort.byteVal[1] = readBuffer(idx+1);
  return valShort.shortVal;
}

uint8_t readBuffer(int16_t index)
{
  if(BluetoothSource == DATA_SERIAL)
  {
    return buffer[index];
  }
  else if(BluetoothSource == DATA_SERIAL2)
  {
    return bufferBt1[index];
  }
  else if(BluetoothSource == DATA_SERIAL3)
  {
    return bufferBt2[index];
  }
}

All the code are taken from here and I am not the owner. I myself still studying how these whole code works. I am hoping someone out there who have experience with these kind of implementations be able to help me out.

if and else if clauses are mutually exclusive. If the if is true then the else if cannot run.

Therefore it must be the case that the code you posted is being executed twice (at least) - once for SLOT_1 and once for SLOT_2.  Just so fast that you think it's happening at the same time.