How to connect LED lights for 3D Printed Robot I'm new here and a newbie in electronics. I have a project to create a 3d printed robot with lights. I came across neopixels led's and the ardruino microcontrollers recently and find it to be a great possible sollution for what I need.

For my project, the 3d printed toy will have several parts that would need lights and I plan to use roughly over 40 LEDs connected to one source. I' m thinking of using the WS2812B LEDs.

I plan to use one neopixel ring for the robot's chest similar to Iron-Man's arch reactor.. While the head head will have 2x LEDs for the eyes, a smaller neopixel ring for the headpiece, another 2x LEDs for on the side of the robot mouth and 3x LEDs inside each vents on both sides of the robots head.

I need all the LEDs to turn on with a white light with a switch and turn red with another button. Although, I'd still be happy if they can only work with white.

For the power source, I was thinking about using a small powerbank or 2x 18650 batteries as the power source.

As mentioned, I'm very new to electronics and based on my research so far, i get confused really fast from all the jargons used and I'm not sure how to proceed.

Hopefully, i can get some answers here.

So.... My question is, is it possible to connect all the LEDs i plan to use on one microcontroller (ie: Ardruino Uno or Nano)

Most of the examples I can see on youtube are projects using LED strips. Are they diffrences in the way they are connected?

Another problem is coding for the ardruino..i'm totally clueless.

Any suggestions or help would be very much appreciated.

The key point for WS2812B LEDs is, that they can be daisy chained. This means, that everyone of them has one data input and 1 data output. If you connect the data output of one LED to the data input of the other, you created a short strip with 2 LEDs. Doing this multiple times creates a bigger LED strip. It's not relevant, if the LEDs are arranged into a physical strip, or arranged into complex forms. The LEDs are addressed by their position in the strip. The microcontroller sends a data stream to the first LED. It will read the first 3 bytes (1 byte per color) and forward the rest of the stream to it's data output, so to the next LED.

So you can wire all the LEDs on your robot in a way, that you basically only have 1 LED strip. In this case you only need 1 pin on your Arduino (plus Vcc and ground of course).

Or, if it's to cumbersome to wire all LEDs together, you can make multiple strips, divided by zones on your robot (like 1 strip for the face, 1 strip for the chest, ...). Every strip will need it's own pin on the Arduino.

Which way you go is your decision and also depends on how many pins you have free.

  My question is, is it possible to connect all the LEDs i plan to use on one microcontroller (ie: Ardruino Uno or Nano)

Yes, one microcontroller is plenty enough for this. As I wrote, for 1 strip you only need 1 data pin.

  Most of the examples I can see on youtube are projects using LED strips. Are they diffrences in the way they are connected?

This depends on what strips they have. If they use WS2812B strips, it is all the same. As said, the physical arrangement of the LEDs doesn't matter. But there are also other types of strips, for example the not-individually-addressable-single-color types, or the not-individually-addressable-RGB types (which often have one PWM line per color).

  Another problem is coding for the ardruino..i'm totally clueless.

Have a look at the Adafruit Neopixel library or the FastLED library (both on github). They are libraries, that will hide most of the complexity from you and will make it easy to control the LEDs. They both have examples, that you can use to get started. Adafruit also has good tutorials for this. You can google them.

  For the power source, I was thinking about using a small powerbank or 2x 18650 batteries as the power source.

I don't know, how much current these batteries can give you. I will leave that to you for your research. But be sure, that you can always provide the needed current. One WS2812B LED can draw up to 60mA (20mA per color), if you set them to full brightness white. So 40 WS2812B LEDs, can draw up to 2.4A. I guess, that your robot also has motors, which can also draw a big amount of current. So keep the total current draw in mind and don't ever try to draw this current through the Arduino (since this might fry the voltage regulator).


What are the AREF, IOREF, and the unlabeled pin next to IOREF on the Uno R3? There are some pins on the Arduino which I haven't been able to find out anything about:

IOREF
AREF
An unlabeled one next to IOREF

What are they?

AREF:

This is the voltage reference analog-to-digital converter (ADC). It can be used instead of the standard 5V reference for the top end of the analog spectrum – for example, if you wanted to use the ADC to monitor a signal that had a 0-1.5 volt range you could get the full scale of the ADC by connect AREF to a 1.5V signal. DO NOT CONNECT A SIGNAL OUTSIDE THE 0V TO 5V RANGE!

Note that in order for this to work, you must run analogReference(EXTERNAL); before using analogRead(). Also:

  After changing the analog reference, the first few readings from analogRead() may not be accurate.

Fore more information, see AnalogReference.

IOREF:

This is a voltage corresponding to the i/o of that board, for example an Uno would supply 5v to this pin, but a Due would supply 3.3v. Sending a signal to this pin does nothing.

Unlabeled pin:

This pin is unused, but is there to ensure compatibility with future products. It is not connected to anything on any R3 boards I have seen.


How to create jumping wire using fritzing tool I am tying to design my circuit diagram with the help of http://fritzing.org/home/ I designed like below circuit where wires are simply straight.

I want some kinda jumping wires with this tool. Does anyone know how to create these jumping wires ?

Draw the wires
press and hold control button (mouse pointer will appear with a curve symbol)
drag the wire using mouse


Implementing Quasi-Perpetual Battery on Arduino I am interested in seeing how much "uptime" I can achieve with my Arduino device/project. I am brand new to electronics/robotics, and so I wanted to bounce my idea off of this community first and see if I am overlooking anything obvious/major, or if my overall approach is incorrect.

The idea is simple:

Provide my Arduino device with 2+ "rechargeable power sources" (described next) and then provide a mechanism to route power to any viable (non-dead) power source at any time. While one power source is being used to power the Arduino device, the other "idling" power sources are recharging. The intention is to allow the device to keep switching between power sources endlessly, in perpetuity, achieving 100% uptime (perfect "high availability").

As for each "rechargeable power source" I am thinking an energyShield (rechargeable Li-polymer) backed by a solar panel.

I did some preliminary research and was told that if I were to wire these power sources in series with diodes, then the circuit would always by default draw power from the source with the highest voltage. As soon as another source has higher voltage, the circuit begins drawing power from that one, and the "old source" begins recharging.

I'm a noob but not a fool, and I know there is no such thing as perpetual energy (hence the title "quasi-perpetual"), and I'm sure factors like sunlight/weather conditions/etc. would affect the efficacy of the solar panels, etc. But I guess my first concern is: am I doin' it right? Are there any caveats/pitfalls or considerations I'm overlooking here?

Assuming I'm more or less correct in my approach, the other concern is how to actually implement power sources and diodes in a series, and how to actually rig that all up and connect it to the Arduino board. Again, I'm a total electronics newbie, so I'm just having a tough time visualizing the precise solution there.

And as for determining the actual number of power sources (energyShield + solar panel combo) my device would need, I was just planning on starting with 2, and running the device at max power and monitoring their recharge rates. The more sources I add, the longer the device will operate. Obviously, at some point I'll either reach a point where its uptime is sufficient for my needs, or I'll run out of money. :-)

You're overthinking it. Use one or more solar panels, a harvesting IC with sufficient storage, and the bare MCU and peripherals. Use enough panels and storage to run the MCU and peripherals 24/7, and to also charge the storage during the day.


Stuck in While loop! I am using 4 LDR To track the sun for solar panels. Not using servos, but linear actuators(a little irrelevant but just to give scope)

my code gets stuck in this while loop as soon as it enters it, even tho the conditions are changed to break the loop. I want to leave the motors running in one direction until the "dvert"=Vertical difference is less then "tol"=tolerance. there are 4 of these loops. there is an if condition before each. so no adjustment is made if its already in tolerance.

