Reading Infrared raw data I'm trying to understand a few things about this code.

Why is digitalRead() slower than IRpin_PIN & (1 << IRpin)?
What does IRpin_PIN & (1 << IRpin) mean? I translated it to numbers and I figured out it's actually PIND & (0b100). What does PIND translate to and why is bitwise-and with 0b100 performed on it?
Why is the 20-microsecond delay (RESOLUTION) necessary?
What does _BV in while (! (IRpin_PIN & _BV(IRpin))) mean?

/* Raw IR decoder sketch!

 This sketch/program uses the Arduno and a PNA4602 to
 decode IR received. This can be used to make a IR receiver
 (by looking for a particular code)
 or transmitter (by pulsing an IR LED at ~38KHz for the
 durations detected

 Code is public domain, check out www.ladyada.net and adafruit.com
 for more tutorials!
 */

// We need to use the 'raw' pin reading methods
// because timing is very important here and the digitalRead()
// procedure is slower!
//uint8_t IRpin = 2;
// Digital pin #2 is the same as Pin D2 see
// http://arduino.cc/en/Hacking/PinMapping168 for the 'raw' pin mapping
#define IRpin_PIN      PIND
#define IRpin          2

// the maximum pulse we'll listen for - 65 milliseconds is a long time
#define MAXPULSE 65000

// what our timing resolution should be, larger is better
// as its more 'precise' - but too large and you wont get
// accurate timing
#define RESOLUTION 20

// we will store up to 100 pulse pairs (this is -a lot-)
uint16_t pulses[100][2];  // pair is high and low pulse
uint8_t currentpulse = 0; // index for pulses we're storing

void setup(void) {
  Serial.begin(9600);
  Serial.println("Ready to decode IR!");
}

void loop(void) {
  uint16_t highpulse, lowpulse;  // temporary storage timing
  highpulse = lowpulse = 0; // start out with no pulse length
//  while (digitalRead(IRpin)) { // this is too slow!
    while (IRpin_PIN & (1 << IRpin)) {
     // pin is still HIGH
     // count off another few microseconds
     highpulse++;
     delayMicroseconds(RESOLUTION);
     // If the pulse is too long, we 'timed out' - either nothing
     // was received or the code is finished, so print what
     // we've grabbed so far, and then reset
     if ((highpulse >= MAXPULSE) && (currentpulse != 0)) {
       printpulses();
       currentpulse=0;
       return;
     }
  }
  // we didn't time out so let's stash the reading
  pulses[currentpulse][0] = highpulse;
  // same as above
  while (! (IRpin_PIN & _BV(IRpin))) {
     // pin is still LOW
     lowpulse++;
     delayMicroseconds(RESOLUTION);
     if ((lowpulse >= MAXPULSE)  && (currentpulse != 0)) {
       printpulses();
       currentpulse=0;
       return;
     }
  }
  pulses[currentpulse][1] = lowpulse;
  // we read one high-low pulse successfully, continue!
  currentpulse++;
}

void printpulses(void) {
  Serial.println("\n\r\n\rReceived: \n\rOFF \tON");
  for (uint8_t i = 0; i < currentpulse; i++) {
    Serial.print(pulses[i][0] * RESOLUTION, DEC);
    Serial.print(" usec, ");
    Serial.print(pulses[i][1] * RESOLUTION, DEC);
    Serial.println(" usec");
  }
  // print it in a 'array' format
  Serial.println("int IRsignal[] = {");
  Serial.println("// ON, OFF ");
  for (uint8_t i = 0; i < currentpulse-1; i++) {
    //Serial.print("\t"); // tab
    Serial.print("pulseIR(");
    Serial.print(pulses[i][1] * RESOLUTION , DEC);
    Serial.print(");");
    Serial.println("");
    //Serial.print("\t");
    Serial.print("delayMicroseconds(");
    Serial.print(pulses[i+1][0] * RESOLUTION , DEC);
    Serial.println(");");
  }
  //Serial.print("\t"); // tab
  Serial.print("pulseIR(");
  Serial.print(pulses[currentpulse-1][1] * RESOLUTION, DEC);
  Serial.print(");");
}

int digitalRead(uint8_t pin)
{
    uint8_t timer = digitalPinToTimer(pin);
    uint8_t bit = digitalPinToBitMask(pin);
    uint8_t port = digitalPinToPort(pin);

    if (port == NOT_A_PIN) return LOW;

    // If the pin that support PWM output, we need to turn it off
    // before getting a digital reading.
    if (timer != NOT_ON_TIMER) turnOffPWM(timer);

    if (*portInputRegister(port) & bit) return HIGH;
    return LOW;
}

1) so it

calls function digitalRead() (puts value on stack, jumps, prepare function frame - each cost some time)
calls 3 other functions (with all the same problems)
check for sanity of value
check for PWN (and eventually calls another function)
does the PIND & (0b100)
returns from function (so read stack, clear the frame, jumps, set the result)

just to obtain the same functionality

typical for library functions, that each call makes sure the environment is sane and expected each and every time it is called - in close loop you can check it onece before and then just do not broke it
translates parameter from nice arduino numbers to real addresses and bits each and every time again

2) it access the PORT D (see AVR (the processor) internal construction) and reads value of its 3. bit (which maps to the relevant pin of the chip/Arduino board

3) see following comment - it is expected length of the pulse (maybe with some safety limit)

4) _BV is for BitValue - shift 1 to position given by arg (that is macro doind 1 << IRpin) maybe more nice/readable version, compiles to the same. (the ! is ofcourse negaition)


Capacitive Sensor gets stuck I want to use CapacitiveSensor library in order to make my own aluminum keys piano. I have seen many videos online showing projects like the one I'm trying to do, but for some reason mine doesn't work.

Here's my cuircit:

Here's my code:

#include <CapacitiveSensor.h>

CapacitiveSensor   cs_7_6 = CapacitiveSensor(7,6);  // 10M resistor between pins 7 & 6, pin 6 is sensor pin

void setup()
{
   //cs_7_6.set_CS_AutocaL_Millis(0xFFFFFFFF);     // turn off autocalibrate on channel 1 - just as an example
   Serial.begin(9600);
}

void loop()
{
    long start = millis();
    long total1 =  cs_7_6.capacitiveSensor(5);

    Serial.print(millis() - start);        // check on performance in milliseconds
    Serial.print("\t");                    // tab character for debug windown spacing

    Serial.print(total1);                  // print sensor output 1
    Serial.println("\t");

    delay(10);                             // arbitrary delay to limit data to serial port
}

This happens whenever I touch the aluminum foil:

First nothing happens (for ~1 sec), then it prints -2 as the capacity value, and when I release my finger from the foil it prints a very high value.

Anyone knows the reason for it? I'm searching for an answer for a long time and still can't find a solution...

The problem is that you're touching the foil.

The "capacitive sensing" used in that library is crude at best.

If you read the Arduino Playground page for the Capacitive Sensing Library it discusses a lot of the problems with the library, including grounding.  Make sure that the Arduino is properly grounded, or provide your own ground plane under the foil sensors.

Also they talk about the value of resistor and the sensitivity.  With a 10MΩ resistor you get sensing at (supposedly) 4-6cm from the foil.  That's the value you're seeing as you remove your finger.  While you're touching the foil it's just having a complete brain haemorrhage and can't work out what is going on (completely unable to charge the pin since you are leeching off all the current).  For "absolute touch" it recommends no more than 1MΩ.

Of course, as I mentioned, that method is rather crude.  To do it properly you need to:

Discharge an analog input pin through a MOSFET to ground (low impedance).
Apply a constant current (typically 50µA is used but varies depending on ADC characteristics) to the analog input for a fixed amount of time.
Remove the current and measure the voltage on the ADC input.
Repeat.

More modern MCUs have this kind of functionality built in, in the form of a "CTMU" - Charge Time Measurement Unit.  If you want to have anything more than "there's someone vaguely in the vicinity of the sensor" then I would suggest switching to a more modern MCU and doing it properly, or employing a specific CTMU chip as an external device.

Also, the sensor should be comprised of three parts - a ground plane, a sensor plane (connected to the ADC) and a dielectric layer between them.  The sensor should also be insulated from direct touch.


Resolved: ESP8266 works when arduino UNO reset pin is grounded I'm setting up PIR and esp8266 with arduino UNO.
First my esp8266 doesn't work after alot of research my esp8266 start working when I put arduino UNO reset pin to ground.
But now my arduino UNO does not run any program and I'm not able to use PIR with this wifi module.
Any help will be appreciated

Only one extra thing is that reset pin is set to GND pin.

The RESET of the UNO puts the ATMega328P (the MCU of the UNO) into an electrically inert state when it is connected to GND.  It is not supposed to be running your sketch when it is being held in reset.  It is, roughly speaking, electrically disconnected from everything else on the board.  This allows you to use the UNO as though it were a USB to TTL serial cable.
If you want to be able to run a sketch on the UNO while it uses the ESP8266, you'll need to not hold reset to GND and you'll also, practically speaking, need to choose a different set of pins for communicating with it, as D0 and D1 on the UNO are the same signals used to for the ATMega328P to talk to the host and used for programming the UNO via its bootloader.  On the UNO, you'd instead need to use SoftwareSerial (or something similar) and pins other than D0 and D1.  [Update: see the original poster's own answer containing the guide they ultimately used, making use of SoftwareSerial on pins 10 and 11]
The ESP-01 can run Arduino sketches using the ESP8266 Arduino core and it may make a great deal more sense to not involve the UNO at all, and instead connect the distance sensor more or less directly to the ESP8266.


HTTPS GET request working on esp32 but not on esp8266 I'm trying to port my esp32 program to esp8266, and i've come across a problem where i can't get a response from a HTTPS GET request on esp8266, but on my esp32 the same code works fine.
The function i'm using looks like this:
void GetHTTP()
{
  if (WiFi.status() == WL_CONNECTED)
  {
    HTTPClient http;
    http.begin(requestURL);
    int httpCode = http.GET();
    if (httpCode > 0)
    {
      requestData = http.getString();
      GenerateTable();
      //GetDelimiterCount(requestData, delimiterStart);
    }
    http.end();
  }
}

I've also tried running my request with the esp8266 "BasicHttpsClient" and "BasicHttpClient", and in both cases the program returns the error: "connection failed" from https.errorToString(httpCode).s_str()
or http code "-1" without any API specific error codes.
I'm requesting from Trafiklab's realtime infromation v4 API And
the request looks somewhat like this:

https://api.sl.se/api2/realtimedeparturesV4.json?

I've omitted the API key and parameters i use from this URL. The response is also correct when requested by any browser.
Could this be something to do with SSL? I'm completely out of clues as to what the differences between esp32's and esp8266's http-client libraries might be. I'm also using the latest version of the ESP8266 Boards libraries (2.7.4).

I ended up using

ESP8266WiFi.h

instead of

ESP8266WiFiMulti.h

This fixed both my original code and the basic HTTPS example. I still don't understand what difference it made though.


Using special Arduino "boolean" Data Type instead of standard "bool" data type There is a special, non-standard Arduino data type called "boolean".
How does it compare with the standard C++ data type "bool", and what are the reasons to use one or the other?
If they are identical in usage, why do both exist, and which one is preferred in Arduino code?

While the other answers give generally useful information, the authors seem to have not read the question very carefully because they are talking about the bool type rather than the boolean type. In the Arduino API, boolean is a type alias for bool, as defined in Arduino.h:

https://github.com/arduino/Arduino/blob/1.8.3/hardware/arduino/avr/cores/arduino/Arduino.h#L125

typedef bool boolean;

So you can use the boolean type just as you would bool and any standard C++ programming reference will instruct you in the use of bool. For this reason the other answers which mistakenly refer to bool are still somewhat useful.

Apparently at some point in the past the Arduino folks decided the name boolean would be more beginner friendly than bool, perhaps to be consistent with the Processing language. However, as discussed here:

https://github.com/arduino/Arduino/issues/4673

the unnecessary use of a non-standard type is now considered by some to be a poor decision as its use makes code less portable and really doesn't provide any clear advantage over bool. A proposal is in the works to remove the use of boolean from all official Arduino code and document bool in the Arduino reference and some even wish to formally deprecate boolean. Therefore my advice is to use bool instead of boolean in your code.


Can I switch a pulse solenoid from the onboard 5V/3.3V power source? I have two pulse solenoids.  One is 6V...

http://www.ebay.com.au/itm/282002733837?_trksid=p2057872.m2749.l2649&ssPageName=STRK%3AMEBIDX%3AIT

and the other is 3.6V...

http://www.ebay.com.au/itm/131989042565?_trksid=p2057872.m2749.l2649&ssPageName=STRK%3AMEBIDX%3AIT

I have a Wemos R2 Mini with an ESP8266 chip on it, and I'm running the switching operation through a H Bridge motor shield (which handily switches the polarity of the electricity for a short time, which opens/shuts the solenoid).

I want to run this thing off a smallish battery pack that will supply 5V to the WeMos. I have three questions:

1) Can I send a 3.6V solenoid a 60ms pulse to open/shut it from a 5V power source without burning out the coil or causing any other damage?

2) Is 3.3V too low to power a 3.6V solenoid?

3) Do pulse solenoids still generate back EMF?

I don't know a lot about solenoids or electromagnetic fields so, sorry if my questions are noobish.

1) Can I send a 3.6V solenoid a 60ms pulse to open/shut it from a 5V
  power source without burning out the coil or causing any other damage?

No. If it's 3.6V then you need 3.6V - 5V will most likely make it smoke. Use a regulator (preferably a buck one, since it is apparently 500mA) to power your H-bridge.

  2) Is 3.3V too low to power a 3.6V solenoid?

Maybe, maybe not. It may be that 3.6V is the absolute maximum and may switch from 3V to 3.6V.

  3) Do pulse solenoids still generate back EMF?

Normally, yes, since they are just a coil like any other inductive load. Your H-bridge should deal with that though if designed right.

To get any meaningful answers you will need a datasheet. Buying such things from eBay is never a good idea unless you have used it before and know what it is, what its specifications are, and how you use it, or they provide a link to a datasheet. Without a datasheet most questions will be answered with a "maybe".


ESP8266 ASyncTCP class example I am new to ESP programming on Arduino, as before I was developing on eLua. There were some memory problems in Lua, so I decided to move to Arduino.

After looking at some examples, I found a library called AsyncTCP and I was very glad because it provides callbacks for events just like Lua. But I was very disappointed when I found no example of an async TCP server. Instead there is an AsyncWeb Server but I don't want to use an HTTP server: I want a simple telnet server. Does someone have a working example?

There are examples in the ESP8266 library
https://github.com/me-no-dev/ESPAsyncTCP/tree/master/examples


Why are commands executing on their own? This is the program I have used. It's working fine. But I don't known why sometimes it operates on its own. It is used to control a welding machine (Arduino is isolated from earthing). When there is a little vibration the code executes a command. This is the code:

int a = 9;  //right actuator forward relay 1
int b = 12; //right actuator reverse relay 2 (orange 10)
int c = 10; //left actuator forward relay 4
int d = 11; //left actuator reverse relay 3
int x = 0;
int y = 0;
const int stepPin = 8; // HIGH =DOWN; LOW == UP
const int dirPin = 7;

void setup() {
  pinMode(5, INPUT_PULLUP);
  pinMode(6, INPUT_PULLUP);
  pinMode(a, OUTPUT);
  pinMode(b, OUTPUT);
  pinMode(c, OUTPUT);
  pinMode(d, OUTPUT);
  pinMode(stepPin, OUTPUT);
  pinMode(dirPin, OUTPUT);
  pinMode(4, INPUT_PULLUP);
  pinMode(2, INPUT_PULLUP);
  Serial.begin(9600);
  digitalWrite(b, HIGH);
  digitalWrite(d, HIGH);
  delay(2000);
  digitalWrite(b, LOW);
  digitalWrite(d, LOW);
  delay(1000);
  Serial.println("press the foot swtich"); // Serial Monitor for Debugging
}

void loop() {
  int Val = digitalRead(5); //   Actuator 1 Clamping
  int ValR = digitalRead(6);//   Actuator 2 Clamping
  int ValS = digitalRead(4);//Stepper Motor anticlockwise
  int ValM = digitalRead(2);//Stepper Motor Clockwise
  if (Val == LOW && x == 0  ) {
    Serial.print("Val000=");
    Serial.println(Val);
    digitalWrite(c, HIGH);
    delay(1750);
    digitalWrite(c, LOW);
    x = 1;
    Val = digitalRead(5);
    Serial.println("fwd");
    Serial.print("Val=");
    Serial.println(Val);
    delay(500);
  }
  if (Val == LOW && x == 1  ) {
    digitalWrite(d, HIGH);
    digitalWrite(b, HIGH);
    delay(2000);
    digitalWrite(d, LOW);
    digitalWrite(b, LOW);
    x = 0;
    Val = digitalRead(5);
    Serial.println("fwd");
    y = 0;
    Serial.print("Val=");
    Serial.println(Val);
    delay(500);
  }
  if (ValR == LOW && y == 0 ) {
    digitalWrite(a, HIGH);
    delay(1350);
    digitalWrite(a, LOW);
    y = 1;
    ValR = digitalRead(6);
    Serial.println("fwd");
    Serial.print("Val=");
    Serial.println(Val);
    delay(500);
  }
  if (ValR == LOW && y == 1 ) {
    digitalWrite(b, HIGH);
    delay(1200);
    digitalWrite(b, LOW);
    y = 0;
    ValR = digitalRead(6);
    Serial.println("fwd");
    Serial.print("Val=");
    Serial.println(Val);
    delay(500);
  }
  if (ValS == HIGH) {
    Serial.println(Val);
    Serial.println("up");
    digitalWrite(dirPin, HIGH);
    // Enables the motor to move in a particular direction
    // Makes 100 pulses for making half cycle rotation
    for (int x = 0; x < 100; x++) {
      digitalWrite(stepPin, HIGH);
      delayMicroseconds(1000);
      digitalWrite(stepPin, LOW);
      delayMicroseconds(1000);
    }
    // Enables the motor to move in a particular direction
    // Makes 200 pulses for making one full cycle rotation
  }
  if (ValM == LOW) {
    Serial.println("down");
    Serial.println(ValR);
    digitalWrite(dirPin, LOW);
    // Enables the motor to move in a particular direction
    // Makes 200 pulses for making one full cycle rotation
    for (int x = 0; x < 100; x++) {
      digitalWrite(stepPin, HIGH);
      delayMicroseconds(1000);
      digitalWrite(stepPin, LOW);
      delayMicroseconds(1000);
    }
    // Enables the motor to move in a particular direction
    // Makes 200 pulses for making one full cycle rotation
  }
}

Trying to write a proper answer...

According to your description, it looks like you are victim of inductive
noise pickup. The circuit [MCU → Arduino ground pin → foot pedal →
Arduino digital input pin → MCU] is a loop that can pick up magnetic
flux. If this flux varies, either because the magnetic field varies
(ambient electromagnetic noise) or because the geometry of the circuit
changes (you move the wires), this will induce an electromagnetic force
that can make your Arduino read LOW even when the button is not
pressed.

There are two things you can try to overcome this effect:

Replace the weak internal pullup of the Arduino by a much stronger
external pullup. Something around 1 kΩ should make it quite hard for
the noise to pull the signal low.
Connect the pedal to the Arduino board using a twisted pair of wires,
like the ones found in telephone or network cables. This kind of
cable does a good job at minimizing inductive pickup.


Explain what is meant by "Arduino core" What is an "Arduino core"?

Are there many different "Arduino cores"? such as a core that applies to LCD
displays, another core that applies to servos, etc.?

The Core is the software API for a specific group of chips.

For instance, the AVR core supports the AVR chips found on most Arduino boards. The SAM3X core supports the Arduino Due. Etc.

It is the code that provides things like digitalRead(), analogWrite(), millis() etc.

Since each family of chips works differently that abstraction layer between your sketch and the physical hardware of the chip needs to be different.

In your default IDE installation the Arduino AVR core can be found within the hardware/arduino/avr/cores/arduino folder.

Cores are usually installed as part of a "boards" bundle in the boards manager. This includes definitions for the boards ("variants"), the core and, equally importantly, the compiler and firmware uploading software for the chip on the board.


Connecting 12V WS2811 RGB LEDs to Arduino Uno & 5V Power Source (Breadboard needed?) I have an Arduino Uno, 12V WS2811 RGB LEDs (from Mokungit), a 5V power source, and DC power connector. I do not have a breadboard and hope I don't need one.

This is almost exactly what I need to follow this tutorial to build a Stranger Things wall. The LED strip listed shares the same name as the one I have, but the wiring is different.

Here's a photo from the Instructables site:

However, the wires coming from my strip don't match up to the instructions, and I can't seem to figure out how to get these bad boys burning.

Thanks to anyone who can help me get started!

This image, from here, shows which pins are what:

Note the flat key next to the 12 V and GND pins. In addition:

the GND wire has a black broken line printed along it;
the data line is in the middle.

If you trust the image then you should be able to wire them up correctly.


ESP8266 upload data to google cloud platform I am trying to upload information to my appspot created with Google App Engine. I am able to do it when I in my browser type:
http://myname.appspot.com/query?city=Copenhagen&temp=20&id=website
But I cannot get it to work on the ESP8266. Here is my code:

const char* MY_URL = "http://myname.appspot.com";

void uploadHTTP() {
    // Define the WiFi Client
    WiFiClient client;
    // Set the http Port
    const int httpPort = 80;

    // Make sure we can connect
    if (!client.connect(MY_URL, httpPort)) {
        return;
    }
    else {
        Serial.println("Connected to MY_URL");
    }

    String url = "/query?city=Copenhagen&temp=20&id=ESP8266";

    // Post to appspot
    if (client.connect(MY_URL, httpPort)) {

        // Sent HTTP POST Request
        client.println("POST " + url + " HTTP/1.1");
        Serial.println("POST " + url + " HTTP/1.1");
        client.println("Host: " + String(MY_URL));
        Serial.println("Host: " + String(MY_URL));
        client.println("User-Agent: Arduino/1.0");
        Serial.println("User-Agent: Arduino/1.0");
        client.print("Content-Length: ");
        Serial.print("Content-Length: ");
        client.println(0);
        Serial.println(0);
        client.println("Content-Type: application/x-www-form-urlencoded");
        Serial.println("Content-Type: application/x-www-form-urlencoded");
        client.println("Connection: close");
        Serial.println("Connection: close");
        }
    //Done
    Serial.println("");
    Serial.println("my HTTP done");
    Serial.println("");
}