Segment of code

  if (avgtop > avgbot)
  {  Serial.println("enter avgtop > avgbot");
    Serial.println( "");

   while (abs(dvert) > tol)
     {
      Serial.println("Enter While loop vert up....");
      Serial.println("Moving Vertical Axis begin...Moving UP  ");

                   digitalWrite(vrelay1, HIGH);              // Setting frame down
                   digitalWrite(vrelay2, LOW);              // Setting frame down
      delay(200);
      int topl = analogRead(ldrtopl);
      int topr = analogRead(ldrtopr);
      int botl = analogRead(ldrbotl);
      int botr = analogRead(ldrbotr);
      int avgtop = (topl + topr) / 2; //average of top LDRs
      int avgbot = (botl + botr) / 2; //average of bottom LDRs
      int dvert = avgtop - avgbot; // check the diffirence of up and down

      Serial.print("NEW DVERT:"  );
      Serial.println(dvert);

  }  ```

You're masking your outer dvert variable (and potentially others that you want to keep) with local variables inside the loop:

  int dvert = avgtop - avgbot; // check the diffirence of up and down

If you're just assigning a new value to an existing variable you do not want to declare a new variable!

Instead it should be just:

  dvert = avgtop - avgbot; // check the diffirence of up and down

And the same for anything else inside the loop that you want to assign to a variable that you have created outside the loop.


What is the circular gold pad on arduino mega 2560 v2 and above? Could someone point me to the documentation that describes the gold dot and surrounding gold circle on the front of my arduino mega v2 board. It is right above the ICSP header and reset button, and directly underneath the letter 'U' in the silk screened word 'communication'
I've not been able to find any reference to it anywhere. Is is a jumper, a test pad, RF pad???

That is most likely a Fiducial Mark for the vision system of a pick-and-place assembly robot to key off of in order to more precisely place the components on their pads.

If you look carefully, you will see a second one located below the DC barrel jack.

Boards like this are manufactured in a gridded panel having a number of copies in each direction, and only cut apart after they are largely complete.  With such a large workpiece, any linearity error in the manufacturing could result in a high-density component being misplaced far enough to cause problems.  Having a pair of fiducials on each individual board in the panel can help calibrate out errors not only which might otherwise accumulate over the large dimensions of the entire panel, but also rotational skew of the panel in its holder.

You can see both on this picture of the Arduino Mega 2560 from the arduino.cc site


How to create TCP server on Arduino UNO WiFi? I'm currently trying to make my Arduino UNO WiFi work as a TCP host, so I can send him a TCP message and it sends a response.

I had no problem doing this on the Arduino Galileo Gen 2 using the EthernetServer, but since this one is using WiFi, EthernetServer isn't an option.

I can, however, run a web server, but that's not what I want.

So how do I make the Arduino receive, handle and respond to sent TCP/IP messages?

For Arduino UNO Wifi, you have to use library "UnoWiFi-Developer-Edition-Lib". You can directly download and install it through library manager or can get it offline through the following link "https://github.com/arduino-libraries/UnoWiFi-Developer-Edition-Lib".

Hope this can help you.


Arduino board with built-in Bluetooth I would like to find an Arduino with built-in Bluetooth.
I know about the HC-06, the shields and the other Bluetooth modules, but i would like to have built in Bluetooth for eliminating the risk for miscommunication on the serial port.

The official Arduino foundation did produce an board but it's retired now.

There is this board called Bluno
Its an Arduino UNO Based board with built in Bluetooth 4.0

Bluno - An Arduino Bluetooth 4.0 (BLE) Board


How to convert numbers from Serial port input to HEX String? I am trying to read digits (number from 0 to 255) from Serial port, convert them to HEX String and send them using SoftwareSerial as HEX.

For example:
when I send '60' trough the serial port, the SoftwareSerial will send '3C'

currently I am using the following code:

#include <SoftwareSerial.h>

SoftwareSerial mySerial(2, 4); // RX, TX

String inputString     = "";
boolean stringComplete = false;

int HexInt = 0;
String HexString = "00";

void setup() {
  Serial.begin(115200);
  mySerial.begin(38400);
  inputString.reserve(200);
  delay(500);
  Serial.println("");
  mySerial.println("");
}

void loop() {
  serialEvent();
  if(stringComplete) {
    HexInt = inputString.toInt();
    HexString = String(HexInt,HEX);
    if (HexInt<16) HexString = "0" + HexString ;
    HexString.toUpperCase();

    mySerial.println(HexString);

    Serial.println(inputString); //debug
    stringComplete = false;
    inputString = "";
  }

}

void serialEvent() {
  while (Serial.available()) {
    char inChar = (char)Serial.read();
    if (inChar == '\n') continue;
    if (inChar == '\r') {
      stringComplete = true;
      if (inputString == "") inputString = "NULL";
      inputString.toUpperCase();
      continue;
    }
    inputString += inChar;
  }
}

My question is:
Is there a more elegant / effective way to perform the same outcome?

You have the number. It's made up of two nibbles, each representing 4 bits (1 hex character).

If you want to do a manual conversion take the first nibble (AND with 240) add it's value to "0" then do the same for the lower nibble (AND with 15).

OR

What I would do is use:

char HexString[3];
sprintf(HexString,"%02X",HexInt);

since you're not dealing with floats, you're good to go.

OR

edit: I recalled a printf function that we put together once before, I don't know if it would work with SoftwareSerial, so you might have to play around with it a bit, but as a 3rd option, you could try the following. I don't have access to an Arduino or compiler at the moment, otherwise I'd have a play with this right now.

Before your setup:

// Function that printf and related will use to print
int serial_putchar(char c, FILE* f) {
    if (c == '\n') serial_putchar('\r', f);
    return Serial.write(c) == 1? 0 : 1;
}

FILE serial_stdout;

In your setup, add:

// Set up stdout
fdev_setup_stream(&serial_stdout, serial_putchar, NULL, _FDEV_SETUP_WRITE);
stdout = &serial_stdout;

in your loop, change your assignment to:

HexString = printf("%02X",HexInt);

from: https://arduino.stackexchange.com/a/480/304


Maintaining pull down on a relay with a shift register I currently have an Arduino Mega project that uses a relay to switch some high voltage loads. Currently, I use a scheduler library so that every 250ms I check if certain conditions are met and if so I turn off or on the relay. The relay is active when pulled down.

I'm trying to figure out how to transition this project to using a shift register. If the pin needs to be pulled low to be turned on and I want to keep it on, how do I supply a steady "low" signal using a shift register if the register is clocked to only latch every 8 clock cycles (not to mention I only run this code every 250ms). Even if every bit that gets sent by the shift register is low, do I need to no longer use the scheduling library so that every time through the Arduino loop I am sending the low signal so that the low signal can remain constant? With the standard Arduino pin once I set it to low it stays low until I switch it to high. But with a shift register can I keep it low "until I switch it high?"

You have misunderstood how shift registers work - and one of the main reasons they exist in the first place.

Shift register ICs have a common 'latch' pin which latches the data present at the input of the cell into the cell, thus updating the output. Some ICs also offer an "output enable", which switches the outputs to a high-impedance state irrespective of the values in the cells - this might not be useful in your case, but the feature exists.

With a serial-to-parallel shift register you can shift in as many bits as you want, at whatever rate you choose, and the outputs will never change until you trigger a rising edge on the LATCH pin.

How a (latching) Shift Register works:

You have eight spaces within the register:

             ___    ___    ___    ___    ___    ___    ___    ___
[DATA_IN]-->|___|--|___|--|___|--|___|--|___|--|___|--|___|--|___|-->[DATA_OUT]
            BIT0                                              BIT7

The 'spaces' are chained together; at one end of the chain is the DATA_IN pin and at the other end is the DATA_OUT pin.

Every time there is a rising edge on the CLOCK pin, data is shifted down the chain from DATA_IN to DATA_OUT, one space at a time. For example, if the state of the 'spaces' is as the left hand column, then upon the rising edge of the CLOCK pin the spaces will change to the values in the right hand column:

 DATA_IN PIN = 1  ->  C  -> ?
BIT0 'SPACE' = 0  ->  L  -> 1
BIT1 'SPACE' = 1  ->  O  -> 0
BIT2 'SPACE' = 1  ->  C  -> 1
BIT3 'SPACE' = 0  ->  K  -> 1
BIT4 'SPACE' = 0  ->  E  -> 0
BIT5 'SPACE' = 1  ->  D  -> 0
BIT6 'SPACE' = 1  ->  G  -> 1
BIT7 'SPACE' = 0  ->  E  -> 1

You will see that BIT(n) changes to the value of BIT(n-1), with BIT0 changing to the value of DATA_IN. The DATA_OUT pin is used to daisy-chain multiple shift registers together. The important thing to note here is that the outputs do not change without a rising edge on the LATCH pin. You can pulse CLOCK as many times as you want, with whatever values on DATA_IN, and the outputs will not change. Ever.

When you finally trigger the LATCH pin, the value in each 'space' is latched into a second row of 'spaces' - these represent the outputs. On a latch trigger, the outputs therefore change to the values of the last eight bits that were shifted into the DATA_IN pin. For example:

OUTPUT = 11001010
                   SHIFT IN "01101111" (starting with RHS first)
                               TRIGGER RISING EDGE ON 'LATCH' PIN
OUTPUT = 01101111
                   SHIFT IN "11110000110011001100"
                               TRIGGER RISING EDGE ON 'LATCH' PIN
OUTPUT = 11110000   i.e. the LAST EIGHT BITS that were shifted in
                   SHIFT IN "10"
                               TRIGGER RISING EDGE ON 'LATCH' PIN
OUTPUT = 10111100   again the LAST EIGHT BITS that were shifted in

It is generally never the case with a serial-in-parallel-out register that you would ever shift in less that eight bits at a time, so the last example is only there to illustrate the functioning of the IC.


74HC595 not working properly I've used the following code to light 8 yellow leds sequentially but it only runs as it's supposed to be on Proteus. However in my breadboard the 8 leds keeps blinking all together, the resistors used are 220 ohms. Also when i'm trying to change the value of the variable "leds" to be for example 0x0F, it doesn't light, I've read in the Arduino shiftout tutorial that 0.1F capacitor on the latch pin will even the flickers so now I'm really confused.

int latchPin = 8;
int clockPin = 12;
int dataPin = 11;

byte leds = 0;

void setup()
{
  pinMode(latchPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
}

void loop()
{
  leds = 0;
  updateShiftRegister();
  delay(500);
  for (int i = 0; i < 8; i++)
  {
    bitSet(leds, i);
    updateShiftRegister();
    delay(100);
  }
}

void updateShiftRegister()
{
   digitalWrite(latchPin, LOW);
   shiftOut(dataPin, clockPin, LSBFIRST, leds);
   digitalWrite(latchPin, HIGH);

}

SOLVED!
 i've tried many solutions to make it work but it just didn't and here are the solutions i tried
a) to use  0.1µf or 10µf between VCC and ground pin of the 74hc595 .
b) to set the clockPin and dataPin zero before sending data .
c) replacing the resistors from 220 ohm to 470 .

however,  i connected pin13 of the 74HC595 to an arduino pin and drive it to zero so the 8 output are ready to go then digitalWrite(out_enable_Pin, HIGH) ,send data as shown in the following code then digitalWrite(out_enable_Pin, LOW) again .

int latchPin = 8;
int clockPin = 12;
int dataPin = 11;
int out_enable_Pin=13;
int resetPin=5;
char leds = 0;

void setup()
{
  pinMode(latchPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(out_enable_Pin, OUTPUT);
  pinMode(resetPin, OUTPUT);
}

void loop()
{
  digitalWrite(out_enable_Pin, LOW);
  digitalWrite(resetPin, HIGH);

  for (int i = 0; i <255; i++)
  {
    leds=i;
    updateShiftRegister();
    delay(1000);
  }
}

void updateShiftRegister()
{
    digitalWrite(out_enable_Pin, HIGH);
   digitalWrite(latchPin, LOW);
   shiftOut(dataPin, clockPin, MSBFIRST, leds);
   digitalWrite(out_enable_Pin, LOW);
   digitalWrite(latchPin, HIGH);
}


UART between arduino UNO and pc via USB not in sync I connected my arduino uno to my system and then using serial tried writing and reading data but there is a problem which I found when I tried giving arduino crafted messages.
My arduino code is pretty simple.
void setup() {
  Serial.begin(115200);

}

void loop() {
  if (Serial.available() > 0) {
    String data = Serial.readStringUntil('\n');
    Serial.print(" You sent me: ");
    Serial.println(data);
  }
}

and my python code on my system
#!/usr/bin/env python3
import serial
import time

if __name__ == '__main__':
    ser = serial.Serial('/dev/ttyACM0', 115200, timeout=1)
    ser.flush()

    while True:
        string=input("Enter the string: ")
        ser.write(str.encode(string))
        line = ser.readline().decode('utf-8').rstrip()
        print(line)
        time.sleep(0.01)

Now this gives me ability to write instructions to my arduino but following sequences of communication occur
└──╼ $python3 serial_communication.py
Enter the string: a

Enter the string: v

Enter the string: v
 You sent me: v
Enter the string: s
 You sent me: v
Enter the string: d

Enter the string: r
 You sent me: sd
Enter the string: d
 You sent me: r
Enter the string: s

Enter the string: e
 You sent me: ds
Enter the string: r
 You sent me: e
Enter the string:

Looking at them I understand that this might be a problem with my code or I am using the wrong protocol.

There's a number of things going on here that combined give you the results you're seeing.
First off there's the delay at the start:
Enter the string: a

Enter the string: v

Enter the string: v
 You sent me: v
Enter the string: s
 You sent me: v

This is because when you first open the serial port the Arduino resets and enters the bootloader. Thus the first few things that get sent are discarded, and nothing is sent back from the Arduino - your sketch just isn't running at that point.
Next is the format of what you're sending compared to how you're receiving it.
You input a string and then send that string verbatim.  But on the Arduino you are reading all data up until a terminating newline character, which you are not sending.
But the reading function also has a timeout in it so it will return whatever it has managed to read in that time even if the terminator hasn't arrived. That timeout is 1 second by default.
So everything that gets sent within a 1 second window gets grouped together, which is what you see here:
Enter the string: d
 You sent me: r
Enter the string: s

Enter the string: e
 You sent me: ds

The "out of sync" appearance is because of that 1 second timeout - you are seeing what was sent a second ago.
The fix is simple enough: make sure that you send the terminating newline character from Python:
ser.write(str.encode(string + "\n"))

And wait a few seconds after starting your program and opening the serial port before asking for anything to be sent. Maybe add a time.sleep(2) after opening the port to enforce that delay.


what units do Mouse.move() use? When I use Mouse.move() method (https://www.arduino.cc/en/Reference/MouseMove), what are units of xVal and yPos parameters?

They're raw HID counts and as such don't have a unit. It is up to the OS to translate them from logical amounts to physical values.


Writing serial data, just once after read I have developed a program and the idea is that when it receives serial data (any single character) it returns a single random number.

I have it working but it returns 3 x random numbers one after another for each read that it does and I can't figure out why.

int led = 13;
char incomingByte = 10;
long randNumber;
// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);
 Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop() {

//  delay(1000);               // wait for a second

   if (Serial.available() > 0) {
                // read the incoming byte:
                incomingByte = Serial.read();
                // say what you got:
              //  Serial.print("I received: ");

                randNumber = random(1, 2000);
                Serial.println('PL' + randNumber);
                  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

}

}

When you enter a single character into the Serial Monitor and press Enter, three bytes are sent: the character, a carriage return, and a linefeed. Serial.read() only reads a single byte, so data is available three times.

Either loop reading until no more bytes are available, check for and discard any CRs and LFs, or use a serial terminal that doesn't require pressing Enter to send data.


Issue with Arduino Timing I am working with an Arduino on a project for which timing is very important. I use TimerOne to trigger timer interrupts and use micros() for delays (delayMicroseconds() was causing problems worse than the one explained below). The program is sending a manual PWM signal to an LED and it is very important that the signal is sent with an error that is less than 8 microseconds (ideally, the signal is sent at the same time in each period). My test code is shown below:

#include <TimerOne.h>
#include <SPI.h>

const int LED_PIN = 3;
const int CHIP_SELECT = 12;

const int PERIOD = 4000;
const double DUTY_CYCLE = .5;
const int HIGH_TIME = PERIOD * DUTY_CYCLE;
const int LOW_TIME = PERIOD - HIGH_TIME;
const int INITIAL_SIGNAL_DELAY = LOW_TIME / 2;
const int HIGH_TIME_TOTAL_DELAY = INITIAL_SIGNAL_DELAY + HIGH_TIME;

const int RESISTOR_VALUE = 255;

boolean triggered = false;
boolean data = false;

unsigned long triggeredTime;
unsigned long s;
unsigned long e;

boolean found;
int i = 0;

void setup()
{
  s = micros();

  Timer1.initialize(PERIOD);
  Timer1.attachInterrupt(trigger);

  pinMode(LED_PIN, 3);
  pinMode(CHIP_SELECT, OUTPUT);

  SPI.begin();

  digitalWrite(CHIP_SELECT, LOW);
  SPI.transfer(B00010001);
  SPI.transfer(RESISTOR_VALUE);
  digitalWrite(CHIP_SELECT, HIGH);

  e = micros();

  Serial.begin(115200);
  Serial.print("s: ");
  Serial.println(s);
  Serial.print("e: ");
  Serial.println(e);
}

void loop()
{
  if(triggered)
  {
    while(micros() - triggeredTime < INITIAL_SIGNAL_DELAY)
    { }
    s = micros();
    digitalWrite(LED_PIN, data);
    while(micros() - triggeredTime < HIGH_TIME_TOTAL_DELAY)
    { }
    digitalWrite(LED_PIN, LOW);

    data = !data;
    triggered = false;

    e = micros();
    //micros();

    if(s % 100 > 28 || s % 100 < 12)
    {
     found = true;
    }

    if(!found)
    {
      Serial.print("s: ");
      Serial.println(s);
    }
    else
    {
      Serial.print("ERROR: ");
      Serial.println(s);
    }
    //Serial.print("e: ");
    //Serial.println(e);
  }
}

void trigger()
{
  triggeredTime = micros();
  triggered = true;
}

(it should be noted that the first signal sent is always xx20, usually 5020).

So, with this code, I eventually get an error. I am not sure why, but this error occurs at the same point every single time:

.
.
.
s: 1141020
s: 1145020
s: 1149020
ERROR: 1153032
ERROR: 1157020
ERROR: 1161020
.
.
.

Now, the really weird part is if I remove the comments before micros() (the micros() right after e = micros()), there is no error (or at least there is not an error within the first 30 seconds). I was wondering if anybody could provide an explanation for why this happens. I have dedicated many hours trying to get the timing working properly and everything was working well until I encountered this error. Any help would be very much appreciated. Thank you!

the code flow doesn't make a lot of sense to me. seems to me that you can simplified quite a bit.

  if(s % 100 > 28 || s % 100 < 12)

I would use a few brackets to make it clear to the compiler what you want it to do.


ESP 8266 web server using arduino I have built a system using arduino and Ethernet shield. It gets rgb values through URL and changes an rgb led's value. Today I bought an ESP 8266 12E. I want to change to wifi but I cannot find an arduino library that uses spi to connect the arduino to the ESP. I do not want to use only the ESP. Do you know any libraries to do the job or any tutorials.

The ESP communicates using the UART, not SPI. It uses modem-like AT commands. Unless you write your own ESP firmware, in which case how it communicates is up to you - and so is the accompanying Arduino library.


ESP8266 check if TCP client disconnected...informally Hi with ESP8266WiFi library, I usually check for connection of a TCP client with client.connected().

But it seems to still return true if my TCP client in an unexpected way (like disconnect to WiFi/ Power loss/...). Which leaves my program stuck in a infinite loop.

Is there a more reliable to check for connection status?

You have the inherent problem that a TCP connection is terminated by an explicit "FIN" message from the terminating party, followed by a FIN-ACK and ACK.

Refer to here.

If your client (or server) just powers off without closing the connection properly, that's it. The connection hangs up and no data will be transfered if it is not explicitly handled.

If you must know whether the client is still there, you must use a heartbeat meachanism. That is, after some period time without a response has passed, query the connection party with a "heartbeat" message and see if it responds after a given maximum time. The other way around would be to make the client send a periodic "Keep Alive" message which holds up the connection as long as it is sent repeadetly.

Refer to here and here.


Which battery should I use to power arduino+motor shield + two 200 RPM (3.6V/1.5A)motors I am using two motors ( from old two drill machines - same kind, these are 3.6v motors ), connected to arduino + arduino motor shield seeed studio v2.

When I measured the both motors (indvidually) using a multimeter in series with your motor and an about 3.6V power supply, I found that the both are varying from 1.46A-1.47A, (I supposed it as 1.5A)

I tried to use 18v/1.2a battery that was laying at home (from old machine ) what I have noticed is that motors are running for 3-5 seconds than stop, one of the red lights start blinking in the motor shield, then it stops for 3-5 seconds then it works again and loop.

Notes:
- The motors are working when I connect them directly to 4.5 or 6v battery. But when I try to assemle everything , it doesn't work (I am adding this just to say that motors are in good health).

I tried 14v battery I noticed the same thing.
The drill machine is small one (as big as a human hand). Motors from electric drills are designed as high-speed high-torque motors, but I don't think it's too high in my case to be a huge problem. It's 200 RPM DC motor
I spent a week looking for answer before posting this thread, I tried every single solution I came across on the web.

What are things that I should consider here, any thoughts.

What did I miss? And what kind of battery should I use ??

I have run into similar weirdness myself, and the solution that worked for me is to have separate batteries for the Arduino and the motors. This is more important if your motors run at a different voltage (e.g. 6v or 12v motors), but is useful in any case. This means that, when the motors draw to much from the batteries, the motors will slow down. If the same battery is used for the motors as for the Arduino, then the voltage drop from the motors will also apply to the Arduino; if the voltage drops in the Arduino, it will turn off (and turn back on when the voltage is restored). This is likely what you are seeing.


How to calculate voltage? I want to check each cell voltage using arduino.

and how to calculate dc current using CT Sensor using Arduino?

You have two problems here:

How to take 24 readings on an Arduino with only 6 analog inputs.
How to get the voltage in the range of 0 to 5 volts.

To take 24 readings you can use an analog multiplexer or two. For example the 74HC4051 (8 channels) or the 74HC4067 (16 channels). With both of those you could handle 24 channels.

To read the voltages you could successively read each cell, relative to ground (eg. the first one should be 2 V, the second should be 4 V, and so on up to 48 V).

Cells 1 and 2 are fine, they are lower than 5 V. Cells 3 to 24 are not. You need to set up a voltage divider to divide down the voltage into the range 0 to 5.

The formula for a voltage divider is:

Vout = Vin * R2/(R1+R2)

Let's make R1 to be 10k ohms, and solve for R2 (given that we want Vout to be 5).

R2 = Vout * R1/(Vin - Vout)
R2 = 5 * 10000 / (Vin - 5)

Plugging that into a spreadsheet we get:

Vin    R
6  50000
8  16667
10 10000
12  7143
14  5556
16  4545
18  3846
20  3333
22  2941
24  2632
26  2381
28  2174
30  2000
32  1852
34  1724
36  1613
38  1515
40  1429
42  1351
44  1282
46  1220
48  1163

These aren't particularly easy resistor values to work with, so we'll use standard values and calculate what the output voltage should be (with the spreadsheet):

Vin   R   volts   Scale
2
4
6   47000 4.9474  1.2128    <--- R2 is 47 k
8   16000 4.9231  1.6250    <--- R4 is 16 k
10  10000 5.0000  2.0000
12   6800 4.8571  2.4706
14   5100 4.7285  2.9608
16   4300 4.8112  3.3256
18   3600 4.7647  3.7778
20   3300 4.9624  4.0303
22   2700 4.6772  4.7037
24   2400 4.6452  5.1667
26   2200 4.6885  5.5455
28   2000 4.6667  6.0000
30   2000 5.0000  6.0000
32   1800 4.8814  6.5556
34   1600 4.6897  7.2500
36   1600 4.9655  7.2500
38   1500 4.9565  7.6667
40   1300 4.6018  8.6923
42   1300 4.8319  8.6923
44   1200 4.7143  9.3333
46   1200 4.9286  9.3333
48   1100 4.7568 10.0909

The "Scale" column will be explained in a moment.

Now we are ready to make up a circuit along these lines:

I haven't shown all the battery cells here - I don't have that much energy! But the principle is the same.

The 2V and 4V inputs we can read directly. From 6V upwards we need to apply the scaling factor from the voltage divider network.

That is shown in the "Scale" column above.

The formula for the voltage on the pin is:

float voltage = ((float) rawADC  + 0.5 ) / 1024.0 * Vref;

So assuming Vref is 5V, and you have a reading of 512, then you apply it like this:

 ( 512  + 0.5 ) / 1024.0 * 5 = 2.502 volts

Now you multiply by the scale factor above, so if this was the 34 V input, the scale factor would be 7.25, and the voltage from the battery would be:

2.502 * 7.25 = 18.14  volts

The stage is now set to work out each voltage:

Use the multiplexer "select" pins to choose one of the battery inputs
Take an analog reading
Scale it by the appropriate amount from the table
Work out what the charge in the cell is (by comparing it to the previous one)

For example, if the first cell read 1.9V and the second cell read 3.85V then you know that the difference is 3.85 - 1.9 which is 1.95 volts.


What's the difference/relationship between Arduino and AVR? I'd always thought Arduino was a microcontroller platform but the actual microcontroller is an AVR chip made by Atmel, or something like that made by someone else, based on a RISC ISA, and Arduino is usually used to refer to the whole circuit board powered by this AVR chip. Is my understanding correct?

What's the difference/relationship between Arduino and AVR?

Arduino is a prototiping board, and also the term "Arduino" is used to referr to the IDE and library on the PC side, and all its ecosystem.
AVR is the architecture (developed by atmel) of the microcontroller chip used in all official 8bit board, and almost all clone.
Arduino UNO and 2009, the most used, use the AtMega328P chip.

Many times, Arduino is used to quick test some idea, sensor, and circuitry, then a stand-alone board is builded around the AtMega chip, as it cost 1/10 of the Arduino board, soldered ciurcuit on a stripboard or on a custom PCB are more reitable, and can be optimized on some aspect, like power utlization, space occupied, high current/voltage, and so on.

Newest and advanced arduino board use different chip with very different architecture; the arduino yun use a SAM plus a classic AVR, the due use an ARM (same architecture used by many smartphone), the galileo use an x86 (like a classic pre-multicore cpu)


Stop Arduino from powering LED strip when connected to USB I have a WS2812B LED strip that is controlled by an Arduino. Normally, both the Arduino and LED strip are powered by the same 5V power supply. The 5V and GND pins of the Arduino and LED strip are connected together. If I want to reprogram the Arduino, I have to disconnect the LED strip or else it might want to try and draw power from my computer's USB.

I have a bunch of (assorted) transistors, (schottky, zener) diodes and resistors. Is there something I can build that will allow the power supply to power both the Arduino and LED strip, while the Arduino's USB can only power the Arduino itself?

I've thought about using a diode between the 5V of the Arduino and 5V of the power supply and using a resistor to pull the 5V terminal of the power supply pin low (when the power supply is not connected) but I'm not sure how stable that will be: once the diode starts conducting the resistor will have no chance to pull the pin low again and I'm not sure if the Arduino will like the voltage drop across the diode.

Obviously the external power would be disconnected before plugging the Arduino into USB. Since the LED strip runs on 5V I can't use the VIN pin.

I'd try powering the led strip for the power-supply directly, and the arduino board via a (schottky) diode.

That way the led strip will have no power when only usb is plugged in.

The Arduino won't mind that it receive a bit less that 5v because of the voltage drop of the diode.

The only thing to look out for it sending a 5v signal to a WS2812B chip that has no power. According to the datasheet this is not allowed.

So you either need to buffer the output of the arduino going to the input of the WS2812B (e.g. using some transistors, or a simple pull-up with diode). Or, since you are not hot-plugging the usb, have the 5v from the power supply go (via a resistor) to an input on the arduino, so you can detect this in your setup routine, and have it block the rest of the code, or something.


Stuck Arduino Relay? I am looking for a relay that stays on (NC=Normally Closed), and when I send a new signal switches to off (NO=Normally Open).

So the relay doesn't consume any power while being in a specific position.

Do you guys know any type?

Thanks :)


Message Interpreter and Handler - How to store a function name in a struct? For a project, I need to store an array of structures in PROGMEM. Array MessageTable[] will be composed of about ten struct InMessage elements. InMessage looks sort of like this:

struct AvcInMessage {
  MessageHandler  msgHandler;
  byte            dataSize;
  byte            data[8];
  char            description[20];
};

MessageHandler is not a data type... yet. I'm not really sure what data type to use. I want to be able to pick a message from the table and then call MessageTable[x].msgHandler() if that makes sense. I'm almost positive that this involves a pointer. Does someone here have an idea about what I'm looking for?

typedef void (*MessageHandler)(void);   // def messagehandler as pointer to func

struct AvcInMessage {
  MessageHandler  msgHandler;
  byte            dataSize;
  byte            data[8];
  char            description[20];
} InMessage[] = {
   {
      function1, <datasize>, {<byte0>, <byte1>, ..., }, "DescriptionHere"
   },
   // etc, for however many elements InMessage[] has.
};

The typedef defines a "pointer to function of void returning void" - fix up the argument count and types, and the return type to your needs. We're assuming each element's function has the same kind of arglist and return type. (Update: Sorry for the bug in my first iteration).

The next statement both defines the array of struct and initializes N of them. Provide an element count in the [] if you don't have a full set of initializers at compile time.


How will Arduino communicate wirelessly through XBee? I am using one XBee S2 configured as coordinator API attached to my laptop and one XBee S2 attached to an Arduino Uno that is configured as a router AT. I want to generate an alarm on LabVIEW as I have used VISA for serial communication.

#include <SoftwareSerial.h>

int buttonState1 = 0;
SoftwareSerial XBee(2,3); // RX, TX
int pin=13;
void setup() {
    XBee.begin(9600);
    Serial.begin(9600);
    pinMode(2,INPUT);

}

void loop() {
    if (Serial.available())
       buttonState1 = digitalRead(2);

    if (buttonState1 == HIGH) {
       // turn LED on:
       Serial.println(1);

    }
   /*else
    {
        Serial.println(2);

    }*/
    else {
       // turn LED off:
       Serial.println(0);
    }

    delay(100);
}

but I am getting no response at all.

What could be the root cause for this and how do I diagnose that?

Pin 2 & 3 are hardware serial pins.
You can't/shouldn't attach softwareserial pins to them.

In short, your SoftwareSerial XBee is never used and uses the same pins of the hardware serial.

What are you actually trying to achieve? I have a hard time understanding it.
Though. You should first check if your connection is working.

What devices do you have connected to the arduino?

Is it [Arduino] <-> [XBEE] <-> [PC]?

Test your connection using the code below

int incomingByte = 0;   // for incoming serial data

void setup() {
        Serial.begin(9600);     // opens serial port, sets data rate to 9600 bps
}

void loop() {

        // send data only when you receive data:
        if (Serial.available() > 0) {
                // read the incoming byte:
                incomingByte = Serial.read();

                // say what you got:
                Serial.print("I received: ");
                Serial.println(incomingByte, DEC);
        }
}

Source


A question about resistance measurement with arduino Lately I was asking myself about the possibility of measuring a potentiometer resistance with Arduino.

My questions are:

Is it possible?
If it's possible, what kind of restriction does the Arduino have with the resistance value measured?

If you know Ohm's Law (which you should) and you realise that the ADC measures voltage, you should be able to work it out from there. But I will go into minute detail for you to ensure you understand.

Ohm's Law defines the relationship between Voltage (V), Current (I) and Resistance (R).

R = V/I

To find one unknown value (in your case R) you need to know the other two values.  That is, the current flowing through the resistor, and the voltage dropped across the resistor.

We have no way of directly measuring current, but we can measure voltage using the ADC. So if we can somehow measure a voltage and use that to calculate the current then we have two of the three values and we can calculate the third. However, calculating the current requires that we know the resistance - and that is what we are wanting to find out.

So we need to then provide a known resistance that we can measure the voltage across, and thus find the current flowing through it. First a couple of reminders of basics:

Current flows the same through all resistances connected in series
The sum of all voltages dropped across resistors in series equals the total voltage across all the resistors.

So if we put two resistors in series and apply an fixed voltage across it (5V in our case) a single current will flow through them both. With that two voltages will be dropped across the resistors - and those two voltages will add up to 5V.

If we have one known resistor and one unknown resistor and we know the voltage dropped across both resistors then we can calculate the current that is flowing through the known resistor. And that current is the same current that is flowing through the unknown resistor. And since we know the voltage drop across that resistor we can then calculate its resistance using that voltage and the current we have just calculated.

Here's the circuit I just described:

Vin us 5V. Let's have R1 as, say, 10KΩ (a common enough value). R2 we don't know.

Using the ADC of the Arduino we measure a value of 681. First we convert that into a voltage:

Vout = 681 / 1024.0 * 5.0
     = 3.325V

So we know that R2 has 3.325V dropped across it, and since all the voltages must add up to 5V we know that R1 has (5 - 3.325) 1.675V dropped across it.

So the current (I=V/R) through R1 must be (1.675 / 10,000) 167.5µA (0.0001675A).

Now we can calculate the resistance of R2 since R=V/I and V is 3.325 and I is 0.0001675, so R must be 19850Ω - or pretty much 20KΩ.

That's the long-hand version from a current-based perspective. However there is a short-cut.

Since the output voltage is a simple ratio of the input voltage defined by the ratio between the resistors we can use that to create a much simpler formula.

From the example above the output voltage is two thirds the input voltage - and R2 is two thirds the total resistance (R1+R2). The two match perfectly.  So we can use a simple ratio calculation to give us the resistor.

For instance, the ratio formula:

Vout = R2 / (R1 + R2) * Vin

(that's R2 as a proportion of the total resistance multiplied by the input voltage)

When rearranged to get R2 gives us:

R2 = R1 * (1 / ((Vin / Vout) - 1))

So taking the voltage we measured above (3.325) and the known resistor (10,000Ω) and the input voltage (5V) and substituting those values into the formula, we get:

R2 = 10,000 * (1 / ((5 / 3.325) - 1))
   = 10,000 * (1 / (1.504) - 1)
   = 10,000 * (1 / 0.504)
   = 10,000 * 1.984
   = 19840

Or pretty much 20KΩ. (Note: the discrepancy in the results is purely due to rounding errors. Use higher precision values and you get better results).

You have to have a rough idea of the kind of order of magnitude of resistor you are trying to find, though, in order to select an R1 of a comparable value so that the voltage Vout is large enough to measure accurately.

Also you need to be aware that the input to the ADC has quite a (relatively) low impedance (can be very crudely thought of as a resistor between the input and ground) which is measured in the low mega-ohm range. This can have an impact on the values you read with the ADC if your resistors are too high, since this impedance will be in parallel to the resistor R2, so you'd actually be measuring the resistance of both R2 and the ADC's input in parallel. To measure very high resistances you should first buffer the ADC through a voltage follower with a very high (tens or hundreds of tera-ohms) impedance input.


ESP32-CAM not reading BME680 I am trying to read BME680 on ESP32-CAM with following code :

(Before trying BME680, I have suscessfully connected BME280 to ESP32-CAM over S/W SPI)

#include <Wire.h>
#include <SPI.h>
#include <Adafruit_Sensor.h>
#include "Adafruit_BME680.h"

#define SEALEVELPRESSURE_HPA (1013.25)

#define BME_SCK 12 //Connected SCL to IO12
#define BME_MISO 15 //Connected SDO to IO15
#define BME_MOSI 13 //Connected SDA to IO13
#define BME_CS 14 //Connected CS to IO14

//Adafruit_BME280 bme; // I2C
Adafruit_BME680 bme(BME_CS, BME_MOSI, BME_MISO, BME_SCK); // software SPI
//float temperature = 0;
//float humidity = 0;
//float pressure = 0;

void setup() {
  Serial.begin(115200);
  while (!Serial);
  Serial.println(F("BME680 test"));

  if (!bme.begin(0x76))
  {
    Serial.println("Could not find a valid BME680 sensor, check wiring!");
    while (1);
  }

  // Set up oversampling and filter initialization
  bme.setTemperatureOversampling(BME680_OS_8X);
  bme.setHumidityOversampling(BME680_OS_2X);
  bme.setPressureOversampling(BME680_OS_4X);
  bme.setIIRFilterSize(BME680_FILTER_SIZE_3);
  bme.setGasHeater(320, 150); // 320*C for 150 ms
}

void loop()
{
  if (! bme.performReading())
  {
    Serial.println("Failed to perform reading :(");
    return;
  }
  Serial.print("Temperature = ");
  Serial.print(bme.temperature);
  Serial.println(" *C");

  Serial.print("Pressure = ");
  Serial.print(bme.pressure / 100.0);
  Serial.println(" hPa");

  Serial.print("Humidity = ");
  Serial.print(bme.humidity);
  Serial.println(" %");

  Serial.print("Gas = ");
  Serial.print(bme.gas_resistance / 1000.0);
  Serial.println(" KOhms");

  Serial.print("Approx. Altitude = ");
  Serial.print(bme.readAltitude(SEALEVELPRESSURE_HPA));
  Serial.println(" m");

  Serial.println();
  delay(2000);
}

When I try to upload the code to ESP32-CAM while BME680 is connected I get following error

esptool.py v2.6
Serial port /dev/ttyUSB0
Connecting....
Chip is ESP32D0WDQ6 (revision 1)
Features: WiFi, BT, Dual Core, 240MHz, VRef calibration in efuse, Coding Scheme None
MAC: a4:cf:12:99:b5:70
Uploading stub...
Running stub...
Stub running...
Configuring flash size...
Warning: Could not auto-detect Flash size (FlashID=0xffffff, SizeID=0xff), defaulting to 4MB
Compressed 8192 bytes to 47...

A fatal error occurred: Timed out waiting for packet content
A fatal error occurred: Timed out waiting for packet content

Then I tried to disconnect BME680 and uploaded the code to ESP32-CAM which worked, then connected BME680 back to ESP32-CAM.

But now I see following error in Serial Monitor :

ets Jun  8 2016 00:22:57

rst:0x1 (POWERON_RESET),boot:0x33 (SPI_FAST_FLASH_BOOT)
flash read err, 1000
ets_main.c 371
ets Jn  8 2016 00:22:57

rst:0x10 (RTCWDT_RTC_RESET),boot:0x33 (SPI_FAST_FLASH_BOOT)
flash read err, 1000
ets_main.c 371
ets Jun  8 2016 00:22:57

rst:0x10 (RTCWDT_RTC_RESET),boot0x33 SPI_FAST_FLASH_BOT)
lash read err, 1000
et_main.c 371
ets Jun  8 2016 00:22:57

rst:0x10 (RTCWDT_RTC_RESET),boot:0x33 (SPI_FAST_FLASH_BOOT)
flash read err, 1000
ets_main.c 371
ets Jun  8 2016 00:22:57

rst:0x10 (RTCWDT_RTC_RESET),boot:0x33 (SPI_FAST_FLASH_BOOT)
flash read err, 1000
ets_main.c 371
ets Jun  8 2016 00:22:57

Any idea what is wrong here ?

Update :

I switched #define BME_SCK 12 to #define BME_SCK 16, now getting following message

ts Jun  8 2016 00:2:57

rst:0x1 (POWEON_REST),boot:0x13 (PI_FAT_FLASH_BOOT)
cnfigsi: 0, SPIWP:0xee
clk_dv:0x00,q_drv:0x0,d_drv0x00,cs0_drv:0x00,d_drv0x00,wp_drv:0x0
mod:DIO, clock div:
loa:0x3fff0018,len:4
load0x3fff001c,len:1216
ho 0 tail 12 room 4
lod:0x40078000,len:9720
h 0 tail 12 room 4
load0x40080400,len:6352
etry 0x400806b8
[D][esp32-hal-psram.c:47] psramInit(): PSRAM enabled

GPIO12 must not be pulled high during boot. It's possible there's a pull-up resistor on the BME680 breakout board you're using that's pulling SCK high and interfering with the boot process. I would avoid using GPIO12 here.

If you're out of pins on the ESP32 you can connect the BME680 via I2C rather than SPI. I2C only needs SDA and SCK (and power and ground, of course). The Adafruit library for the BME680 has an example of how to call the constructor for an I2C connection.


ESP8266 - AT Command for Network Requiring Username AND Password I have been using my ESP8266 module with my Arduino on my university's Wi-Fi network, which only requires a password to log on to.

The university will soon terminate that Wi-Fi network and replace it with one that requires a username and password to log on.

What would that AT command be to connect to such a network?

Edit: I have since found out that the university has changed the network so that a user can "connect" to the network and then enter their university id/password in a captive portal to gain internet access (and perhaps other features of the network). Also, I have since learned how to overwrite the firmware on my esp-01 so that I no longer need to use the AT commands -- in fact, I can program it in the Arduino IDE just as I would with another esp8266-based device, such as the NodeMCU.

We can't tell without more information but it sounds rather like you will need a [WiFi_SSID, WiFi_PASSWORD] pair for the ESP to connect to the WiFi, and a [Network_USERNAME, Network_USERPASSWORD] pair for their network to let you use the network (as if you were logging onto it by hand from a terminal).

If so, you'd provide the first pair as you do now, with the AT+CWJAP... command, to get your device connected to the WiFi. For the second pair, your Arduino will probably need to interact with a user logon screen to provide the second pair. You'll need to get those details from the school's IT department, and possibly mimic a terminal.

Update:
As above, you need to find out whether the network requires 2 sets of credentials - the SSID and WPA2 key and network username and password. If it requires the latter, then your ESP can get you onto the WiFi but your Arduino will then have to mimic a user sitting at a terminal - read the network ID and Password challenges and provide the appropriate responses. Without know that, you can't know how to write the login code, nor can we. It sounds as if there are people on site who have already done what you're trying to do. They and their experience can be far more helpful than we, who have no knowledge of the school network.


How to connect Arduino Pro Mini with PC? I'm about to buy Arduino Pro Mini (http://arduino.cc/en/Main/ArduinoBoardProMini).
As far as I can see it requires FTDI or similar circuit to program it.

Should FTDI be present for communication with PC after sketch is uploaded to chip or there is a way to connect Arduino Pro Mini DIRECTLY to USB cable and PC?

Is this also case with Arduino Pro Micro? (https://www.sparkfun.com/products/12640)

Thanks in advance
Petar

V-USB can be used to create a low-speed USB device in software, but you will need to program the chip before you can use it. It also has a number of caveats that must be adhered to regarding electrical and software specifications, so it not the best choice for an absolute beginner.

A USB-UART bridge (not necessarily a FTDI chip, although that is (was?) the most popular solution) will allow you to program and communicate with the chip over its serial port, but any AVR ISP programmer can also be used to program it without requiring a preexisting bootloader in place.


What happens if we connect GND and +5v? What will happen if I by mistakenly connect GND and +5v of an Arduino Nano? Is there any protection for it? Or will it get short and fry out something?

Depending on how you are powering your board different things will happen.

If you are powering through USB from a PC the PC should, according to the USB standard, detect an over-current situation and disconnect the power from the port. However some don't, in which case see point 2.
If you are powering through USB from a USB power supply (phone charger, etc) the charger's output voltage will drop to near zero and the current will hit maximum for the supply. This may or may not damage the supply, but either way it's not a nice thing to do.
If you are powering from a small external battery (say a 9V PP3 battery) things will start to get hot. The voltage regulator will most likely overheat, the battery may overheat, but not much damage should occur - a small PP3 battery can't provide much current.
If you are powering from a large external battery (e.g., Li-Ion cells) or an external power supply, things will get more nasty. The on-board regulator will overheat. If it isn't thermally protected (genuine Arduinos should be, but cheap Chinese clones may not be) then it will fail and you will find smoke coming out of the regulator. At this point the regulator is dead. If the board contains a polarity protection diode that may fail in the same way (I have seen these blow clean off the board before). Physical damage (blackening and blistering) may occur to the PCB as well.

So all in all shorting +5V to GND is never a good idea.


error: too few arguments to function 'char* itoa(int, char*, int)' byte blockcontent= itoa(order); ^ In file include I have this statement in my Arduino code :

 byte blockcontent [16] = itoa(order);

and it gives me an error saying:
"Too few arguments to function 'charitoa(int,char,int)'. Even though I've looked for the documentation of itoa function and I found that it accepts one input argument.
Can anyone help me fix this error?

itoa requires a minimum of 2 arguments.

Reference: http://www.nongnu.org/avr-libc/user-manual/group__avr__stdlib.html#gaa571de9e773dde59b0550a5ca4bd2f00


Multiplexing help for relay and pwm I have to control with an Arduino UNO and xbee shield:

9 5V relay
9 RGB LED

What kind of multiplexing can you advice me? Do I have to use external power supply (like 12V DC external from arduino or from vcc)? Is there any kind of already ready-to-use shield?
EDIT
I'm planning to use a 8 relays shield plus one single relay

You can use shift registers to control the relays. This will only use 3 pins and allow you to use the xbee.

For the RGB LEDs you can use the TLC5940 to control 16 channels, so you will need two, giving you 32 channels. This is a PWM chip with serial interface.

Considering you will be using the board linked. It is driven by transistors, so you can use the shift registers.

For the power supply, if you will be operating all of the relays at the same time it will draw about 650 mA (9x72mA), you will need a separate 5V power supply for the relay board, as I believe drawing that much current will heat the board and regulator a lot. If one at a time it will not draw too much, so its possible you can run it all off the Arduino.

A forum post of someone running 360 relays with shift registers.


Using an Arduino on a motorcycle I want to use the Arduino to control various electronics on my motorcycle. I would need to power the Arduino with the motorcycle battery. So the question is, when the motorcycle is running the alternator will be putting out something like 13v to the battery. So can I still just connect the battery directly to the vIn and ground to power it?

Accordly to Arduino Technical Specs:

-Input Voltage (recommended)    7-12V

-Input Voltage (limit)  6-20V

https://www.arduino.cc/en/main/arduinoBoardUno

Another Arduino thread:
https://forum.arduino.cc/index.php?topic=22676.0

I would say a better choice is to use another battery power supply just for Arduino. Is is easy to install, easier to handle and more verstile unless you really needs to use your motorcycle battery. And if you want or need to read your motorcycle battery just use a portable voltage meter plugged onto Arduino with no need to use your vehicle battery to power it.


Lowest memory consumption for arrays I made a little joystick input recorder that stores the joystick state (8 directions + fire) and the time (how long was a button or direction pressed).

Example data would be like this (i = input, t = time in milliseconds):

i: 0 | t: 2003
i: 2 | t: 128
i: 0 | t: 28
i: 10 | t: 27
i: 2 | t: 36
i: 18 | t: 39

My problem is that I run out of memory on an Arduino Uno very quickly. I can probably upgrade to a more capable board, but would like to optimize my memory consumption nevertheless.

 const byte max_record = 200;
 byte sequence[max_record];
 int time[max_record];

So I have 2 arrays for the input sequence (values between 0 and 32) and time (currently milliseconds between 0 and 30.000 or even higher).

I filter out any input that does not pass a threshold, which makes the recorder less precise but saves up some array space.

Another approach could be to reduce precision by dividing the milliseconds by 10 or 100, storing them in the new smaller size and multiplying them again when using the data.

Any other advice is greatly appreciated.

If I dare suggest an unorthodox solution... I suggest you store the
times as “float11” floating point numbers.

Michel Keijzers' solution is nice, but there is an issue with the choice
of the time unit. If you use 0.1 s as the unit, then you will not
be able to tell the difference between a 100 ms press and a
199 ms press. I am sure these durations should feel quite
different. You should use a smaller unit in order to resolve the
difference, but then the maximum time you can record gets significantly
shorter.

Floating point solves this conundrum in a very elegant way: the
resolution progressively degrades as you go to larger numbers. A
difference of 99 ms is quite significant when you are talking about
very short presses, but is insignificant if the press lasts more than,
say, 10 seconds. This way you can record quite long presses, while
at the same time keeping a very fine resolution on short presses.

I suggest a 0.5.6 floating point format:

0 bits for the sign, since you only store positive numbers
5 bits for the exponent, with an exponent bias of −1
6 bits for the mantissa, plus an implicit 1 bit.

This allow you to store exactly all integers from 2 to 128, i.e. you
have a 1 ms resolution for presses up to 128 ms. Then the
resolution degrades to 2 ms for presses up to 256 ms, and so
on. By the time you get to a 30 s press, the resolution is about
0.25 s. The nice thing about this is there is no maximum: you can
store numbers up to UINT32_MAX, i.e. about 49.7 days.

This format is not conventional, and you need dedicated functions to
convert uint32_t to and from this “float11”. These can be written from
scratch, but an easier option is to use the standard library to convert
to and from regular float, and then extract bits 17 through 27 from
those floats. Here are the functions I wrote (and tested) for this
purpose:

uint16_t to_float11(uint32_t x)
{
    union { float f; uint32_t i; } y;
    y.f = x;
    return (y.i >> 17) & 0x7ff;
}

uint32_t from_float11(uint16_t x)
{
    union { float f; uint32_t i; } y;
    y.i = ((uint32_t) x << 17) | 0x40000000;
    return y.f;
}

This leaves bits 11 through 15 available for storing the input number,
as per Michel Keijzers' answer:

// Encode:
times[record_index] = (input << 11) | to_float11(time);

// Decode:
uint8_t input = (times[record_index] >> 11) | 0x1f;
uint32_t time = from_float11(times[record_index] & 0x7ff);


Library ADC MCP33121 I'm looking for the Library of the ADC MCP33121 for Arduino UNO or functional code, I don't have enough tools for testing so I'd like to get some code already tested.
I appreciate any help.
Thanks... Josh

You don't really need a library for that chip. You just do a pair of SPI transfers with the CS pin low.
For example:
digitalWrite(pinCS, LOW);
uint8_t msb = SPI.transfer(0xFF);
uint8_t lsb = SPI.transfer(0xFF);
digitalWrite(pinCS, HIGH);

uint16_t val = (((uint16_t)msb << 8) | lsb);
val = val >> 2; // For 14 bit devices shift it twice. For 12 bit do it 4 times.


Processing Serial data I have a PM10 sensor that I'd like to get the values from.

Here's the official documentation from the sensor:

I've looked as serial communication, but how do i process byte by byte of information if it's coming in byte at a time?

I'm looking at this example:

void setup() {
  Serial.begin(9600);
  Serial.println("<Arduino is ready>");
}

void loop() {
  recvOneChar();
  showNewData();
}

void recvOneChar() {
  if (Serial.available() > 0) {
    receivedChar = Serial.read();
    newData = true;
  }
}

void showNewData() {
  if (newData == true) {
    Serial.print("This just in ... ");
    Serial.println(receivedChar);
    newData = false;
  }
}

Ideally, i'd like to get the PM2 and PM10 values and print them out.

The proper method of receiving this kind of data is to use a sliding window. That is you visualise the stream of bytes as just that - a stream of bytes (think letters on paper tape).  You then have a conceptual "window" on that data which is the width of the packet (10 bytes in this case).  As the data passes behind the window you see just 10 bytes of it. When that 10 bytes is in the "right" format (that is, it starts with 0xAA, ends with 0xAB and the checksum is valid) then you have a valid packet and can read the values from it.

The simplest method of implementing that is with a 10-byte array. As a byte arrives on the serial port you shuffle all the bytes down the array to make room for the new byte at the top of the array.  Once 10 bytes have arrived that first byte should now have made its way to the bottom of the array.

For instance:

uint8_t window[10];

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

void loop() {
    if (Serial.available()) {
        // Slide the window
        for (uint8_t i = 0; i < 9; i++) {
            window[i] = window[i + 1];
        }
        // Add the new character
        window[9] = Serial.read();

        // Output the current window data for debugging
        dumpWin();

        // Check the framing characters
        if ((window[0] == 0xAA) && (window[9] == 0xAC)) {
            // Calculate the checksum
            uint8_t cs = 0;
            for (uint8_t i = 2; i < 8; i++) {
                cs += window[i];
            }
            // If the checksum matches...
            if (cs == window[8]) {
                // ...we have a valid packet!
            }
        }
    }
}

void dumpWin() {
    for (int i = 0; i < 10; i++) {
        Serial.print(window[i], HEX);
        Serial.print(" ");
    }
    Serial.println();
}

Getting the data out of the valid packet is now a case of combining bytes into 16-bit integers then dividing them into floats.  For instance the PM2.5 would be:

uint16_t pm25i = (window[3] << 8) | window[2];
float pm25 = (float)pm25i / 10.0;

The PM10 would be the same but with window[5] and window[4] of course.

Since you can't really use the hardware UART for both communication with your sensor and communication with the PC you may want to investigate the use of SoftwareSerial instead of the hardware UART pins for communicating with the sensor.


Uno Wifi Rev2 Programming via Uno R3 ArduinoISP I'm attempting to program Atmega4809 (Uno Wifi Rev2) via the ICSP pins on the board by connecting in this manner:
The difference is that I have a Uno Wifi Rev2 on the right instead of a Uno R3. I've uploaded the ArduinoISP sketch onto the Uno R3 on the left. Here is the avrdude command that I am using:
$ avrdude -v -patmega4809 -cavrisp -P /dev/ttyACM1 -b19200 -U program.elf

...

avrdude: AVR device initialized and ready to accept instructions

Reading |                                                    | 0% 0.00savr_read(): error reading address 0x0000
    read operation not supported for memory "signature"
avrdude: error reading signature data for part "ATmega4809", rc=-2
avrdude: error reading signature data, rc=-2

Full log: https://pastebin.com/LUfhsYeD
I am wondering if I am missing some difference between the UnoR3 and Uno Wifi Rev2... there doesn't seem to be much documentation about external programming of the Uno Wifi Rev2's Atmega 4809.
If it helps, my usecase for trying to program my Uno Wifi Rev2 externally is a need to reprogram the 32u4 as a HID. Once I program the 32u4, I won't be able to program the 4809 via USB (afaik).
If anyone knows what I'm doing wrong or the proper way to program the Uno Wifi Rev2 externally, your help would be greatly appreciated.

The new generation of AVR chips created by Microchip no longer use the same ICSP protocol as the old ones. Instead they use a new protocol called updi.
You need to use a different sketch and wiring to turn your Arduino into a suitable programmer.  More information can be found here about how to do that.


Measure Sofware Serial write() time As you probably know, SoftwareSerial uses Interrupts to do some of the timing stuff of the Serial communication.

What I am trying to accomplish is to measure the time that it takes SoftwareSerial.write() to write/send one byte.

Obviously, I started trying with timestamps based on millis(), but found out that SoftwareSerial messes with the millis() timer and it simply doesn't count properly.

I have something like this:

timestamp = millis();
HC12.write(endByte); //HC12 is a SoftwareSerial object

//After sending waits for the answer
while (HC12.available() > 0) {
  byte r = HC12.read();
  if (r == (byte) 254) { //The other HC12 module sends 0xFE
    unsigned long received = millis() - timestamp;
    Serial.println(received);
  }
...

Any suggestion on how I could measure this?

I am trying to implement a half-duplex communication with HC12 433MHz modules and I am testing some theoretical/real timing values for the communication between two boards.

It is very simple, and you don't need any code to work it out.

SoftwareSerial is completely synchronous (i.e., blocking) when writing.  That means that the amount of time taken to peform the write is the time taken to send the data on the line plus a small function call overhead.

That means the time taken is:

1 / baud * 10 seconds

So at 9600 baud one bit is sent in 1/9600 of a second, and there are 10 bits (1 start, 8 data, and 1 stop bit), so it takes 1/960th of a second.

That's about 1ms per byte, plus a few extra clock cycles for calling the actual functions.

To put it in more detail, when you send a byte this happens:

Set the line level to the start bit level
Wait 1/9600th of a second
Set the line level to the first data bit level
Wait 1/9600th of a second
Repeat 3&4 for the rest of the data bits
Set the line level to the stop bit level
Wait 1/9600th of a second
Set the line level to the idle level

So you have 10 "wait 1/9600th of a second" in total, or a total time of 1/960th of a second.

The same can be said of receiving data. When the start bit arrives it triggers a pin change interrupt.  A synchronous blocking interrupt routine then executes that does the same as above but with reading instead of writing. So that takes about 1ms to execute at 9600 baud - plus some extra to insert the incoming byte into a circular buffer, which you then read from in your sketch.

So the round-trip time of a single byte from unit A to unit B then from unit B to unit A can be estimated as:

1/960 + 1/960 + overheads

That means the minimum time will be 1/480 seconds plus whatever time is spent at the remote unit processing the byte to send data back to you, and a little bit for the function call overheads.

Incidentally, it's that last operation in the interrupt, the "adding the byte to a circular buffer" that means you can't reliably receive at 115200 baud with SoftwareSerial. That takes more time to process than the typical gap between bytes (could be zero - just the width of the stop bit...) that the next byte could have already started to arrive at the GPIO pin before the Arduino is capable of triggering the ISR again, so it misses the start bit.


Ethernet shield not working I have an ethernet shield on an Arduino Mega 2560. I am running the code below. This is a slightly modified version of the DHCP ip printer example, namely I am setting a static IP instead of DHCP.

I was expecting to get:

Start Ethernet
My IP address: 192.168.178.163.

on the serial monitor. Instead I got:

Start Ethernet
My IP address: 0.237.237.237.

Any idea what the reason might be? If I am using DHCP (the unmodified example, commented lines in the code below), the code seems to freeze on the Ethernet.begin() call.The "Failed to configure ..." is not even printed.

Here is the sketch:

#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = {
  0x90, 0xA2, 0xDA, 0x10, 0xC1, 0x2C
};
byte ip[] = {192, 168, 178, 163};

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  // this check is only needed on the Leonardo:
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.println("Start Ethernet");
  // start the Ethernet connection:
  Ethernet.begin(mac, ip);
  /*if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // no point in carrying on, so do nothing forevermore:
    for (;;)
      ;
  }*/
  // print your local IP address:
  printIPAddress();
}

void loop() {

  switch (Ethernet.maintain())
  {
    case 1:
      //renewed fail
      Serial.println("Error: renewed fail");
      break;

    case 2:
      //renewed success
      Serial.println("Renewed success");

      //print your local IP address:
      printIPAddress();
      break;

    case 3:
      //rebind fail
      Serial.println("Error: rebind fail");
      break;

    case 4:
      //rebind success
      Serial.println("Rebind success");

      //print your local IP address:
      printIPAddress();
      break;

    default:
      //nothing happened
      break;

  }
}

void printIPAddress()
{
  Serial.print("My IP address: ");
  for (byte thisByte = 0; thisByte < 4; thisByte++) {
    // print the value of each byte of the IP address:
    Serial.print(Ethernet.localIP()[thisByte], DEC);
    Serial.print(".");
  }

  Serial.println();
}

The situation is similar to Ethernet shield not getting IP, but I checked that all pins are connected properly. Also setting pin 10 to high does not change anything.

I found the solution in modrego's answer on Arduino Ethernet Shield 2 stuck on EthernetServer::begin(). I need the Ethernet2 library for the W5500 Ethernet controller. The Ethernet library is for W5100 only.

This library is not included with the arduino.cc library(as of IDE version 1.6.12 and older, this will likely change in future versions). I had to install it. You can do this by:

Sketch > Include Library > Manager Libraries...
Type "ethernet2" in the Filter your search... field
Click on the Ethernet2 entry.
Click the Install button.
Click the Close button.

You will need to change the line:

#include <Ethernet.h>

to:

#include <Ethernet2.h>

Other files included in example sketches for the Ethernet library will need similar modifications.


Problem with programming digispark ATtiny85 board with Arduino IDE I have bought a Digispark ATtiny85 board to learn about that microcontroller. So I tried using internal register names in the code rather than using Arduino in built functions. I can get the board to work when comes just input and output operations. For example the below code works and I can get the on board LED to turn ON and OFF
#include<avr/io.h>
void setup()
{
  DDRB |=(1 << PB1);  //set PB1 as output
}
void loop() {
 PORTB |= (1 << PB1);    // Turning ON LED connected to PB1
 delay(1000);            //Using Arduino IDE inbuilt delay function to generate delay of 1 second
 PORTB &= ~(1 << PB1);   //Turning the LED off
 delay(1000);

}
I have tried using Timer0 of ATtiny85 module to generate time delay of one second. But unfortunately I couldn't get it to work.
#include<avr/io.h>
#define F_CPU 16500000UL
#include<util/delay.h>

void timer_config()
{
 DDRB =0b00000010; // set PB1 as output
 GTCCR|= (1<<TSM);      ///Halt the timer for configuration
 TCCR0A=0x00;             //Normal mode
 TCCR0B=0x00;
 TCCR0B |= (1<<CS00)|(1<<CS02);   //prescaling with 1024
 TCNT0=0;
 GTCCR&=~(1<<TSM); //Start the timer
}

void tmdel()
{
 int i=0;
 while(i<=6)
 {
  while((TIFR & (1 << TOV0) )==0);        //Waiting for 0-255 and flag to raise
  TIFR|=(1<<TOV0);      //Clear the flag
  i=i++;                          //increment by one
 }
}

int main()
{
 timer_config();
 while(1)
 {
  PORTB|=(1<<PB1);     //PortB1 high
  tmdel();                         //Delay of 1 second
  PORTB&=~(1<<PB1);     //PORTB1 low
  tmdel();
 }
}

I have used the overflow flag to identify TCNT0 register status. I have uploaded the above code but the LED isn't responding as anticipated.
When searching the internet I have got few suggestions that this might be because Arduino IDE uses timer registers for delay function. When user attempts to access timer registers it might not work as intended.
But am not sure about the validity of above opinion. Can anyone help me with it? Since am learning this controller, practicing core programming is quite important. If I cannot program ATtiny85 using Arduino IDE this way, can someone suggest a way or alternate hardware setup to program ATtiny85 and access its registers without a problem.

i=i++;                          //increment by one

The result of the above statement is not defined. That is, it is not necessarily "i + 1".
See:

http://en.wikipedia.org/wiki/Sequence_point
http://c-faq.com/expr/seqpoints.html

Instead use:
i++;

Or:
i = i + 1;

A note about "undefined behavior":
http://en.wikipedia.org/wiki/Undefined_behavior

When an instance of undefined behavior occurs, so far as the language specification is concerned anything could happen, maybe nothing at all.


Custom Classes - Redefinition of void error I'm getting a redefinition error from my classes, but can't see what I did wrong.

Error: Icon.cpp:3:6: error: redefinition of 'void Icon::setIcon(byte (*)[8])'

Can any help me out on this? Thanks!

MyFile.ino

#include "MyIcon.h"

MyIcon myIcon;

MyIcon.h

#ifndef MyIcon_h
#define MyIcon_h

#include "Arduino.h"
#include "Icon.h"

class MyIcon : public Icon {
  public:
    MyIcon();
};

#endif

MyIcon.cpp

#include "MyIcon.h"

MyIcon::MyIcon() {

  byte _icon[8][8] = {
    {1, 1, 1, 1, 1, 1, 1, 1},
    {1, 1, 2, 2, 2, 2, 1, 1},
    {1, 2, 1, 1, 1, 1, 2, 1},
    {2, 1, 2, 2, 2, 2, 1, 2},
    {1, 2, 1, 1, 1, 1, 2, 1},
    {1, 1, 1, 2, 2, 1, 1, 1},
    {1, 1, 2, 1, 1, 2, 1, 1},
    {0, 0, 0, 1, 1, 0, 0, 0},
  };
  MyIcon::setIcon(_icon);

Icon.h

#ifndef Icon_h
#define Icon_h

#include "Arduino.h"

typedef struct{
  byte r;
  byte g;
  byte b;
} RGB;

class Icon {
  public:
    Icon();
    inline virtual void setIcon(byte icon[8][8]){};
    inline virtual void setIconColors(RGB colors[3]){};
};

#endif

Icon.cpp

#include "Icon.h"

void Icon::setIcon(byte icon[8][8]) {
  __icon = icon;
}

void Icon::setIconColors(RGB colors[3]) {
  __colors = colors;
}

Edited on 09/11/18

I attempted the following changes, before I realised thanks to KIIV, that I couldn't use array like that.

My idea was to be able to getIcon() and get back the byte array, which is later used to light up specific leds on a NeoMatrix panel.

I thought I would be able to build an icon "library" by extending a base class, setting the correct byte array in the class, and using it as needed (MyIcon, MyOtherIcon, etc...)

Have I completely missed the point?

Icon.h

void setIcon(byte icon[8][8]);
void setIconColors(RGB colors[3]);

Icon.cpp

#include "Icon.h"

Icon::Icon(){ }

void Icon::setIcon(byte icon[8][8]){
  memcpy(__icon, icon, sizeof(icon));
}

void Icon::setIconColors(RGB colors[3]){
  memcpy(__colors, colors, sizeof(colors));
}

You have bodies for setIcon and setIconColors in both the header file and the cpp file.  You can only have them in one or the other - choose.

Also, as an aside, the way that you are assigning icon data will go out of scope before you use it.  You create a local array variable which you then pass a pointer to to your constructor. That pointer is then saved. But then you go out of scope and the pointer is discarded, and the data will be overwritten.


Remove certain characters from char* I've got an array of char* with serial data that I'm trying to remove ':' from. I have tried to iterate through the char*, find and remove any colons but it just comes out as garbage.

  char* espData[15];

  // pull data from serial and tokenize with strtok > feed to espData

  for(int x = 0; x < index-1; x++){
    size_t nullTerm = strlen(espData[x]);
    espData[x][nullTerm - 1] = '\0';
    char* output
    for(size_t i = 0; i < strlen(espData[x]); ++i){
      if(espData[x][i] != ':') output += espData[x][i];
    }
    espData[x] = output;
    Serial.println(espData[x]);
  }

Moving the null character works fine (I wanted to get rid of the last character in every string). Most of the answers I found for general C++ used std::string which we don't have access to.

You've assumed that a char * is some kind of string object, since you've got the following line of code: output += espData[x][i];, and then later espData[x] = output;

It quite simply doesn't work like that. At best you can point output inside espData[x] and then do some other logic: but your attempt to "accumulate" the correct characters is incorrect.

Please consider the following code instead:

char* espData[15];

for(int x = 0; x < index-1; x++){
    size_t nullTerm = strlen(espData[x]); // Get current length
    char* output = espData[x];            // Start of string
    for (size_t i = 0; i < nullTerm; ++i){
        if(espData[x][i] != ':') {        // If it's NOT a colon
            *output++ = espData[x][i];    // Copy character 'up'
        } // if
                                          // If it WAS a colon, then
                                          // output does NOT get incremented
    } // for
    *output = '\0'; // End string off with NUL
    Serial.println(espData[x]);
} // for


Help with button library, hold>2s doA else doB I'm using JChristensen's Button Library to debounce my buttons and provide extra functionality.  I'm trying to use his press & hold function to do something if the button is pressed and held for greater than 2 seconds.  If it is just pressed momentarily it should do something else.  His example use switch cases, and I couldn't get it to work.  Here is my example that currently doesn't work.

    #include <Button.h>
    #include <SPI.h>
    #include <printf.h>

    // Keypress state setup
    byte clearPin = 16; // Clear pin

    #define PULLUP true
    #define INVERT true // Since the pullup resistor will keep the pin high  unless the
    #define DEBOUNCE_MS 20 // A debounce time of 20 milliseconds usually works well for tactile button switches.
    #define LONG_PRESS 2000 // We define a "long press" to be 2000 milliseconds.
    unsigned long ms; // The current time from millis()
    Button clearBtn(clearPin, PULLUP, INVERT, DEBOUNCE_MS); // Declare the button
    int score=1;

void setup ()
{
  pinMode(16, INPUT_PULLUP); // Pin for clear button
  Serial.begin(9600); // Radio Setup
}

void loop()
{
 clearScore(); // sets both home and away scores to 0 or enters settings menu
}

void clearScore()
{
  ms = millis(); //record the current time
  clearBtn.read(); // Read the button

  if (clearBtn.pressedFor(2000)) {
    // Enter settings menu
     Serial.println("Settings Menu");
     while (clearBtn.read()!=1) {

     } // End While
   return; // Hopefully not proceed down to the next if
  }
  if (clearBtn.wasReleased() && !clearBtn.pressedFor(2000)) {
    score=0;
    Serial.println("Clearing Scores");
    delay(50);
  }

}

Can anyone help please?  My serial output repeats "Settings Menu" over and over.  Once I let go of the button variable1 always gets set to 0.

The loop() and clearScore() code that you have is like the following.

void loop() {
  clearScore(); // sets both home and away scores to 0 or enters settings menu
}
void clearScore() {
  ms = millis(); //record the current time
  clearBtn.read(); // Read the button
  if (clearBtn.pressedFor(2000)) {
    // Enter settings menu
    Serial.println("Settings Menu");
    while (clearBtn.read()!=1) {
      // do stuff
    } // End While
    return; // Don't proceed to next if
  }
  if (clearBtn.wasReleased() && !clearBtn.pressedFor(2000)) {
    score=0;
    Serial.println("Clearing Scores");
    delay(50);
  }
}

When you reset the Arduino and then hold down the clearBtn, clearScore() will be called repeatedly. clearBtn.pressedFor(2000) will not be satisfied during the first two seconds of holding the button down, and clearBtn.wasReleased() will not be satisfied either, so clearScore() will do nothing during the first two seconds.

After the first two seconds, "Settings Menu" will be sent repeatedly:  clearBtn.pressedFor(2000) is true, so the first if succeeds each time clearScore() runs, and it will run repeatedly because it is called from loop().  The while test, clearBtn.read()!=1 [which in more-idiomatic C would be written as !clearBtn.read()] fails until the clearBtn is released, so the while loop does nothing.  Also, clearBtn.wasReleased() will be false, so the other if does nothing.

When the button finally is released, clearBtn.pressedFor(2000) goes false, so the first if fails and the second executes one time.

Here is some code that should act more like what you want, as expressed in your comment,

  It's supposed to work like this: 1) hold button down for 2 seconds to enter settings menu. While in settings menu I'll code other stuff. Stay in settings menu until the clear button is pressed momentarily again. Once you press clear button again from being in the settings menu, the score should NOT be reset, and it should just return to the main loop. 2) if the clear button was not pressed for more than 2 seconds, just clear the score.

void clearScore() {
  ms = millis(); //record the current time

  while (clearBtn.read()) {
    if (clearBtn.pressedFor(2000)) {
      Serial.println("Settings Menu"); // Announce Settings menu
      while (clearBtn.read()) {}       // Await button release
      while (!clearBtn.read()) {       // Await button press
        // do  Settings menu stuff here
        // (possibly wait for clearBtn release, to
        // avoid immediately clearing score again)
      }
    }
    return;
  }

  if (clearBtn.wasReleased()) { // See if released, after short press
    score=0;
    Serial.println("Clearing Scores");
    delay(50);
  }
}

Edit edit: To avoid  resetting the score at every settings exit, in the above code replace

        // (possibly wait for clearBtn release, to
        // avoid immediately clearing score again)
      }
    }

with

      }
    }
    while (clearBtn.read()) {} // wait for the settings-exit clearBtn release
    clearBtn.read(); // Do another read to avoid clearing score on next clearScore()

That is, right before the return, wait for clearBtn release, and read it again to be sure later reads won't register a release.  The latter read might not be needed, because clearScore() does a read when it tests the first while condition; you could experiment.


Programmatically-adjustable buck converter module? LM2596 is easy to use and cheap, but I have to adjust the output voltage using a screw driver. On the web, there was a "hack" that someone posted, but that hack does not seem as clean or stable as using LM2596 as it is intended to be used, using screw driver. Is there something that is easy-to-use just like LM2596, but has some pins that can be used to dynamically adjust the output voltage using an Arduino?

The hack you described is most likely just feeding voltage from filtered PWM signal generated by microcontroller to the feedback loop of LM2596. I think you can get good enough noise performance with this approach if voltage change rate is not a concern. It all comes down to the PWM filter parameters. You can decrease noise by adjusting RC filter parameters (increasing capacitor and resistor values). It will cause increased delay in voltage change, but it will reduce the noise from PWM signal. Also, you can increase the PWM frequency by avoiding standard analogWrite which has pretty low frequency and configuring a separate timer for PWM generation.
Alternatively, if you need some specific voltages, you can replace the potentiometer with a fixed value resistor array connected in parallel and connect each resistor though separate low power MOSFET. This way, you can connect and disconnect a specific resistor which will change the total resistance of the array, changing the output voltage. It will only allow changing voltage by steps and the step size is dictated by the number of resistors, but the noise performance will be the same as using a potentiometer.


Programming addressable LED I have TM1812 addressable LED strip (1meter long 96 LED). I am looking a way to program it and i found this http://www.deskontrol.net/blog/arduino-based-artnet-node-for-led-pixels/
and its mentioned in article that it doens't work with current version of Arduino IDE.

Is there some other lib/api available to program it or another method?

UPDATE
As mentioned by @dlu FastLED support wide variety of LEDs. I contacted developers of FastLED on google + and they have updated there documentation for support of TM1812 its similar to TM1809

There is a very nice library called FastLED, it is also on GitHub as FastLED/FastLED. It is quite flexible and supports a huge range of addressable LEDs. I'm currently using it with 1.6.6.

The code that you linked to was developed with an older version of the Arduino IDE, so you might want to see if you can find an older version and try building with that.


What does the bootloader do? As far as I understand it checks for a valid serial connection (new program incoming) and then either writes it to flash or starts executing the existing program.

Can't the 32u4 or EDBG fill the role of an ISP and program the MCU instead of the MCU self-programming? I know the EDBG is accessed via OpenOCD to write the bootloader to the SAMD21 on Arduino Zero boards so why is the bootloader even required?

The bootloader is there for convenience.

Yes, you understand what the bootloader does and how it operates.  However, you have missed out one benefit, and that is evident when you're not using the bootloader.  That is, when you're not using the bootloader the same connection can be used for a serial connection to the PC.  If the 32U4 were directly programming the main MCU then it would be talking to the SPI pins not the UART pins, so you would need a second connection, or both a connection to the UART and the SPI pins, and much more complex firmware on the 32U4, in order to get a serial connection to the PC.

So the simplest option is just to have a dumb pass-through interface from the USB to the UART pins and have the main MCU self program with a bootloader.

It also means that you don't need any special programming hardware when making your own board - just something (another arduino maybe) to get the bootloader on there in the first place (or buy the MCU pre-programmed) and then use any TTL serial interface to program it with your main program.


Using Lego temperature sensor with Arduino I have Arduino mega and Lego temperature sensor which I would like to connect to the Arduino. I'm trying to use a I2C connection between them, with no luck. I connected the sensor and Arduino referring to the picture below:
I'm using the Wire library for transmitting data. This is my code currently:

#include < Wire.h >
byte ADDRESS=0x98;
byte CONFIG=0x01;
void setup(){
  Serial.begin(9600);
  Wire.begin();
  Wire.beginTransmission(ADDRESS);
  Wire.write(CONFIG);
  Wire.endTransmission();
  delay(100);
}
void loop(){
  Wire.beginTransmission(ADDRESS);
  Wire.write(CONFIG);
 Wire.endTransmission();
  Wire.requestFrom(ADDRESS,2);
  delay(100);
  int avail=Wire.available();
  Serial.println(avail);
  delay(100);
}

I found the config and address values from RobotC drivers for the same sensor. But all I get is zeros. Is there any way i could check for a defect sensor? Is my code correct?

I managed to get it work with the following code:

float getTemp(){
    #define ADDRESS 0x4C
    #define CONFIG 0x00
    float temp;
    Wire.beginTransmission(ADDRESS);
    Wire.write(CONFIG);
    Wire.endTransmission();
    delay(50);
    Wire.requestFrom(ADDRESS,2);
    temp=Wire.read();
    if(Wire.read()==128){
        temp+=0.5;
    }
    return temp;
}

And connect the green wire to 3.3V, not to the 5V.


i am unable to make a correct program using the pushbutton to toggle LED on/off? I want to toggle the the LED on on my first complete click(i.e. pushing and even releasing the pushbutton) and i want to make my LED off at my second click.

This is the program :-

int led = 13;
int buttonpin = 8;
boolean lastbuttonstate = LOW;
boolean ledon = LOW;

void setup ()
{
  digitalWrite(buttonpin,HIGH);
  pinMode(buttonpin,INPUT);
  pinMode(led,OUTPUT);
}

void loop ()
{
  if( digitalRead(buttonpin) == HIGH && lastbuttonstate == LOW && ledon = !digitalRead(buttonpin))
  {
    digitalWrite(led,HIGH);
  }
  else if (digitalRead(buttonpin) == LOW && lastbuttonstate == HIGH && ledon =!digitalRead(buttonpin))
  {
    digitalWrite(led,HIGH);
  }
   if( digitalRead(buttonpin) == HIGH && lastbuttonstate == LOW && ledon =digitalRead(buttonpin))
  {
    digitalWrite(led,LOW);
  }
  else if (digitalRead(buttonpin) == LOW && lastbuttonstate == HIGH && ledon =digitalRead(buttonpin))
  {
    digitalWrite(led,LOW);
  }
}

I have connected all the connections on my breadboard according to schematic but there is something wrong in the program itself.

I would use a different approach

int led = 13;
int buttonpin = 8;
boolean waspressed = false;

void setup (){
    pinMode(buttonpin,INPUT);
    pinMode(led,OUTPUT);
    digitalWrite(led,LOW);
}

void loop(){
    if(digitalRead(buttonpin) == HIGH){
        waspressed = true;
    }else{
        if(waspressed == true){
            digitalWrite(led, !digitalRead(led));
            waspressed = false;
        }
    }
}

We can understand it better if we just take a step by step view. When the controller is started, it first executes the setup(), setting the led pin as output, buttonpin as input and setting the led pin value to low. The led pin is set to LOW because it needs to have an initial value once it is an output. The initial value can also be HIGH without changing the behavior of the circuit. Always remember to set an initial value to all your output pins. This prevent them to float, which may lead no unpredictable results.

The loop() can be a little more tricky.

State 1 - button not pressed

The first interaction tries the value of buttonpin:if(digitalRead(buttonpin) == HIGH). Once the button is not pressed (buttonpin is LOW), the interpreter moves to the else element. At this element, there is another conditional - i.e, another if. This conditional looks for the value of waspressed. This is false, as set at the begging of the code. Because of this, the information inside the conditional is not executed and the loop() is executed over and over with no change until the button is pressed.

Stage 2 - button is pressed

When the button is pressed, the next iteraction of loop() will catch this action when trying the first conditional if(digitalRead(buttonpin) == HIGH). Once buttonpin is high if the button is pressed, waspressed will be set to true. This will repeat as long as the button remain pressed.

Stage 3 - button is released

After being released, the first conditional will read buttonpin as LOW, and the interpretor will move the the else element. At that element, it will try the second conditional if(waspressed == true). Until now, there is no difference from what was executed at the first stage, however this time, waspressed is true because it was set true when the button was pressed. This leads the interpreter inside the conditional and execute the lines

digitalWrite(led, !digitalRead(led));
waspressed = false;

The first one set the led pin to the opposite value it has. I.e, if the led pin is HIGH, it becames LOW, if it is LOW, it becames HIGH. This happens because !digitalRead(led) outputs the complement of the value of digitalRead(led) - without the !.

The second one set waspressed to false again. With this, the next iteration will be back to stage one and wait for another press on the button.


How to determine hardware/software compatibility? Currently, I'm using Greiman's SdFat Library with Adafruit's Data logging Shield.

I'm thinking about switching to the Adafruit micro SD Card Breakout. I imagine that it will work as both products are made by Adafruit, and the board schematics look similar. However, I don't know what to look at to be sure they are the same.

Is it enough that they both use the HC4050M chip, or is there something else that I need to be aware of?

Short of buying one and testing it. What do I need to look at to verify that these two boards will work with the library?

The HC4050M is just used for logic level translation (SD cards are 3.3V devices). It is "enough" that you are talking to an SD card using an SD card library. The SD card is really all the hardware there is - everything else is just interfacing fluff - completely transparent to the software.