Your biggest problem is that you are trying to use a website URL as a FQDN. That's not going to work.

When you connect to a remote machine you connect to the name (myname.appspot.com) which gets translated into an IP address for you to open a connection to.

When you use a web browser it parses the URL to extract the protocol (http) and the FQDN (myname.appspot.com) and uses the protocol to determine the port (and what language to speak) to connect to, then look up the IP address from the FQDN.

You need to drop the http:// from your FQDN which is causing it to break (there is no host called http://myname.appspot.com).  The fact that you are connecting to port 80 and speaking the HTTP language implies that you are using HTTP.

To put it into more layman's terms: if you "need to call Fred to talk about going to the pub" you first look up fred's number in the phone book then call that number. Then only once he has answered do you talk about going to the pub. What you don't do is try and find the number to call by looking in the phone book under "talk about going to the pub with Fred". It won't be there.

If you are programming your ESP8266 directly you should consider using the much simpler bundled ESP8266HTTPClient.h library.


What does a tilde (~) mean as annotation for a data pin? When I examine the datasheet for the Arduino Micro (couldn't find the Pro Micro on their site, btw) then I see some data pins annotated with a ~ character, and some are not.

For instance, D9 has a ~ annotation, D8 does not.

What does this annotation mean?

It means the pin can be a PWM output for use with analogWrite().


How do I properly convert a pointer (uint8_t* or void*) to a "normal" integer? I'm writing a program for arduino that needs dynamic memory allocation frequently, but as I don't want the memory to get fragmented, I'm also writing a "memory handler" for it. This memory handler would need to do calculations involving both pointers and size_t variables, like this (example code is not part of program, but the structure of the calculations is the same):

size_t freeMemSize = nextPointer - currentPointer - currentSize;

Which would calculate the size of free memory between two reserved spaces.

Of course, arduino doesn't want to swallow this code, as it compares incompatible types. My questions are:

Is a cast to the correct integer type enough to solve the problem?
If it is, what is the "normal integer" counterpart of a pointer?

I guess this varies from processor to processor, so I should look for something like size_t, but for memory indices instead of sizes.

Board: Uno, Nano
IDE version: 1.8.2

Assume the following declarations:

uint8_t* nextPointer;
uint8_t* currentPointer;
size_t currentSize;

Then the expression is valid:

size_t freeMemSize = nextPointer - currentPointer - currentSize;

If any of the pointers are void* the compiler cannot calculate the expression (pointer or size).

Cheers!


Simple network protocol to communicate between N slave arduino and 1 central arduino? i am looking to communicate text ( 40 char for each message ) between N arduino and a central one ( Communication is one way slaves to Master).I am looking for wire communication with 1 to 5 m distance.Does anyone know the best approach to do that ?

Vincent

You have quite a few options available to you as your requirements are filled by quite a few protocols, I am not going to list all. You can use things such as I2C, CAN, RS-485, RS-232.

You can find a few good examples from this EE.SE post from a search.

The CAN option is quite a good one for your application and is easy to set up and there are quite a few libraries available for the common chip MCP2525 and MCP2551. Yo can also get a 'shield' with this functionality from sparkfun.

The other options are discussed in the linked EE.SE post with regards to RS-485.

I2C can be implemented with the Wire library of arduinos and other libraries.

You can use RS-232, but I don't think it will be immune to noise at the distance you want, but you can still try. What you can do is use a multiplexer, such as this one CD74HC4067, and use it to multiplex the TX line from each node to the RX of the master.

From SFE's site:

  For example, you could use it to connect the TX pins of 16 devices to one RX pin on your microcontroller. You can then select any one of those 16 devices to listen to. If you want two-way communications, you can add a second board to route your microcontroller’s TX line to 16 device’s RX lines. By using multiple boards, you can create similar arrangements for I2C, SPI, etc.

You will probably want to add some sort of checksum/CRC to the data you send over the network too.


Overriding main function in Leonardo I've trying to write my code in plain C++ dropping out the Arduino's IDE. Although I've succeed in compiling the code, whenever I try to upload it to the board it doesn't run, seems that it stucks at some unknown point.

After that, everytime I try to upload a new code to the board it stops responding and avrdude throws this message:

$ ino upload -m leonardo -p /dev/ttyACM1
/dev/ttyACM1 doesn't exist. Is Arduino connected?

It doesn't matter if I unplug and then plug again the board, that message is still showing up.

In order to restart the board, I open the Arduino IDE and then I upload any sketch, then the board comes to live again.

The first time I tried overriding the main() function and the program didn't run I thought it was the tool I was using at that moment, arduino.mk, the one that was doing something strange.

Then I tried the ino tool, but the result was the same.

I don't think avrdude is failing because it actually uploads the .hex to the board.

My original main() code was:

#include <Arduino.h>

const int LED_PIN = 13;

int main(void)
{
    pinMode(LED_PIN, OUTPUT);

    while (1)
    {
        digitalWrite(LED_PIN, HIGH);
        delay(100);
        digitalWrite(LED_PIN, LOW);
        delay(900);
    }
    return 0;
}

Then I tried to mimic the one that comes with Arduino:

#include <Arduino.h>

const int LED_PIN = 13;

int main(void)
{
    pinMode(LED_PIN, OUTPUT);

#if defined (USBCON)
    USBDevice.attach();
#endif

    while (1)
    {
        digitalWrite(LED_PIN, HIGH);
        delay(100);
        digitalWrite(LED_PIN, LOW);
        delay(900);

        if (serialEventRun) serialEventRun();
    }
    return 0;
}

Sadly, with both codes the board gets stucked at some point.

While I figure out how to solve this issue I've been exercising this solution inside a sketch:

const int LED_PIN = 13;

void setup() {
}

void loop() {
    pinMode(LED_PIN, OUTPUT);

    while (1)
    {
        digitalWrite(LED_PIN, HIGH);
        delay(100);
        digitalWrite(LED_PIN, LOW);
        delay(900);
    }
}

Any ideas that led me to a solution? Thank you!

Solved!

It was a (big) silly mistake of my own. I overloocked the init() function right after entering the main() function. I'm shure it initializes the hardware and the entire system, so my board stucks when I skipped it.

So my code now looks like this:

#include <Arduino.h>

const int LED_PIN = 13;

int main(void)
{
    init();

#if defined (USBCON)
    USBDevice.attach();
#endif

    pinMode(LED_PIN, OUTPUT);

    while (1)
    {

        digitalWrite(LED_PIN, HIGH);
        delay(100);
        digitalWrite(LED_PIN, LOW);
        delay(900);

        if (serialEventRun) serialEventRun();
    }

    return 0;
}

BTW, the mix: Arduino + Vim + ino, rocks! Now I can do whatever I want from the console :)


How to measure electrical conductivity using Arduino? I want to measure TSS(Total soluble salt) in soil. I have found in some literature that, through measuring of electrical conductivity, it is much easier to measure TSS. So, I thought, If I can measure electrical conductivity, it might be possible to find out TSS. (Logic behind the TSS is that, pure water is poor conductor of electric, increasing of soluble salt in water proportionately lift up the conductivity). So are there any sensor that readily measure conductivity. A point I also want to mention, can a voltmeter be useful for that.

The answer is Three Dollar EC - PPM Meter [Arduino]. I tried it against a consumer level EC meter and got the same results after calibration. It's cheap and simple.

The only warning is that there is several scales in use to measure EC, so results may not be comparable between diferentes devices and you have to read carefully the EC recomendations for your water solution.

EC units

Electrical conductivity can be expressed using a number of different units, but the typical unit is siemens per meter2 per mole (S/m2/mole) or millisiemens per centimetre (mS/cm). The mS/cm unit is generally used in Europe as a guide to the concentration of nutrients in water. In North America, conductivity is converted into a count of the ions in the water using parts per million (which can also be converted into units including mg/l etc.). This is done by converting the EC into a value based on the ions contained in the solution. Fortunately, there is a fixed calculation for the relationship between all these units, which is given in the table below.

Code for the EC meter

/*
  ElCheapo Arduino EC-PPM measurments

  This scrip uses a common USA two prong plug and a 47Kohm Resistor to measure the EC/PPM of a Aquaponics/Hydroponics Sytem.
  You could modift this code to Measure other liquids if you change the resitor and values at the top of the code.

  This Program will give you a temperature based feed controller. See Read me in download file for more info.

  28/8/2015  Michael Ratcliffe  Mike@MichaelRatcliffe.com

          This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see .

    Parts:
    -Arduino - Uno/Mega
    -Standard American two prong plug
    -1 kohm resistor
    -DS18B20 Waterproof Temperature Sensor

    Limitations:
    -
    -

    See www.MichaelRatcliffe.com/Projects for a Pinout and user guide or consult the Zip you got this code from

*/

#include <OneWire.h>
#include <DallasTemperature.h>

//************************* User Defined Variables ********************************************************//

int R1= 1000;
int Ra=25;          //Resistance of powering Pins
int ECPin= A0;
int ECGround=A1;
int ECPower =A4;

//*********** Converting to ppm [Learn to use EC it is much better**************//
// Hana      [USA]        PPMconverion:   0.5
// Eutech    [EU]         PPMconversion:  0.64
// Tranchen  [Australia]  PPMconversion:  0.7
// Why didnt anyone standardise this?

float PPMconversion=0.5;

//*************Compensating for temperature ************************************//
// The value below will change depending on what chemical solution we are measuring
// 0.019 is generaly considered the standard for plant nutrients [google "Temperature compensation EC" for more info
float TemperatureCoef = 0.019; //this changes depending on what chemical we are measuring

//********************** Cell Constant For Ec Measurements *********************//
// Mine was around 2.9 with plugs being a standard size they should all be around the same
// But If you get bad readings you can use the calibration script and fluid to get a better estimate for K
float K=2.34;

//************ Temp Probe Related *********************************************//
#define ONE_WIRE_BUS 10          // Data wire For Temp Probe is plugged into pin 10 on the Arduino
const int TempProbePossitive =8;  //Temp Probe power connected to pin 9
const int TempProbeNegative=9;    //Temp Probe Negative connected to pin 8

//***************************** END Of Recomended User Inputs *****************************************************************//

OneWire oneWire(ONE_WIRE_BUS);// Setup a oneWire instance to communicate with any OneWire devices
DallasTemperature sensors(&oneWire);// Pass our oneWire reference to Dallas Temperature.

float Temperature=10;
float EC=0;
float EC25 =0;
int   ppm =0;

float raw= 0;
float Vin= 5;
float Vdrop= 0;
float Rc= 0;
float buffer=0;

//*********************************Setup - runs Once and sets pins etc ******************************************************//
void setup()
{
    Serial.begin(9600);
    pinMode(TempProbeNegative , OUTPUT);  //seting ground pin as output for tmp probe
    digitalWrite(TempProbeNegative , LOW); //Seting it to ground so it can sink current
    pinMode(TempProbePossitive , OUTPUT); //ditto but for positive
    digitalWrite(TempProbePossitive , HIGH);
    pinMode(ECPin,INPUT);
    pinMode(ECPower,OUTPUT);//Setting pin for sourcing current
    pinMode(ECGround,OUTPUT);//setting pin for sinking current
    digitalWrite(ECGround,LOW);//We can leave the ground connected permanantly

    delay(100);// gives sensor time to settle
    sensors.begin();
    delay(100);
    //** Adding Digital Pin Resistance to [25 ohm] to the static Resistor *********//
    // Consule Read-Me for Why, or just accept it as true
    R1=(R1+Ra);// Taking into acount Powering Pin Resitance

    Serial.println("ElCheapo Arduino EC-PPM measurments");
    Serial.println("By: Michael Ratcliffe  Mike@MichaelRatcliffe.com");
    Serial.println("Free software: you can redistribute it and/or modify it under GNU ");
    Serial.println("");
    Serial.println("Make sure Probe and Temp Sensor are in Solution and solution is well mixed");
    Serial.println("");
    Serial.println("Measurements at 5's Second intervals [Dont read Ec morre than once every 5 seconds]:");
}

void loop()
{
    GetEC();          //Calls Code to Go into GetEC() Loop [Below Main Loop] dont call this more that 1/5 hhz [once every five seconds] or you will polarise the water
    PrintReadings();  // Cals Print routine [below main loop]
    delay(5000);
}

void GetEC()
{
    sensors.requestTemperatures();          // Send the command to get temperatures
    Temperature=sensors.getTempCByIndex(0); //Stores Value in Variable
    //************Estimates Resistance of Liquid ****************//
    digitalWrite(ECPower,HIGH);
    raw= analogRead(ECPin);
    raw= analogRead(ECPin);// This is not a mistake, First reading will be low beause if charged a capacitor
    digitalWrite(ECPower,LOW);

    //***************** Converts to EC **************************//
    Vdrop= (Vin*raw) / 1024.0;
    Rc = (Vdrop*R1) / (Vin-Vdrop);
    Rc = Rc-Ra; //acounting for Digital Pin Resitance
    EC = 1000/ (Rc*K);

    //*************Compensating For Temperaure********************//
    EC25  =  EC / (1+ TemperatureCoef*(Temperature-25.0));
    ppm=(EC25)*(PPMconversion*1000);
}

//***This Loop Is called From Main Loop- Prints to serial usefull info ***//
void PrintReadings()
{
    Serial.print("Rc: ");
    Serial.print(Rc);
    Serial.print(" EC: ");
    Serial.print(EC25);
    Serial.print(" Simens  ");
    Serial.print(ppm);
    Serial.print(" ppm  ");
    Serial.print(Temperature);
    Serial.println(" *C ");
};

Code for calibration

/*
  ElCheapo Arduino EC-PPM measurments Calibration

  This Script is used for calibration of the sensor and fine tuning of the Cell Constant K
  Submerge the sensor and temperature probe in the calibration solution and leave for a while so the temperature probe can settle
  Change the value of the calibration solution to suit the solutiton strength
  Stir the probe to make sure the solution is well mixed and upload the code to the arduino
  Open the terminal for an update of the estimated Cell Constant K [should be around 3] and use this new value in the main EC code.

  28/8/2015  Michael Ratcliffe  Mike@MichaelRatcliffe.com

          This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see .

    Parts:
    -Arduino - Uno/Mega
    -Standard American two prong plug
    -1 kohm resistor
    -DS18B20 Waterproof Temperature Sensor

    See www.MichaelRatcliffe.com/Projects for a Pinout and user guide or consult the Zip you got this code from

*/

//************************** Libraries Needed To Compile The Script [See Read me In Download] ***************//
// Both below Library are custom ones [ SEE READ ME In Downloaded Zip If You Dont Know how To install Use them or add a pull up resistor to the temp probe

#include <OneWire.h>
#include <DallasTemperature.h>

//************************* User Defined Variables ********************************************************//

float CalibrationEC = 0.762; //EC value of Calibration solution is s/cm

//##################################################################################
//-----------  Do not Replace R1 with a resistor lower than 300 ohms    ------------
//##################################################################################
int R1 = 1000;
int Ra = 25; //Resistance of powering Pins
int ECPin = A0;
int ECGround = A1;
int ECPower = A4;

//*************Compensating for temperature ************************************//
//The value below will change depending on what chemical solution we are measuring
//0.019 is generaly considered the standard for plant nutrients [google "Temperature compensation EC" for more info
float TemperatureCoef = 0.019; //this changes depending on what chemical we are measuring

//************ Temp Probe Related *********************************************//
#define ONE_WIRE_BUS 10          // Data wire For Temp Probe is plugged into pin 10 on the Arduino
const int TempProbePossitive = 8; //Temp Probe power connected to pin 9
const int TempProbeNegative = 9;  //Temp Probe Negative connected to pin 8

//***************************** END Of Recomended User Inputs *****************************************************************//

OneWire oneWire(ONE_WIRE_BUS);// Setup a oneWire instance to communicate with any OneWire devices
DallasTemperature sensors(&oneWire);// Pass our oneWire reference to Dallas Temperature.

float TemperatureFinish = 0;
float TemperatureStart = 0;
float EC = 0;
int ppm = 0;

float raw = 0;
float Vin = 5;
float Vdrop = 0;
float Rc = 0;
float K = 0;
int i = 0;
float buffer = 0;

//*********************************Setup - runs Once and sets pins etc ******************************************************//
void setup()
{
    Serial.begin(9600);
    pinMode(TempProbeNegative , OUTPUT);  //seting ground pin as output for tmp probe
    digitalWrite(TempProbeNegative , LOW); //Seting it to ground so it can sink current
    pinMode(TempProbePossitive , OUTPUT); //ditto but for positive
    digitalWrite(TempProbePossitive , HIGH);
    pinMode(ECPin, INPUT);
    pinMode(ECPower, OUTPUT); //Setting pin for sourcing current
    pinMode(ECGround, OUTPUT); //setting pin for sinking current
    digitalWrite(ECGround, LOW); //We can leave the ground connected permanantly

    delay(100);// gives sensor time to settle
    sensors.begin();
    delay(100);
    //** Adding Digital Pin Resistance to [25 ohm] to the static Resistor *********//
    // Consule Read-Me for Why, or just accept it as true
    R1 = (R1 + Ra);

    Serial.println("ElCheapo Arduino EC-PPM measurments Calibration");
    Serial.println("By: Michael Ratcliffe  Mike@MichaelRatcliffe.com");
    Serial.println("Free software: you can redistribute it and/or modify it under GNU ");
    Serial.println("");
    Serial.println("Make sure Probe and Temp Sensor are in Solution and solution is well mixed");
    Serial.println("");
    Serial.println("Starting Calibration: Estimated Time 60 Seconds:");
};
//******************************************* End of Setup
//************************************* Main Loop - Runs Forever ***************************************************************//
//Moved Heavy Work To subroutines so you can call them from main loop without cluttering the main loop
void loop()
{
    i = 1;
    buffer = 0;
    sensors.requestTemperatures();// Send the command to get temperatures
    TemperatureStart = sensors.getTempCByIndex(0); //Stores Value in Variable

    //************Estimates Resistance of Liquid ****************//
    while(i <= 10) {
        digitalWrite(ECPower, HIGH);
        raw = analogRead(ECPin);
        raw = analogRead(ECPin); // This is not a mistake, First reading will be low
        digitalWrite(ECPower, LOW);
        buffer = buffer + raw;
        i++;
        delay(5000);
    };

    raw = (buffer / 10);

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

    TemperatureFinish = sensors.getTempCByIndex(0); //Stores Value in Variable

    //*************Compensating For Temperaure********************//
    EC = CalibrationEC * (1 + (TemperatureCoef * (TemperatureFinish - 25.0))) ;

    //***************** Calculates R relating to Calibration fluid **************************//
    Vdrop = (((Vin) * (raw)) / 1024.0);

    Rc = (Vdrop * R1) / (Vin - Vdrop);

    Rc = Rc - Ra;

    K = 1000 / (Rc * EC);

    Serial.print("Calibration Fluid EC: ");

    Serial.print(CalibrationEC);

    Serial.print(" S  ");  //add units here

    Serial.print("Cell Constant K");

    Serial.print(K);

    if(TemperatureStart == TemperatureFinish) {
        Serial.println("  Results are Trustworthy");
        Serial.println("  Safe To Use Above Cell Constant in Main EC code");

    } else {
        Serial.println("  Error -Wait For Temperature To settle");
        Serial.print("Temp start=");
        Serial.print(TemperatureStart);
        Serial.print(" Temp end=");
        Serial.println(TemperatureFinish);
    }
}
//*************************** End Of Main Loop *******************************************************************//

EDIT:

Make sure to use a factory sealed male plug. If water get inside the plug, the voltage reading will be inaccurate.


Which libraries for DS1302 real time clock and WS2811 LED strip do not conflict? I am making a custom wall-clock, and need the Arduino (Uno or Nano) to connect to a DS1302 real time clock module and a WS2811 LED chain.

So I’m using DS1302 for the clock, and FastLED for the lights. Individually these two libraries work fine, so I can either echo the time to the serial console, or I can drive the LEDs as I need.

But when I combine them there is some conflict happening and I get no LED output. The LED data goes over pin 6 and the clock uses pins 2,3,4 (these pins are customisable in code).

Even just adding a DS1302 initialisation to a working FastLED sketch causes no more LED output

#include <FastLED.h>
#include <DS1302.h>

#define NUM_LEDS 50
#define DATA_PIN 6

// Init the DS1302 - stops LEDs working
DS1302 rtc(2, 3, 4);

CRGB leds[NUM_LEDS];

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

void loop() {
  for (int i=0; i<NUM_LEDS;i++) {
    leds[i] = CRGB::Red;
  }
  FastLED.show();
  delay(100);
}

What are my troubleshooting steps - should I try alternative libraries, or could I dig into the libraries themselves and see what hardware resources they might be using?

I guess as both the lights and the clock probably operate over a serial protocol, it could be a conflict with the serial drivers - maybe both using the same time-critical operations.

Edit: inserted sketch which demonstrates the issue

I installed a library from within the IDE as StarCat suggested.

https://github.com/Makuna/Rtc

#include <FastLED.h>
#include <ThreeWire.h>
#include <RtcDS1302.h>

#define NUM_LEDS 50
#define DATA_PIN 6

ThreeWire myWire(3,4,2); // IO, SCLK, CE
RtcDS1302<ThreeWire> Rtc(myWire);

CRGB leds[NUM_LEDS];

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

void loop() {
   RtcDateTime dt = Rtc.GetDateTime();

   for (int i=0; i<NUM_LEDS;i++) {
     leds[i] = CRGB::Red;
   }

FastLED.show();
delay(100);
}

I am able to get and use the time, and the LED output works.


Read time digits from DS1307 and run code based on return I am currently reading a DS1307 adafruit breakout board and I need to drive two nixie tubes from a shift register. The shift register is running two 74141 IC chips. I have code that loops through all the nixie digits one at a time with a delay of 1 second between each. Now I need to write some code to pull min, hour, and second and change the shift register low/high outputs to display the correct nixie digit. I have the DS1307 returning the correct time on my com by using

 Serial.print(now.hour(), DEC);
 Serial.print(now.minute(), DEC);
 Serial.print(now.second(), DEC);

However, I am not sure how to dimension a string, set that string equal to the two digits on the hour, minute, or time, and then divide the two digits and write if statements to correctly display the tubes. I am used to VB.NET and now C coding.

=======================UPDATE=======================

I am using this code to set any individual digit of the nixie tube to on.

       //Turn on 0
 sr.set(4, LOW);
 sr.set(5, LOW);
 sr.set(6, LOW);
 sr.set(7, LOW);

The sr is the shift register and each number is which leg of the shift register I am turning low or high. This specific piece turns on the digit 0.

You can set up an array containing the bit patterns to turn on different digits, and then use code that sends the bits for the high digit of now.hour()/12 and the bits for the low digit of now.hour()%12.  For example:

const byte digiBits[] = { B0000, B0001,
// and so forth for all the digits ...
};

void send1Digit(byte digiVal, byte whichDigit) {
  // somehow use whichDigit to direct the bits someplace...

  // To send the bits:
  byte bits = digiBits[digiVal];
  for (byte i=4; i<8; ++i) {
    sr.set(i, bits & 1);  // Set a bit in SR to 0 or 1
    bits >>= 1; // shift out the used bit
  }
}

void send2Digits(byte numVal, byte whichDigit) {
  send1Digit(numVal/10, whichDigit);
  send1Digit(numVal%10, whichDigit+1);
}

void loop() {
  // other stuff, then:
  send2Digits(now.hour(), HourSpot);
  send2Digits(now.minute(), MinuteSpot);
  send2Digits(now.second(), SecondSpot);
  // other stuff ...
}

Note 1:  If your sr.set() routine is doing any complicated masking or shifting, you may be able to avoid some of that by ORing digiBits[digiVal] with whatever number sr.set() might be building up to shift out.

Note 2:  If the numerical value of digiBits[digiVal] is equal to digiVal, then don't bother defining digiBits[], but instead in send1Digit() just say byte bits = digiVal, or use digiVal directly in place of bits.


Is there a microcontroller that can output hdmi? Pretty simple question. Is there a microcontroller that can output hdmi? If not, what microcontrollers can output any type of video?

It depends on what you are looking for. There are lots o chips made to control and process hdmi frames. However, as Jot said, the arduino is not suitable for this. The arduino can output basic VGA, but it does not have enough "horsepower" to play with HDMI. The best and cheapest solution is to use a Raspberry Pi.


Multiple node communication using NRF24L01 Code for detecting data available at which pipe when using multiple pipe for communication??

// check if there is data ready
    uint8_t pipeNr;
    if ( radio.available(&pipeNr) )
    {
        Serial.print("Pipe: ");
        Serial.println(pipeNr);
    }


Unable to compare two integer values in Arduino Mega I wrote Arduino code (code is given at the end) to compare two integer values. The steps I took was:

Give input to DC motor to rotate it using serial port. Input was: G254
Then I store it in XX string and using XX.remove(0,1); I removed G from G254. XX now become 254
Then I used Serial1.println("P"); to get position of motor after rotation. I stored this value in ZZ string using String  ZZ = Serial1.readString();. ZZ will be P254.
And using XX.remove(0,1); I removed P from P254. ZZ now become 254.
Now, I convert both XX and ZZ into integer from string using  XX.toInt(); ZZ.toInt(); .
After that, I compare both values using:

if (XX == ZZ)
{
    Serial.println("BOTH ARE EQUAL");
}
else
{
    Serial.println("BOTH ARE NOT EQUAL");
}

But it shows BOTH ARE NOT EQUAL which is not true. I want to know where I'm making a mistake?

Code I used:

void setup() {
    // put your setup code here, to run once:
    Serial.begin(9600);
    Serial1.begin(9600);

    pinMode(13, OUTPUT);
}

void loop() {
    // put your main code here, to run repeatedly:
    if (Serial.available() > 0)
    {
        Serial1.println(Serial.readString());

        String  XX = Serial1.readString();
        XX.remove(0,1);

        Serial1.println("P");

        String  ZZ = Serial1.readString();
        ZZ.remove(0,1);

        XX.toInt();
        ZZ.toInt();
        Serial.println(ZZ);
        Serial.println(XX);
        Serial.println(typeof(XX));

        if (XX == ZZ)
        {
            Serial.println("BOTH ARE EQUAL");
        }
        else
        {
             Serial.println("BOTH ARE NOT EQUAL");
        }
    }
}

Thanks.

You should use

 int x = XX.toInt()

Without the int x = part, the string is converted and the result (the integer) is not used.

Also comparing strings should be done with the strcmp function. The problem is that if you compare two strings, you compare the pointers to those strings and two strings can have equal texts but (probably) not equal addresses.


creating table in 24LC256 here i am doing some project with the help of Arduino UNO with External EEPROM (24LC256),
 All i want to create table and wants to  store all  data into  24LC256 External EEPROM,there are many library for internal EEPROM to create table with limited data as per size of arduino EEPROM but i have huge data to store so have to use External eeprom to do, so  i can't find any proper library for doing that.!

can anyone tell me how to do that...

any suggestion..Please help me..

thanking you..

Simplest way to create a table is to view it as a vector of struct's. For performance it is good to make the struct size a multiple of the EEPROM page size.

struct row_t {
  ... column fields ...
};

uint32_t row_addr = TABLE_START_ADDR;
row_t data;
data.column = value;
...

eeprom.write(row_addr, &data, sizeof(data));
row_addr += sizeof(row_t);
...

Basically you need to map a two/multiple dimensional table onto a one dimensional address space (of the EEPROM). The programming language can help with some of the calculations (and hide them).

Cheers!


Vcc measurement with internal 1.1V reference fails on 3.3V powered Atmega328 I need to monitor a battery plugged to an ATmega running on standalone mode.

I use the "ATmega on a breadboard (8 MHz internal clock)" bootloader.
More info here

When the ATmega is powered with 5V the sketch outputs good values : arround 5100 mV.

But when I power it with 3.3V the sketch gives strange values : arround 178619 mV.

Here is my code Inspired from here

void setup()
{
  Serial.begin(9600);
  Serial.println(F("Internal Voltage Sensor"));
}

void loop()
{
  Serial.println( readVcc());
  delay(1000);
}

long readVcc()
{
  long voltage=0;
  uint8_t wADC;

  // Read 1.1V reference against AVcc
  // set the reference to Vcc and the measurement to the internal 1.1V reference
  ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
  ADCSRA |= _BV(ADEN);  // enable the ADC

  delay(20); // Wait for Vref to settle

  ADCSRA |= _BV(ADSC); // Start conversion
  while (bit_is_set(ADCSRA,ADSC)); // measuring

  // Reading register "ADCW" takes care of how to read ADCL first and ADCH then.
  wADC = ADCW;

  voltage = 11253000L / wADC; // Calculate Vcc (in mV); 1125.3 = 1.1*1023*1000
  return voltage; // Vcc in millivolts
}

I don't understand what's going on. The returned value with Vcc=3.3V should be lower than with VCC=5V. Something like 3300 mV !

Thanks for your answers!
Jot gave the solution: wADC must be a uint16_t.

Here is the corrected code :

void setup()
{
  Serial.begin(9600);
  Serial.println(F("Internal Voltage Sensor"));
}

void loop()
{
  Serial.println(readVcc());
  delay(1000);
}

long readVcc()
{
  long voltage=0;
  uint16_t wADC;

  // Read 1.1V reference against AVcc
  // set the reference to Vcc and the measurement to the internal 1.1V reference
  ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
  ADCSRA |= _BV(ADEN);  // enable the ADC

  delay(20); // Wait for Vref to settle

  ADCSRA |= _BV(ADSC); // Start conversion
  while (bit_is_set(ADCSRA,ADSC)); // measuring

  // Reading register "ADCW" takes care of how to read ADCL first and ADCH then.
  wADC = ADCW;

  voltage = 1125300L / wADC; // Calculate Vcc (in mV); 1125300 = 1.1*1023*1000
  return voltage; // Vcc in millivolts
}


Arduino Due and Vin, 3.3V and 5V power inputs I just want to confirm something before I wire up my first ever Arduino project and fry all the stuff I just spent money on.

It is my understanding that the Vin power input will tolerate a 9V battery and use voltage regulators to pare it down to either 3.3V or 5V (as different parts of the board require). So it is then my assumption that if I have a 9V battery running to Vin, that I could then connect a power wire to the 3.3V connector, and reliably get a 3.3V signal (and ditto for 5V), yes?

Or, is it that they are input jacks expecting either 3.3V or 5V signals? I guess I'm confused over this:

Will Vin then power the 3.3V and 5V inputs, giving me access to voltage at that level; or
Do I have to choose between 3.3V, 5V or Vin, and only use one of those to power my board (with the appropriate voltage level)

DC Jack is connected, through a diode, to Vin.

Vin is stepped down to 5V on-board.

5V is stepped down to 3V3 on board.

Thus you can do any one of the following numbered items.

Connect a 7-12V supply to the DC Jack; thus:

use Vin as a supply @ DC - 0.7V for off-board peripherals, and
use 5V as a supply for off-board peripherals, and
use 3V3 as a supply for off-board peripherals.

Connect a 6-12V supply to Vin; thus:

use 5V as a supply for off-board peripherals, and
use 3V3 as a supply for off-board peripherals.

Connect 5V supply to the 5V; thus:

use 3V3 as a supply for off-board peripherals.

The above is only guaranteed for boards that follow the reference schematic, as plenty of clone/compatible boards do. If you buy a cheap Chinarduino and something doesn't work, or the thing breaks, after following anything above then that's your tough luck.


Modbus RTU over TCPip I have developed my arduino code using below library. I tested code working fine over modbus RTU slave. Now i am planning to use RS485 to wifi instead of wire connection. In order to get data over web apllication i need to add another layer of modbus TCP-IP. can some one suggest me is it possible to without changing any hardware add library function which can acts like MODBUS RtU over TCP-IP protocol.

if any library avilable please share it
I am using WIFI device like below.
rs485 to wifi

MODBUS RTU

Modbus TCP simply put is a Modbus packet wrapped in a TCP packet.

There is no 'additional layer of Modbus' added on top. If we look at the osi model pictured below you can see there is only one Modbus application layer (i.e modbus slave/server)

Essentially if the wifi->RS485 gateway strips the payload from the TCP packets and simply spits it out the serial side then no modifications are necessary (apart from the obvious RS485 transceiver you will need to interface the arduino with the gateway).

What you will need to make sure is that the gateway will only send packets directed to port 502 to the arduino (502 is the Modbus TCP port) as it is possible other IP traffic could cause some drama for the modbus slave.

Additionally, you will have to ensure that you set the slave ID of the arduino to be what is specified by the master. Are you also building the Modbus TCP client? If not it is very possible that the required slave ID is 255 which is not supported by the modbus library you have linked.

Modbus (serial) slave IDs can only be between 1 and 247 for traditional reasons when Modbus was first standardised as it was only envisioned to be on serial, however when Modbus TCP was introduced an additional addressing layer (TCP / IP) meant that the unit ID (slave ID when using Modbus TCP) could be anything from 0 - 255. It is common for some vendors (at least in industrial automation) to use a unit ID of 255 for standard Modbus transactions scanning IO and diagnostic or configuration transactions to be send to other unit IDs (essentially making the TCP server a modbus router, forwarding packets to one of the multiple Modbus servers running on that single slave device)


Arduino Yun C++ environment? Bridge + Cross-Compiler I'm creating an XMPP chatbot for the Arduino Yun. However, I'm not too confident in the Python performance on such a low performance device and I'm much more comfortable with C++. Is there a C++ crosscompile environment available, and is there a port of the Bridge library to C++? Alternatively, documentation on how to interface with the ATMega using raw serial communication?

The Linux side of the Yun is just an OpenWRT installation. It has hardly been modified at all.

To cross-compile you will first need a Linux computer, or a Linux virtual machine.  Then you need to download the OpenWRT source code and configure it for the Yun (I think it defaults to the right settings).  Then you can build the whole OpenWRT image.  One side-effect of that is it compiles and configures a full cross-compiling environment for you.

You can then use that cross-compiling environment to compile your own code.


mcufriend SPI connection Bought a cheap LCD form china (mcufriend, pictured below) and I cant understand which pin is which to use it with the SPI interface (starting to get worried that I can't use it), I've figured out this much:

LCD_RST; reset pin
LCD_CS; chip select
LCD_RS;
LCD_WR;
LCD_RD;

Which of those is MOSI, SCK, DC? Trying to use it with a ESP8266 (ESP-12).

You can't use that TFT screen with SPI. The SPI interface (SD_DI, SD_DO, SC_SCK and SD_SS) is for the SD card slot only.

All the pins starting LCD_ are the 8-bit parallel ("8080" style) interface for controlling the TFT screen.


Arduino Nano PWM frequency I have been using an Arduino Nano as a PWM controller for a heating element.

I am currently using D11 (PB3). I could change, although all pins with PWM are in use, and would require a re-write and re-wire.

This produces a signal at ~490Hz, but I would like to experiment with changing this to a higher frequesncy.

I gather it its possible to vary the frequency by changing the divisor from its default 64.

My sketch uses Uses http://playground.arduino.cc/Main/SevenSegmentLibrary and calls millis() - will changing PWM divisor impact on either of these?

NOTE I have read the setPwmFrequency documentation, but find "disrupts the normal operation" unhelpful - I am actually after some explanation of the concrete effect. I only use millis() to time button presses and flash a LED, which are not time critical

Please keep in mind that changing the PWM frequency changes the Atmega's timers and disrupts the normal operation of many functions that rely on time (delay(), millis(), Servo library).

I have been doing some further study. http://playground.arduino.cc/Code/PwmFrequency states  Changes on pins 3, 5, 6, or 11 may cause the delay() and millis() functions to stop working.

Other references say 3, 11 use timer 2 so do they affect millis() or not as other references claim timer 0 is used for these.

Depends on the pin you used for the PWM.

Arduino UNO/NANO specs say following things:

The base frequency for pins 3, 9, 10, and 11 is 31250 Hz.

The base frequency for pins 5 and 6 is 62500 Hz.

The divisors available on pins 5, 6, 9 and 10 are: 1, 8, 64, 256, and 1024.

The divisors available on pins 3 and 11 are: 1, 8, 32, 64, 128, 256, and 1024.

PWM frequencies are tied together in pairs of pins. If one in a pair is changed, the other is also changed to match.

Pins 5 and 6 are paired on timer0.

Pins 9 and 10 are paired on timer1.

Pins 3 and 11 are paired on timer2.

Changes on pins 3, 5, 6, or 11 may cause the delay() and millis() functions to stop working. Other timing-related  functions may also be affected.


need to use jp2 because need extra pins i clearly understand jp2 is the extra leftover pins of atmega16u2 . but how to access it ? i find my arduino has less pins and jp2 are the only ones left . but if it is not accessable , why do they have it ?
and also , if it requires seperate programing of the atmega16u2 , i'd like to know how . i completely dunno a thing about atmega16u2 . only thing i understand is that it makes the arduino more compatible with the usb input ...
thanks alot !

if it requires seperate programing of the atmega16u2,

It does.  Often an ATMega8U2 is used here instead though.

i'd like to know how.

You might start by having a look at HoodLoader2 and NicoHood's related projects.
This involves replacing the normal Xu2 transceiver firmware with HoodLoader.  There are different ways to do that outlined in the installation instructions.  If you don't have an ISP programmer or a second Arduino to behave as one, there's a method that involved burning an installer-sketch to the 328P which turns around and reprograms the Xu2 chip.
Once you have that done you can use their board definitions for put sketches onto the ATMegaXU2 itself.
Apparently, JP2's layout is flipped on some boards. So, beware of that.  In any case, the header it makes the ATMegaXU2's PB4, PB4, PB6, and PB7 available.  Sketches on the XU2 would use the Hoodloader pin mapping of these:

Arduino Pin No.
AVR GPIO PIN

D4
PB4

D5
PB5

D6
PB6

D7
PB7

Or course, now you need to find some way to coordinate what happens on the ATMegaXU2 with the ATMega328P.

i find my arduino has less pins and jp2 are the only ones left.

There are clever ways to reuse pins on microcontrollers.  For example, it is possible to put an LED and a switch on the same GPIO pin.  And there are GPIO expanders, SPI/I2C ADCs, etc.
Messing with JP2 and programming the ATMegaXU2 and having it coordinate with the 328P may be more trouble than you like just to get a couple extra pins.

but if it is not accessable, why do they have it ?

Just added capability.  Usually that header is unpopulated, so there's no part cost there.

and also , i completely dunno a thing about atmega16u2 . only thing i understand is that it makes the arduino more compatible with the usb input ...

It serves the role of a USB to logic-level-serial converter for connecting to the USART of the otherwise non-USB-aware ATMega328P (you have tagged UNO).  But, it can be made to run sketches.  Usually if you're doing this, it's to get native USB support on an UNO (or Mega, or..), e.g. so you can have your board act as a keyboard, like you might with a Leonardo or Micro or any other board that has native-USB in normal use.  And that's a large part of what NicoHood's project is about.


GET the first result in HTTP request I have a String content="" and if I put an HTTP request like this:

client.println("GET /api/actions?parking_id=39 HTTP/1.1");
client.println("Host: ramp-rampcontrol.rhcloud.com");
client.println("Connection: close");
client.println();

the output I get is:

 [{"action_id":35,"action_type":"up","parking_id":39,"user_id":17,"ramp":"exit","created_at":"2015-07-10 18:02:40","updated_at":"2015-07-10 18:02:40"},{"action_id":41,"action_type":"up","parking_id":39,"user_id":17,"ramp":"entry","created_at":"2015-08-16 20:50:14","updated_at":"2015-08-16 20:50:14"},{"action_id":42,"action_type":"down","parking_id":39,"user_id":17,"ramp":"entry","created_at":"2015-08-16 20:50:21","updated_at":"2015-08-16 20:50:21"},{"action_id":43,"action_type":"down","parking_id":39,"user_id":17,"ramp":"exit","created_at":"2015-08-16 20:50:22","updated_at":"2015-08-16 20:50:22"}]

The little parser I created is this:

while(client.available()) {
 char c = client.read();
    if(c == '{'){
      begin1 = true;
    }

  if (begin1) {
    content += c;
   }

  if (c == '}') {
      break;
    }
 }

Is it possible to store only the first action in JSON output, because the actions are updated, and if the number of chars extends 256 than I get errors while working with the String content?

Your question is not clear to me. First of all does your parser get the whole response? And second by first action do you mean "action_id":35"?
If both are true then your solution is simple.

First you separate every comma ", " and put in a string array then you further split each index by ":" so the first part is the name "action_id" and the second is the value "35". I hope that helps . You can look up the split function, it's easy.

But if the above is not what you needed then I am afraid you cannot get only the first response, because that has to do with the server itself.

Here is a solution, do try it.

I found an easier solution. Follow the example and replace the content and fields with your response content and you will be done in minutes.


Some questions about a RGB LED Strip project that Im planning to do Good day all

So Im in the planning and research phase of a new project that I want to start for my car. I want to control a bunch of RGB LED strips independently from each other via a micro controller, preferably Arduino  of courese, with a breakout board or something. I am going to run this system off the car battery so the current shouldn't be an issue, I hope, but prolonged usage will most likely drain the battery quite quickly. The strips I want to control are of the following lengths:

6 x 30cm Pieces
3 x 2m Pieces

So I want to be able to control all of them individually as well as the colour and brightness individually. So here are my questions:

Is there a board that the arduino can talk to that has 27 PWM outputs?
Can one maybe use normal outputs and just HIGH Low them quickly in sequence and use an arduino MEGA?
What would the current draw be if all the colours are on full on all strips? Would  it rather be better to blink them in sequence,rather than full on, and lose some brightness to reduce current draw?
Could multiplexing here be an alternative to controlling them individually? Maybe get it so I switch all the Positive outs of the LEDs, and the connect the 3 colours together. So in that case I would have 3 + 9 outputs?
Would addressable LEDs actually work better?

If you could refer to me to similar projects so I can sniff around there that would be greatly appreciated. So far Im just trying to wrap my head around all the aspects of the project. And yes I know that I wil not be able to use this while Im on public roads, its just for show.... So not sure what the legal aspects there are... :P

You could use chainable RGB drivers like these:

They are based on the P9813 chip and can be used with the FastLed library.
You can find them on Aliexpress or eBay, if you search for "STM32 rgb".


Value read is not changing while rotating pot in arduino? I am trying to read voltage using analogRead in Arduino Uno from a voltage divider circuit consisting of 1k resistor and 10k pot. The Pot used is bourns 3296. The values obtained only range from 1011 to 1023? Why is the count not reducing further if I rotate the pot?

(this how i have connected the circuit, but the pot is the one that i have mentioned above, i couldn't find that kind in the software, but i have made the connection this way only)

int analogPin = A0;

// variable to store the value read
float val = 0;

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

void loop() {
  Serial.println(val); // read the input pin
  val = analogRead(analogPin); // debug value
}

Since potentiometer itself is a voltage divider, I have tried connecting as per the answer, the ends of the 10k pot to 5V and ground , and the slider pin to the analog pin A0. The new circuit is as shown below, but I am still unable to get the value ranging from 0 to 1023. The values returned only vary in between 1010 to 1023. What is going wrong? How do I get the full range?

OK, I am unable to leave a comment (< 50) so...

Use this link to learn about the AREF pin on the Arduino, this may not be your problem but it is good to know about anyway:
what is arduino adc reference?

Your pot MAY be broken. Measure the resistance of the pot with an ohm meter, from the center pin to either of the side pins. Verify when you turn it the resistance varies from 10K to 0.

You can also measure the voltage it is providing your Arduino by measuring the voltage it presents to pin A0. Verify the voltage changes little by little from +5 to 0 when you turn it back and forth.

You list the pot as being a "bourns 3296" which the data sheets show as a "Multiturn / Cermet / Industrial / Sealed" pot.

Just so you know, when you adjust it you will have to turn it 25 turnes to fully adjust it through its entire range. The data sheet shows "Effective Travel.........25 turns nom."


How to have some code executed at a certain time of day with a DS3231 RTC? I recently bought a DS3231 RTC, but I cannot seem to figure out how to get it to work. I have tried all different tutorials and example programs but I keep getting 2165.25.165 165:165:165 as the output.

I am using an Arduino Micro, with the RTC connected as follows:

GND > GND
VCC > 5V
SDA > A4
SCL > A5

Project details:

The project uses a 16x2 LCD to display the time of day, and a countdown to the next occurrence of 06:00. Then at 6 it will allow for a button to be pressed to open a servo and do other things. I got temporary test code to work using millis(), but it is only displaying a 12-hour countdown in seconds, and I would like to replace it with a more reliable RTC.

If you are getting 165:165:165 that indicates usually a problem with your I2C bus. But it might also be a power problem in the RTC.

In any case, check your wiring.

Your processor is simply not properly communicating with the RTC. If the RTC's red light is on then check your wiring and make sure you haven't reversed SDA and SCL.

Also, the DS3231 has and most Arduinos have enough pull-up that you won't need external pull-up resistors in order to communicate directly with the DS3231.

Try plugging it straight into the Arduino - go minimalist and make that work before adding other devices to the I2C bus like a LCD display. Set the clock by code and watch it in the serial monitor.

Once you're sure the RTC is not a problem then you can go from there with the I2C bus. It is certainly possible for other devices on the bus to cause the RTC to be unable to respond correctly. For a short-range I2C bus that includes the DS3231 don't add any external pullups.

The most reliable RTC for Arduino is the DS3231, but if you bought it via the slow boat you might try a voltmeter to verify the battery so it keeps time even when powered down.

And of course, it is only as accurate as you program it to be. When I program my DS3231s, I always add a couple of minutes to the current time to allow for the time to fix forgotten semicolons and such before it gets around to actually programming the device.

One last note: The program will run when you open the serial monitor. So that will be when it sets the time then begins to display it.


Electric interference from cnc spindle I've got a CNC machine and I recently started using a spindle for it. At first it was running smoothly with no issues, but after the first brush pair wore off (I've replaced them later on) it started interfering with the Arduino/gshield and pc monitor. The monitor displays a "no signal" message, although after turning off the spindle or turning it to a low speed the signal comes back. The other problem is that after running a long job, sometimes the gshield disconnects and the job stops midway.

What part could be causing all this interference?
How can I shield that part so it stops interfering with other electronics?

I am using the following hardware:

600 watt spindle
600 watt power supply with variable speed
the wires from the spindle to the power supply are not shielded, although Ive tried covering them with aluminium foil, not sure if that should be of any benefit, I've read it somewhere so I gave it a try.
Gshield with Arduino, connected to a Raspberry pi.

All the electronics are within 70 cm radius.

I would guess that arcing in the spindle causes spikes that travel through the power supplies and power wires. One thing you could try is to use a really long extension cord (say 15 meters or more) to power the spindle power supply. You can insert this cord to a different power outlet to gain additional distance.


FastLED and Neopixel Help I'm in the process of trying to create a "Aurora Glow" effect using a Particle Photon and a Neopixel ring.

I have the code fully working using a single Breadboard-friendly NeoPixel however when upgrading this to a NeoPixel Ring (16 LED) the code does not run as expected

The current working code for a single NeoPixel can be found here: http://pastebin.com/Yj1cywpx

It was my assumption that i could change Line 33 from one LED to Sixteen e.g.:

FastLED.addLeds<NEOPIXEL, 6>(&led, 1);

to

FastLED.addLeds<NEOPIXEL, 6>(&led, 16);

However when I run this code rather than all NeoPixels cycling through the Aurora Colours, only the very Top LED does and rest are either off or a static colour (e.g. http://imgur.com/a/MvKZQ)

Could someone please advise what i missing? Apologies if this is a "Noob" question but this is my 2nd Arduino project and I cannot understand why this would not work.

Thanks

Never used neoPixels in arduino before so this is a complete guess based on reading the code but it looks like you are only setting the colour of the first LED.

Try creating 16 LED colours:

CRGB led[16];

and then setting them all:

for (int i = 0;i<15; i++) {
  int colourIndex = index + i;
  if (colourIndex > 15)
    colourIndex -= 15;
  led[i] = ColorFromPalette(auroraPalette, colourIndex , 255, LINEARBLEND);
}

edit - as @rDg indicates in his answer

FastLED.addLeds<NEOPIXEL, 6>(&led, 16);

becomes

FastLED.addLeds<NEOPIXEL, 6>(led, 16);

since led is now an array not a single value

Finally I think paletteSize should only be 16 not 5*16, you only have 16 colours in there.


Stepper motor doesn't start immediately when i pressed the button When I release my hand from the button on pin 2, the stepper motor takes at least few seconds to stop, but I want it stop immediately. here's my codes:

 #include <Stepper.h>

    const int stepsPerRevolution = 200;  // change this to fit the number of steps per revolution
    // for your motor

    // initialize the stepper library on pins 8 through 11:
    Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

    bool dir = false;
    bool power = true;

    void dir_pin() {
      if (!digitalRead(3)) {
        dir = !dir;
      }
    }//when the switch is being pressed
    //it condition would be different from last time

    void setup() {
      // set the speed at 60 rpm:
      myStepper.setSpeed(60);
      // initialize the serial port:
      Serial.begin(9600);
      pinMode(2, INPUT_PULLUP);//it is a easier way to using INPUT-PULLUP
      //cause you dont have to use a real resistor
      pinMode(3, INPUT_PULLUP);//why choose those two pins
      //cause for uno, the interrupt pin are pin 2 and pin 3
      attachInterrupt(digitalPinToInterrupt(3), dir_pin, FALLING);
      pinMode(A0, INPUT);
    }

    void loop() {
      int pwr = analogRead(A0) / 100;
      Serial.print("power:");
      Serial.print(power);
      Serial.print("  pwr:");
      Serial.print(pwr);
      Serial.print("  dir:");
      Serial.println(dir);
      while (digitalRead(2) == 0)
      {
        if (pwr) {
          myStepper.setSpeed(pwr);
          int pwr = analogRead(A0) / 100;

          if (dir) {
            //Serial.println("clockwise");
            myStepper.step(stepsPerRevolution);
            //delay(500);
          }
          // step one revolution in the other direction:
          else if (!dir) {
            //Serial.println("counterclockwise");
            myStepper.step(-stepsPerRevolution);
            //delay(500);
          }
        }
        else
        {
          myStepper.step(0);
        }
      }
      while (digitalRead(2) == 1)
      {
        pwr = 0;
        myStepper.step(0);
      }
      delay(10);
    }

You tell it to move whole 200-step revolutions, so once it begins a revolution, it must continue.  At 60 RPM, that should be up to 1 full second after you open pin 2.   Depending on the analogRead(A0)/100, a full revolution could take much longer than 1 second -- maybe 5.86s to 6000s

If you want it to stop immediately, disregarding full revolutions, you could:

      stepsPerButtonpress = 1;

      ...

      if (dir) {
        //Serial.println("clockwise");
        myStepper.step(stepsPerButtonpress);
        //delay(500);
      }
      // step one revolution in the other direction:
      else if (!dir) {
        //Serial.println("counterclockwise");
        myStepper.step(-stepsPerButtonpress);
        //delay(500);
      }

Or you could reduce stepsPerRevolution to the fraction of steps you want to treat as a unit, and increase rpm proportionally.


How do I manipulate a large number of moving platforms? I am trying to build a device that will allow me to control at least a couple hundred raising platforms. The goal of this is to create a real time editor for board games (Dungeons and Dragons).

Ideally:

All the platforms would move simultaneously
The platforms would be transparent to allow us to place LEDs inside them to color the platform so we can make colors like blue for water and brown for dirt.

In our current setup, we use some acrylic prisms that are 1 inch x 1 inch x 6 inch (width, length, height). We wanted to use a CNC motor like system to move something around and move a platform. Obviously, this can only raise/lower one item at a time. We calculated (on paper) quite a long update time (calculated approximately 1 sec per platform) to raise/lower a platform. A CNC linear drive type system is the only solution we found that had a reasonable cost/quality (a CNC motor for every platform also raised the power consumption very high). After a few weeks of looking around, planning and throwing stupid ideas away, we found this.

Clearly, it's way better then our idea but I have no idea how they did this. They have 900 platforms and they all work simultaneously. We also don't need real time interaction. Loading from computer and staying static until we change it is good (though water movement would be really nice).

What would you guys recommend to raise simultaneously a thousand small platforms?

After looking at this document that the devs made, and doing a bit more research I found that the device they used to move the platforms cost approxomently $30; I don't think I need to say this, but I don't have $27,000.

Key difference between their implementation and our goal:

No real-time interaction with the table. Controlled by an Arduino is fine.
Size of the platforms will be closer to 1 inch^2
All sides of the platform should be light up, but I believe this is mostly a question of choosing the right material

In terms of cost, perhaps it would be best to build a 4x4 prototype.

My first thought was to use inexpensive servos with a flexible rod inside a sheath, perhaps a wire, like a bicycle brake/gear.  The amount of movement could then be governed by the size of the armature on an inexpensive servo.

Servos will position themselves after being given the command, so there's no need to wait and do them one-by-one.  Fire off the command, then use some sort of multiplexed output like multiple 74HC595 shift registers to connect to the next one.

If the tiles were spring loaded, such that they returned to the topmost position by themselves, only a simple pull-string is needed to adjust the tile height.  Even a very light filament (like fishing line) would be strong enough for the pull.  This would allow the servos to be positioned even some metres away from the table.


Parsing serial port data Hello I found an Arduino project that works with serial port parsing and it had very interesting parsing code. I am trying to use it in my project but I still don't understand some lines and what is going there. (I marked them with ???).

char inData[82]; //create 82 char array
byte index = 0; //index byte (0 - 255)
String string_convert; //String
int PCdata[20]; //int array

void setup() {
  Serial.begin(9600); //init port
}

void loop() {
  parsing(); //loop the function
}

void parsing() {
  while (Serial.available() > 0) {
    //while there is data in serial buffer (128 bytes)
    char aChar = Serial.read(); //aChar - current symbol in buffer
    if (aChar != 'E') {
      //if aChar isnt the 'E' (End) symbol do:
      inData[index] = aChar;
      //(inData - array, index - loop № counter) write all Buffer to the array
      index++; //index + 1 - loop count
      inData[index] = '\0';
      //set the next position to '\0' or null symbol
    } else {
      //if aChar or current buffer symbol is 'E' (End) do:
      char *p = inData; //create inData address pointer
      char *str; //create pointer
      index = 0; //set counter to 0
      String value = ""; //create string
      while ((str = strtok_r(p, ";", &p)) != NULL) { //???
        string_convert = str; //???
        PCdata[index] = string_convert.toInt(); //???
        index++; //counter + 1 - loop count
      }
      index = 0; //counter to 0
    }
  }
}

Thank you for help!

It's parsing a bunch of semi-colon separated data, like "12;34;45;". In each iteration, it converts one value from character representation to its integer value.
strtok_r is the reentrant version of strtok. On Arduino you simply use strtok. Every time you have to parse a string having a list of values separated by some char, you use strtok.
Name
strtok, strtok_r - extract tokens from strings
Synopsis
#include <string.h>

char *strtok(char *str, const char *delim);

char *strtok_r(char *str, const char *delim, char **saveptr);

The strtok() function parses a string into a sequence of tokens (sub-strings). On the first call to strtok() the string to be parsed should be specified in str. In each subsequent call that should parse the same string, str should be NULL.
Each call to strtok() returns a pointer to a null-terminated string containing the next token. This token does not include the delimiting byte. If no more tokens are found, strtok() returns NULL.


How can I switch from ArduinoOTA to ESPhome safely? I have an ESP8266 (ESP-12F), which I flashed with ElegantOTA, a variation of ArduinoOTA with just a different interface. I never managed to flash anything else, so it's a bare OTA I flashed using a dedicated programmer. The device has not even pins for further flashing.

The ESP is already in a device that I would like to avoid opening, and I would like to avoid soldering pins and flashing locally the ESPhome firmware (which is also configured for future OTA).

I'm not sure the bootloader or whatever is used to self-flash the chip is compatible. How can I do it?

Or should I just open the ArduinoOTA webpage, upload a ESPhome firmware and go on?

I've found that when a flash fails with a space error, I've usually specified the wrong flash size option in Arduino (under Tools->Flash Size).  Depending on the version of Arduino you're using, try picking the one with "No SPIFFS" or FS:none that matches the size of your flash memory.  Once you make that change, recompile and reupload.


How to use a push button & transistor as a kickstarter for power supply? My goal is to save energy, and I intend to do so by powering a chip with itself, and cut power whenever unnecessary. The best image I can have is of a startled monkey who jumps on the branch, screams its profanities while holding to the branch, and when the screams are done, lets go of the branch and falls back on the floor, asleep.
The chip, in my case an ATtiny45, has a program that just makes a specific sound (hopefully more pleasing than an angry monkey's) with a PWM, but would also power an output pin connecting to a transistor acting as a relay between the battery and the power pin.
This is the ideal protocol:
(No closed circuit, no power)
Press Button
Battery power goes through to transistor
Transistor allows current from Battery to PWR pin
Software: Chip starts PWM to Speaker and Outputs constantly the Hold Pin
Hold pin powers the transistor and thus the chip for when the button won't be pressed
Software: When Button still pressed, makes Chip Scream louder
Software: Button not pressed anymore makes chip scream softer until it's done screaming
Software: Scream is finished, stops powering the Hold Pin
Transistor isn't powering the chip anymore.

I think the idea is plausible, though I can't test it at the moment due to not having NPN transistors (?)
My questions are the following:

Truth: Is is possible for a transistor as relay to power a chip on demand?
Risks: Is the power going to be stronger due to the amplifying nature of the transistor? What about the chip, I've read that a chip can maintain its code for 20+ years without power supply. Is this true?
Goals: Is there a better way to save power? Would it be best for the chip to just have sleep enabled?
Name: If this works, is there a better name than the Startled Monkey?

Thanks again for your help, this community has already taught me a lot!

simulate this circuit – Schematic created using CircuitLab

Your idea is sound, but your implementation is flawed.
First, you don't want to bother with "wake" and things like that - when the chip gets power it just starts from scratch - that's your "wake" signal. Your code will just be "Hold it on" and "Make a sound" followed by "Let it switch off".
You only need one IO pin for that - the "Hold it on" signal. The "catch" signal in your schematic is just the chip getting power.
And then there's your schematic.  You should really use a P-channel MOSFET to do the switching of the power, not an NPN transistor. An NPN won't work, and a PNP (which would be what you would use for this if you were using a BJT) would impose a voltage drop, which you don't want.
Your circuit would in fact need to look like this:

simulate this circuit – Schematic created using CircuitLab
When idle M1 (P-channel with threshold voltage well below the battery voltage) is turned off by R1 pulling the gate up to the source voltage. Pressing the button pulls the gate below its threshold voltage allowing M1 to turn on. The chip then gets power.
M2 (N-channel with threshold voltage well below the chip voltage) is then activated by the chip by driving the GPIO HIGH to bypass the switch and connect the gate of M1 to GND.  R2 keeps M2 turned off while idle.
M2 is needed so that there is no current flow between the battery and the GPIO when the power is turned off.  Without it current can flow through R1 into the GPIO, through the ESD protection diodes inside the chip, and potentially break the chip.
Now to help clear up some of your questions:

Truth: Is is possible for a transistor as relay to power a chip on demand?

Yes, it is.

Risks: Is the power going to be stronger due to the amplifying nature of the transistor?

No. Amplification, with a BJT, is really a misnomer. It doesn't "amplify" a signal, it takes one small signal and uses that to proportionally control a larger signal. But that's only in the "linear" portion of the curve. When used in "saturation" like this it's more like a switch - power applied to the base turns on the flow of current from collector to emitter.

What about the chip, I've read that a chip can maintain its code for 20+ years without power supply. Is this true?

Yep. Flash memory typically has a retention time in the order of 10 to 100 years. 20 years is a reasonable ballpark figure.

Goals: Is there a better way to save power? Would it be best for the chip to just have sleep enabled?

Zero power is the best low power there is. Even in the deepest sleep mode the chip will still draw power. But if you do it right there can be little difference between the current drawn by a sleeping chip and the self-discharge of a battery as it sits idle.

Name: If this works, is there a better name than the Startled Monkey?

I like the name Startled Monkey. I think I'll use that in future myself.


Can I call functions from a different sketch? I am a beginner at programming with Arduino and I am unsure on how can I call functions (such as, getData()) for the touchscreen LCD to display that data. The purpose of my device would be to listen to data communications between sensors and a controller and thus I have one RedBoard with CAN-BUS shield with a dataComms.ino sketch, which initialises getting data functions from received data packets and parses them.

Do I need to create another sketch for the display? If so, how can I call functions from another sketch, so that display.ino would have access to received values? Or are there some better ways of displaying data?

You can only use one sketch at a time, meaning one sketch can be stored inside an Arduino to be executed.

This means all your code (and functionality for all devices you want to access) needs to be within that single sketch.

So what you mostly need to do is:

Add a library for every device that you want to use.
Call functions from that library in your .ino file.
If you want to add functions which are not part of a library, you add both the function code and the call (where you need it) in your .ino file.

Also if you are new, don't start with everything at the same time.

First find an example how to control the display (that's probably easier than the CAN shield).
Add the library for the display
Change (or copy from an example) code for the display
Run and debug it until it works.
Create a new sketch for the CAN shield.
Add the library for the CAN shield.
Call functions from that library (or use an example if available).
Once you are convinced you know how to use both devices (display + CAN), combine the sketches (create a new sketch, add both libraries, copy code and make it one sketch).


Sending sine wave from MATLAB and reading on Arduino Uno I am working on timing issues associated with sampling data at high rates and storing it on an SD card (ADC delays, clock drifts and file I/O time). For this experiment, I thought of sending a sinusoidal wave to an analog pin on the Arduino Uno, and have the board read the samples. Can I eliminate the need for a function generator and instead use the Matlab Support Package for Arduino to send the sinusoid to the Arduino? (I guess this would mean two programs simultaneously, a Matlab program for generation of a sinusoid and an Arduino sketch for reading and writing.)
I'm new to Matlab, so any help would be greatly appreciated.

No, you can't. The Arduino Uno has no analog outputs to start with and,
as you guessed, it cannot run two programs at the same time.

Maybe you should search for a solution of the initial problem instead.
You should be aware that you cannot get consistent timings with
analogRead(). You will have to read the datasheet of the ATmega328p,
especially the section dedicated to the ADC. Then you will configure the
ADC yourself, at the register level. It has a feature called
“auto-trigger” which is intended to provide perfectly consistent
timings. This is what you are looking for.


Arduino analogWrite source code explanation The source code for the analogWrite function looks like this:

void analogWrite(uint8_t pin, int val) {
    ...
    sbi(TCCRnA, COM0x);
    OCRnx = val;
    ...
}

Where n is which timer (0, 1, 2...) and x is which pin is controlled by that timer (A, B).

This doesn't make sense to me, because the ATmega328P datasheet says that the bits TCCRnA.WGM0[1:0], and TCCRnB.WGM0 need to be set up as well.

Datasheet

Obviously the above code works, but how, with the missing bit settings?

Look at the init() function in wiring.c.  All of the timers get set up there depending on which chip is selected.  I don't know if some might also be done by initVariant().  But all it leaves for analogWrite to do is set the bit in the COM register to enable the PWM.


How are HIDs (keyboard,joypad) created and mapped? I am creating an electronic device that has a 4 position rotator switch and a SPST Momentary ON push button. For the knob, I plan for position 0 to be low (OFF). Position 1-3 are high (ON). But I want these positions to equate to a different signal so they each have different values. When push button is pressed, it sends a high (ON) signal.

Can someone point me into slightly setting up the circuit to accomplish this?
And how can I create a remapper program (preferably in C++) that detects the HID device and allows the end-user to remap the pushbutton signal to any QWERTY key? I want replicate this process for each input of my device.

When the Arduino sends data to the computer using the HID protocol it sends what is called a HID Report. That is basically an array of numbers in a pre-defined format that correspond to what the computer is expecting.

In the case of keyboard events it sends a HID Keyboard Report

It can send events for up to 6 keys at once along with up to 8 meta keys.  How those key events are interpreted are down to the Keyboard Mapping used on the computer.  This is the setting (usually in the Language or Regional settings of the computer) that defines the layout of your keyboard - UK, US, French "AZERTY", etc.

While it is possible to create custom key mappings in many operating systems it is usually a very difficult and involved task. Also the mapping takes effect for every keyboard attached to the system, including the one you type on. So changing the mapping at will is probably not a good idea since it could break your normal keyboard usage.

So how would you go about doing what you want to do?  Well, my recommendation is not to do it on the computer, but to do it on the Arduino.  The Arduino has multiple interfaces available at once. As well as the HID interface for keyboard and mouse it also has the CDC/ACM interface for emulating serial. You can use both of these at once quite happily.  So you can use that USB serial interface to configure the way the Arduino works - including what key code to send for any particular event.  You could even write an easy-to-use GUI in Visual Basic or something that communicates with the Arduino over serial to adjust the settings.  How you do that communication (what protocol you come up with) is entirely up to you.

As for the hardware side of things - all you really need is just the switches / buttons and wire.  Just follow the on-line tutorials (there's millions of them) for connecting switches and buttons to the Arduino. Enable the internal pullups, and connect the switch between the I/O pin and ground.  For the rotary switch you will have 4 inputs and 1 output, so connect the 4 inputs to I/O pins and the 1 output to ground.