All the differences between Arduinos: Pro Mini & Pro Micro I'd like to know the differences between these two boards: Arduino Pro Mini and Arduino Pro Micro.

Even if I've read this and this related post, it is not clear enough. I've always used the Arduino Uno or Leonardo and I'm a little bit scared of using these compact miniaturised boards.

I have seen so far those differences:

The Micro doesn’t need the separate FTDI, while the Mini does
The Micro takes more time to boot up due to USB device (keyboard/mouse) emulation (is more like a Leonardo than an Uno)
They both have 5 V and 3.3 V versions
The Mini has 2 more digital IO and 2 more analog Inputs (1 more PWM)
The pinout is the same (a shield designed for the Pro Mini is OK also with Pro Micro)
Micro is more expensive (IF you don't have already an FTDI cable).

So, what I care about most is the boot up time (because it could make debug harder) but other than that.. if I don't need the 2 more Digital IO and the 2 more Analog Inputs.. why buy one over the other?

And some more question: can I use the Mini boot loader inside the Micro to avoid the boot up time (if I do not need the keyboard/mouse emulation)?

Is the power consumption the same? Can I use the same battery?

Sorry if this is a silly question but I'm little bit confused.

It is more the differences between ATMega328P + FTDI (Pro Mini) vs ATMega32u4 (Pro Micro)

Apart from the minor pin differences, the peripherals for both MCUs are the same. The major difference is the ATMega32u4 has built in full-speed USB. This allows the board to function as a USB device by implementing the appropriate USB stack. E.g. it can act as a

USB to serial converter (CDC device)
Keyboard or mouse (HID device)
USB hard drive (MSC device)
MIDI controller
and more...

The LUFA library from AVR devices can be used for this but means going outside of the Arduino IDE and compiling proper C code using the latest avr-gcc tools.

The Arduino core library has built-in support for the HID and CDC device profiles. The CDC profile is used for comms with the Leonardo, Micro, etc. while the HID profile is used for keyboard / mouse emulation.

The Leonardo / Micro boot loader implements a CDC profile for communications with the PC. This CDC profile uses Arduino vendor and product ids so unlike FTDI devices, requires an extra step to install an *.inf file on Windows.

You would have to recompile the Pro Mini bootloader for the Micro, but even then it would require an FTDI board as programming would need to be done via the TX and RX UART pins. If you we going to go to all that trouble you could just recompile the proper boot loader to have a shorter time out. Why is difference of 1 or 2 seconds in boot loader time important?

The ATMega32u4 uses more power than the ATMega328P.


Reading multiple bytes from *software* serial I have Arduino Leonardo board operating lots of AC relays in quite noisy environment. USB works unstable, which sometimes causes the board to hang, so I decided to use secondary serial connection as "debug console":

  Serial1.begin(115200);
  .....
  .....
  if (Serial1.available()) {
    char ch = Serial1.read();
    if ( isalnum(ch) ) {
      switch (ch) {
        case 'M': {
          turnOn_pin_Motor();
          break;
        }
        case 'm': {
          turnOff_pin_Motor();
          break;
        }
        .......

My problem is that noise affects Serial1 the same way it messes USB (but at least it doesn't cause it to freeze). I'd like to use some sort of error checking to prevent Leonardo from acting on "phantom" commands. I could, for example, prefix each keyboard command my Arduino should receive with special symbol, maybe "!".

So I must be reading one char, checking if it is "!" and reading second character.

Unfortunately, I can't modify my code so it would use 2-character buffer and shift its contents as characters arrive, without locking the main loop while waiting for the next char. Any hints on what should I do in this case?

Serial1 on the Arduino Leonardo is hardware serial, not software.

There are several ways to read in multiple bytes from Serial.

Instead of detecting Serial.available() (i.e. non-zero), change it to Serial.available() >= 2

if (Serial.available() >= 2) {
  for (int i=0; i<2; i++) {
    buffer[i] = Serial.read();
  }
}

Or you can leave it as it is, and read into the buffer one at a time.

static int bufferIndex;

if (Serial.available())
{
    buffer[bufferIndex++] = Serial.read()
}

You'll need to detect the contents of the buffer in another if statement, and also deal with the bounds of the index.

Honestly though, noise is your issue here - this is an example of an XY problem. There's nothing inherent in using a microcontroller with relays that should mean that serial won't work.


Sending Data from ESP8266 to PHP I want to display the RFID tag value to a html file.

I am using ESP8266 ESP-01 module, EM-18 Reader Module, Arduino Uno and Xampp for hosting PHP.

Right now, I am getting a value of "255" in Arduino whenever I scan a RFID tag. But I am supposed to get the 12-digit alphanumeric RFID tag value.

I have attached the Arduino and also the output screen of the Serial Monitor.

I have my college submission next week so it's urgent. Any help would be appreciated.

#include "SoftwareSerial.h"
String ssid ="Home";
String password="****";
SoftwareSerial esp(2, 3);// RX, TX
String data;
String server = "192.168.0.182"; // www.example.com
String uri = "/testget.php";// our example is /esppost.php
int DHpin = 0;//sensor pin
byte dat [12];
String tag;

void setup() {
  pinMode (DHpin, OUTPUT);
  esp.begin(9600);
  Serial.begin(9600);
  reset();
  connectWifi();
}

//reset the esp8266 module

void reset() {
  esp.println("AT+RST");
  delay(1000);
  if(esp.find("OK") )
    Serial.println("Module Reset");
}

//connect to your wifi network

void connectWifi() {
  String cmd = "AT+CWJAP=\"" +ssid+"\",\"" + password + "\"";
  esp.println(cmd);
  delay(4000);
  /*
  if(esp.find("OK")) {
    Serial.println("Connected!");
  }
  else {
    connectWifi();
    Serial.println("Cannot connect to wifi"); }*/
}

byte read_data () {
  byte data;
  for (int i = 0; i < 13; i ++) {
    if (digitalRead (DHpin) == LOW) {
      while (digitalRead (DHpin) == LOW); // wait for 50us
        delayMicroseconds (30); // determine the duration of the high level to determine the data is '0 'or '1'
      if (digitalRead (DHpin) == HIGH)
        data |= (1 << (12-i)); // high front and low in the post
      while (digitalRead (DHpin) == HIGH);
// data '1 ', wait for the next one receiver
    }
  }
  return data;
}

void start_test () {
  digitalWrite (DHpin, LOW); // bus down, send start signal
  delay (30); // delay greater than 18ms, so DHT11 start signal can be detected
  digitalWrite (DHpin, HIGH);
  delayMicroseconds (40); // Wait for DHT11 response
  pinMode (DHpin, INPUT);
  while (digitalRead (DHpin) == HIGH);
    delayMicroseconds (80);
  // DHT11 response, pulled the bus 80us
  if (digitalRead (DHpin) == LOW);
    delayMicroseconds (80);
  // DHT11 80us after the bus pulled to start sending data
  for (int i = 0; i < 13; i ++)
    // receive tag value data, the parity bit is not considered
    dat[i] = read_data ();
  pinMode (DHpin, OUTPUT);
  digitalWrite (DHpin, HIGH);
  // send data once after releasing the bus, wait for the host to open the next Start signal
}

void loop () {
  start_test ();
  // convert the bit data to string form
  tag= String(dat[12]);
  data = "tag=" + tag;// data sent must be under this form //name1=value1&name2=value2.
  Serial.println(data);
  httppost();
  delay(1000);
}

void httppost () {
  esp.println("AT+CIPSTART=\"TCP\",\"" + server + "\",80");//start a TCP connection.
  if( esp.find("OK")) {
    Serial.println("TCP connection ready");
  }
  delay(1000);
  String postRequest =
  "POST " + uri + " HTTP/1.0\r\n" +
  "Host: " + server + "\r\n" +
  "Accept: *" + "/" + "*\r\n" +
  "Content-Length: " + data.length() + "\r\n" +
  "Content-Type: application/x-www-form-urlencoded\r\n" +
  "\r\n" + data;
  String sendCmd = "AT+CIPSEND=";//determine the number of caracters to be sent.
  esp.print(sendCmd);
  esp.println(postRequest.length() );
  delay(500);
  if(esp.find(">")) {
    Serial.println("Sending..");
    esp.print(postRequest);
    if( esp.find("SEND OK")) {
      Serial.println("Packet sent");
      while (esp.available()) {
        String tmpResp = esp.readString();
        Serial.println(tmpResp);
      }
      // close the connection
    esp.println("AT+CIPCLOSE");
    }
  }
}

Output :

I got it working using the code below:

#include "SoftwareSerial.h"
String ssid ="Home";

String password="%Qwerty@123%";
char input[12];
int count = 0;
SoftwareSerial esp(2, 3);// RX, TX

String data;

String server = "192.168.0.182"; // www.example.com

String uri = "/testget.php";// our example is /esppost.php

int DHpin = 0;//sensor pin

byte dat [12];

String temp;

void setup() {

pinMode (DHpin, OUTPUT);

esp.begin(9600);

Serial.begin(9600);

reset();

connectWifi();

}

//reset the esp8266 module

void reset() {

esp.println("AT+RST");

delay(1000);

if(esp.find("OK") ) Serial.println("Module Reset");

}

//connect to your wifi network

void connectWifi() {

String cmd = "AT+CWJAP=\"" +ssid+"\",\"" + password + "\"";

esp.println(cmd);

delay(4000);
}

byte read_data () {

byte data;

for (int i = 0; i < 8; i ++) {

if (digitalRead (DHpin) == LOW) {

while (digitalRead (DHpin) == LOW); // wait for 50us

delayMicroseconds (30); // determine the duration of the high level to determine the data is '0 'or '1'

if (digitalRead (DHpin) == HIGH){

data |= (1 << (7-i)); // high front and low in the post
 }
while (digitalRead (DHpin) == HIGH);

// data '1 ', wait for the next one receiver

}

} return data; }

void start_test () {

digitalWrite (DHpin, LOW); // bus down, send start signal

delay (30); // delay greater than 18ms, so DHT11 start signal can be detected

digitalWrite (DHpin, HIGH);

delayMicroseconds (40); // Wait for DHT11 response

pinMode (DHpin, INPUT);

while (digitalRead (DHpin) == HIGH);

delayMicroseconds (80);

// DHT11 response, pulled the bus 80us

if (digitalRead (DHpin) == LOW);

delayMicroseconds (80);
while(count<12){
input[count] = Serial.read(); // Read 1 Byte of data and store it in the input[] variable
      count++;          // increment counter
      delay(5);}
// DHT11 80us after the bus pulled to start sending data

//for (int i = 0; i < 4; i ++)

// receive temperature and humidity data, the parity bit is not considered
/*for(int x=0;x<12;x++)
for(int i=0;i<12;i++)
//dat[i] = read_data ();
dat[x]=input[i];*/

pinMode (DHpin, OUTPUT);

digitalWrite (DHpin, HIGH);

// send data once after releasing the bus, wait for the host to open the next Start signal

}

void loop () {

start_test ();

    count = 0;      // Reset the counter to zero
    temp = "";
    // convert the bit data to string form
for(int i=0;i<13;i++)
temp += input[i];
Serial.println(temp);
//Serial.println(temp);

data = "tag=" + temp;// data sent must be under this form //name1=value1&name2=value2.

httppost();

delay(200);

}

void httppost () {

esp.println("AT+CIPSTART=\"TCP\",\"" + server + "\",80");//start a TCP connection.

if( esp.find("OK")) {

Serial.println("TCP connection ready");

} delay(100);

String postRequest =

"POST " + uri + " HTTP/1.0\r\n" +

"Host: " + server + "\r\n" +

"Accept: *" + "/" + "*\r\n" +

"Content-Length: " + data.length() + "\r\n" +

"Content-Type: application/x-www-form-urlencoded\r\n" +

"\r\n" + data;

String sendCmd = "AT+CIPSEND=";//determine the number of caracters to be sent.

esp.print(sendCmd);

esp.println(postRequest.length() );

delay(500);

if(esp.find(">")) { Serial.println("Sending.."); esp.print(postRequest);

if( esp.find("SEND OK")) { Serial.println("Packet sent");

//while (esp.available()) {

//String tmpResp = esp.readString();

//Serial.println(tmpResp);

//}

// close the connection

esp.println("AT+CIPCLOSE");

}

}}


Communicating between a computer and multiple Arduinos I am designing a experiment of controlling 6 small wind turbines wirelessly. For each wind turbine, I need to measure power time series (or voltage or current time series) from the generator, and control blade pitch angle, yaw angle, and generator load (using variable resistance). The control input will be all PWM signal.

I am planning to put an Arduino UNO with a ZigBee wireless module to each wind turbine, making it measure the power time series and transmit to the central node, as well as receive the control input from the central node and command the control input to servo motors. The central node will be additional Arduino UNO.

Here are my questions:

Is it possible for each Arduino to send time series signal to central node wirelessly without interference with other Arduino? (6 wind turbines transmitting time series to a central server). If it is possible, How can I implement such network ? recommending a source for learning would be also greatly helpful.
Interface between the central node and the computer software: The algorithm in the computer need to process the received power time series and determine the optimum control input for 6 wind turbines. Then these control input should be transmitted to wirelessly to 6 wind turbines. In such case, what is the good option to interface the algorithm and the Arduino connected to the computer? Currently the algorithm is written in Matlab. I heard there is the sketch interfacing Arduino and Matlab, is it efficient enough for such project?

It is very interesting project. In my opinion, i would not do like you want to control generators from one point.

Look at ZigBee and Wireless sensor network. It is possible. Do more search, also there are several books about networking.
I think that would be more efficient to control the wind turbine with an Arduino and send only data to the main computer. Main computer should do some calculations or send some main configuration data or control on/off wind turbine basis of:

2.1  Metrological data (wind speed or else);

2.2 Storage SOC(if you will store it in batteries or somewhere);

2.3 Required power of grid and etc. etc.

Arduino UNO like you said, connected to computer could do just data collection and making it compatible with computer(MatLab or whatever) and spread control data from PC to targeted Arduino.

Added links

Could not add more than 2 links due to low reputation :)

http://www.digi.com/pdf/wp_zigbeevsdigimesh.pdf , http://forum.arduino.cc/index.php?topic=105273.0


Measure Water Flow in literes using Arduino Mega 2560 Board and Water Flow Sensor I have a water flow sensor with Arduino Megs 2560 board. I am trying to conceptualize the concept to calculate amount of water getting dispensed esp. in 1,2,3,4 and 5 liters quantity.

Water flow sensor specification:

http://www.seeedstudio.com/wiki/images/b/b7/Water_flow_sensor_datasheet.pdf

I would connect the sensor input to any pin from 22-53 pin.

Suppose I connect to ping 23 so in my setup() function I would add:

attachInterrupt(23, pulseCounter, FALLING);

where pulseCounter is an interrupt function triggered on each signal generated from sensor and increments a variable

void pulseCounter()
{
  // Increment the pulse counter
  pulseCount++;
}

Now how do I calculate the flowrate and water dispensed in milliliters using this information?  How do I know the freqz of the MCU (which is required as water dispensed per pulse is different for different MCUs)?

the pulse rate can be derived without knowledge of the CPU clock speed. To achieve the pulse rate from your sensor input you can do two things:

count the pulses dn within a certain (i.e. fixed) interval T of time) or
measure the time dt between two pulses.

I'll come back later on this concerning accuracy.

To measure time, you can use the function millis(). This function returns you the milliseconds since bootup as an integer upon calling it. Method 2 is rather simple to implement.

Setup three global integers a, b and c.
At the end of setup set a to current millis();
In your ISR set b to current millis();
Also in ISR: set a=b;
calculate c=b-a (i.e. your dt);

c holds your current full wave pulse length in milliseconds, which is updated every pulse. You can derive your flow then from it.

The first method uses a counter as demonstrated in your suggestion. You then need a timer outside your ISR, two variables d and e. Either you poll millis() in your main "loop()" or you install a timer interrupt, both will work here.

At the end of setup set d to current millis();
If your predefined time T is passed (by comparing d with millis(),
save your counted pulses to e=pulseCount
reset: pulseCount=0

e holds your pulse count during interval T, from which you can derive your pulse rate.

Accuracy

Method 1's accuracy increases with higher T and higher flow speeds. Therefore the update rate of your measurement is low. By changing T you can easily increase accuracy on cost of responsiveness. This is perhaps a good idea, if you have pulsating flows in your tubings, or the sensor is a bit rattling.

Method 2's accuracy increases with lower flow speeds. It is best to measure very low flow speeds. Update frequency is minimal (1/dt).

Regarding this sensor you should calibrate it yourself. It is a cheap and rugged device (I'm using it, too), but its output depends on several parameters like mounting position, fluid viscosity and so on. Make sure, there are no bubbles, foam or contaminants in your fluid systems as they garble the results effectively.

n.b.: make sure to take care of an overflow of millis().


Arduino Mega 2560 not showing up in Serial Port in IDE I recently purchased an Arduino Mega 2560. As soon as I connected it for the first time with my macbook pro the led was blinking (default blink program). To stop the blinking, I uploaded an empty sketch to Arduino. Now the arduino is not showing up in serial port in any operating system. The LED is constantly on and not blinking. Please help

Did you try:-

Unplugging and reconnecting the board?

or

Holding down the reset button (on the board) during compile and then letting go when the Ide says "Uploading to ..."? (Make sure the sketch has a setup(){} and loop(){} so is not entirely empty)

If that doesn't work then ...

The pin13 on all the time with an empty sketch might indicate a hardware problem. Is anything connected to the board apart from the usb cable? Green LED simply means the board has power unless you are talking about the tx/rx Led's?

for windows users ...

Look in "Control Panel>Device Manager" to see if there is an exclamation mark against any devices, or "Unknown/Other" devices? If you can see the board but it has an error against it look at the properties to see if you can see what the error is. Re-installing the arduino ide will attempt to install the usb drivers again but they can also be found in the \drivers sub folder below the Arduino Ide.
If you can see an entry in control panel but it is not showing in the Arduino Ide try changing the port to a different COM number (right click>properties)
If you can't see anything in Control Panel try a different usb port on your computer.
Is the board connected directly to the pc via usb or via a usb hub? Make sure direct connect. If power externally make sure enough power.


Control LED strip IR controller using Arduino Is it possible to connect to one of these, which run at 12v, to turn on the LED strip using an ESP8266? It doesn't matter if it's an Arduino or the ESP8266, both should be able to do this. The board looks like this:

If I turn on the red light, the "R" gets grounded and therefore applies 12v to the rail. The 3 MOSFETs on the images are P0903BDG MOSFETs.

Alternatively, I can hook into the IR signal and send an IR signal using the ESP8266. That would be really awesome, as it only requires 3 wires. How that is possible, I'm not really sure, though.

I know it's possible to make your own circuit using IRLZ44N MOSFETs, which I have done before, but I want to try and use as much as this circuit as possible.

I tried to do the same thing with hooking up an IR LED on a Raspberry Pi. It worked pretty well but the chip on the receiver board could not take fast switchings. I ended up doing my own PCB.

The problem is that the chips run at voltages higher than you would use for an ESP8266 or Arduino. This will be the biggest problem if you want to supply it with the voltages available on the board.

I think the safest thing is to see if you can simulate IR input by just connecting to GND and OUT of the IR receiver port.


Understanding memory fragmentation due to char arrays in functions This is similar to:
Is this function subject to memory fragmentation?

I am trying to get my head around Memory fragmentation in Arduino's and embedded systems in general.

Currently I have a function in a __lcdAux__ Class which is responsible for doing basic operation on the lcd.
One of the members of the class is a char array double2StrBuff1 which is used with __dtostrf()__ to create a double which is then passed to sprintf. So the following function (__lcdAux::UpdatePosition__) is responsible for updating the position on the lcd.

void lcdAux::UpdatePosition(double MtXPosLengthUnits) {
    lcd->setCursor(0, 2);
    dtostrf(MtXPosLengthUnits, 0,3, double2StrBuff1);
    sprintf(lcdBuff, "X: %s", double2StrBuff1);
    lcd->print(lcdBuff);
}

Currently, I am under the impression that by defining once the class as a global variable and then using it throughout the program, then the char array is allocated only once memory space. Therefore by using it afterwards no memory fragmentation occurs.

However, I read that functions allocate space on the stack which is immediately recoved when the function is exited. Therefore I am curious if the following declaration is any different in terms of memory fragmentation.

void lcdAux::UpdatePosition(double MtXPosLengthUnits) {
    lcd->setCursor(0, 2);
    char double2StrBuff1[10];
    dtostrf(MtXPosLengthUnits, 0,3, double2StrBuff1);
    sprintf(lcdBuff, "X: %s", double2StrBuff1);
    lcd->print(lcdBuff);
}

To sum up:

by putting  the declaration for variable __char double2StrBuff1[10];__  inside the function, is the memory allocated from the stack and therefore recovered upon exiting the function (therefore there is no need to declarate a member variable on the class level),

OR

is the fact that __double2StrBuff1__ is a pointer means that the pointer is allocated in the stack but the values are located in the heap (therefore what I am doing makes sense)?

PS: Because some might point out that  __"X: %s"__ is worse in terms of memory usage and fragmentation, I'll state the following. Instead of the format string __"X:%s"__ I use a _PROGMEM const char_ array and __strcpy_P()_, but to simplify the question I replaced it with the literal string , since I feel that is another problem.

by putting the declaration for variable char double2StrBuff1[10];
  inside the function, is the memory allocated from the stack and
  therefore recovered upon exiting the function

This is correct.

  is the fact that double2StrBuff1 is a pointer means that the pointer
  is allocated in the stack but the values are located in the heap
  (therefore what I am doing makes sense)?

No, double2StrBuff1 is not a pointer, it's an array. In C and C++,
when you use an array identifier, it decays to a pointer in many
situations. However, for the purpose of memory allocation, an array is
very different from a pointer.

Heap allocation only happens when using malloc() and new.


The code of ISR executes twice i am using Arduino Mega.. ANd this is the code:

void bump(void);

void setup()
{
    pinMode(19,INPUT);
    attachInterrupt(4,bump,HIGH);
    pinMode(13,OUTPUT);
}

void loop()
{

}

void bump()
{
   for(float i = 0; i < 90000; i++){
   digitalWrite(13,HIGH);
   }
   for(float i = 0; i < 10000; i++){
   digitalWrite(13,LOW);
   }

}

Although i give +5 V to it once, the LED will blink twice...!
What is the solution?

After wondering over it for quite a long time, I finally came to the conclusion, that the interrupt should be made to trigger at RISING edge, if I want it to go into ISR the moment it gets HIGH.

Hence the setup line was change to

attachInterrupt(4,bump,RISING);

And the cod e works well.
I suppose that is because, when it receives a HIGH signal, than the period for which it receives HIGH is a bit long, during which it adds another interrupt into the queue, and so the ISR is executed once again.


Why does controlling power with a transistor interfere with MHZ19B's serial communication? I've been trying to turn off an MHZ19B (datasheet and teardown photos: revspace.nl/MH-Z19B). I've used an Arduino, NPN, PNP transistors and mosfets as well as the diagram below for connecting the sensor to an ESP32. In all cases, PWM communication works great! I can power off the sensor, turn it back on, and values derived from PWM communication are as expected. However when I connect the Rx and Tx lines (to software serial Tx and Rx pins respectively on Uno pins A0 A1 or ESP32 pins 32 33) they spit out gibberish and the PWM signal also suffers hiccups.
Otherwise, without any kind of logic power control, the MHZ19B works great and can communicate with anything via UART, even my PC usb port via FTDI.
I added resistors to the Rx and Tx lines so the voltage on them doesn't exceed Vcc. I tried 1n4007 diodes (they're the only ones I have; no Schottky diodes either). I tried an NPN equivalent optocoupler. I also tried powering the sensor from my breadboard. I don't own an oscilloscope :(
My High School teacher said to just use PWM, but as I searched for a solution to this error, I noticed hundreds of others have this exact same problem with all sorts of different sensors and loads with ICs; no one has come up with a general solution.
I've been obsessing with this for weeks and if anyone can help or can recommend a book about sensor schematics I would really appreciate it. Thanks!

Just guessing but I suggest you use a level translator. Also when you power off the sensor the serial output should go to ground disabling that channel.  Check your voltages and put a bypass cap on the transistor for the sensor. You can use a simple P channel Logic Level fet,only a 50 ohm resistor in the gate to prevent oscillation.  Your output will now be active low instead of active high. If you stay with transistors make R2 & R3 510 ohm so you have enough drive for the transistor and be sure it is NOT a darlington device, if it is you will not have enough voltage for the sensor.


Blue LED not switching off I have a circuit with a blue led, 470ohm resistor and one IR led. I want the led to be switched off when the IR led has a digitalRead value of LOW(i move my hand over it). So I wrote the code:-

void setup() {
// initialize digital pin 13 as an output.
pinMode(13, OUTPUT); // this is the blue led
pinMode(10, INPUT);  // this is the IR sensor's O/P

}

// the loop function runs over and over again forever
void loop() {
digitalWrite(13, HIGH); // first I give HIGH voltage to the blue LED

if(digitalRead(10) == LOW){  // when the voltage of the IR sensor decreases
digitalWrite(13, LOW); // the blue LED should switch off or have 0 Voltage
}

}

But the blue LED just dims and doesn't switch off. Thanks in advance

Every time through your loop, the LED is being set to HIGH voltage. This may or may not be followed by setting it to LOW voltage, but since the loop runs again immediately, it's immediately set back to high voltage. This happens so fast that the LED essentially "feels" half voltage and it will dim. Your code needs to be more like this...

void loop() {
  if(digitalRead(10) == LOW) {
    digitalWrite(13, LOW);
  } else {
    digitalWrite(13, HIGH);
  }
}

OR... even like this...

void loop() {
  digitalWrite(13, digitalRead(10));
}


Storing Long numbers in arduino like phone numbers...How? I am using 20 x 4 LCD And 3 x4 keypad I want to enter and store 3 inputs in different variables the code I am using can store 3 inputs and display it right in serial monitor example I type 5 digits using keypad it will store and display correctly in LCD and serial monitor the right value however if its more than five it has negative output and very far to what inputted. Thank you for help .The code is...

#include <SoftwareSerial.h>
#include <LiquidCrystal.h>
SoftwareSerial mySerial(6,5);
#include <Keypad.h>
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns

char keys[ROWS][COLS] = {
  {'1','2','3'},
  {'4','5','6'},
  {'7','8','9'},
  {'*','0','#'}
};
byte rowPins[ROWS] = {19, 18, 17, 16}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {15, 14, 13}; //connect to the column pinouts of the keypad

int count=0;
Keypad kpd = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);

char entryStr[12];   // This can hold up to 4 digits
int i=0;

void setup()
{
    mySerial.begin(9600);
    Serial.begin(9600);
    lcd.begin(20, 4);
}

void loop(){
    long n1, n2 , n3;

    lcd.setCursor(0,0);
    lcd.print("Enter n1:   ");

    lcd.setCursor(0,1);
    n1 = GetNumber();
    Serial.println ("n1: ");
    Serial.println (n1);
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Enter  n2:   ");

    lcd.setCursor(0,1);
    n2= GetNumber();
    Serial.println ("n2: ");
    Serial.println (n2);
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Enter n3:   ");
    lcd.setCursor(0,1);
    n3 = GetNumber();
    Serial.println ("n3: ");
    Serial.println (n3);
}

int GetNumber()
{
    long num = 0;
    char key = kpd.getKey();
    while(key != '#')
    {
        switch (key)
        {
            case NO_KEY:
            break;

            case '0': case '1': case '2': case '3': case '4':
            case '5': case '6': case '7': case '8': case '9':
            lcd.print(key);
            num = num * 10 + (key -'0');
            break;

            case '*':
            num = 0;
            lcd.clear();
            break;
        }
        key = kpd.getKey();
    }
    return num;
}

int GetNumber()

should be changed to

long GetNumber()

It is because the function type is the type of value that returning. In this case you are returning a long so you have to change it. An int can handle a number from -32 768 to 32 767. A long on the other side can handle a number from -2,147,483,648 to 2,147,483,647.


Arduino IDE / Specified folder/zip file does not contain a valid library I trying to add library here but it doesn't seem to work https://github.com/esp8266/Arduino

This happens
"Specified folder/zip file does not contain a valid library"

This problem make me no longer upload any library. any solution about this??
Manual installation does not either.

You don't install that repository as a Arduino library.

Read the README file in that repo. It explains how to install it using the Arduino IDE Board manager. That's the correct way to install it.


PWM water pump flow control - in percent I want to control flow level on 12V water pump with PWM pin, I'm using IRF520N MOSFET for that (and dedicated 12V power supply).

I'm assuming, that setting PWM to full byte should give me about 100% or 12V. But how to set proper value on PWM pin so the flow equals to eg. 10%, 25% or 50%? Is it some logharitmic equation?

Expanding on dannyf's answer, if the pump datasheet does not feature a graph, then you will have to experiment. If a flowmeter is not readily available, an excellent approximation can be calculated by pumping water into a large, known receptacle (e.g. 10 litre bucket) and timing how long it takes. Do this for 20%, 40%, 60%, 80% and 100% Pulse Width Modulation modes, and you will have a plot of flow rate vs PWM that will help you interpolate the PWM required for a desired flow rate (e.g. 50% flow rate).

Below is an example of Rotations Per Minute of a 12V computer CPU cooler water pump for a given PWM input. It is assumed that this would be under load (of pumping water), but not stated explicitly.

Note that it may not be physically possible for the motor to operate with 10% or less PWM duty cycle. At this point I imagine that the internal friction of the motor and forces required to push the water along are greater than the force provided by a "10%" duty cycle.

Source: ekwb


How to store an RFID tag number in a string I want to send RFID tag number to PHP page. So far I have sent a fixed string to php and it worked, now I am not getting data in string when i scan rfid tag. I want to store every RFID tag number in a string when it is scanned, so that I can send it to php page.

if (rfid.isCard()) {

    String rfid_uid = "";
    if (rfid.readCardSerial()) {
        String rfid_uid = "";
        for (int i = 0; i < 4; i++) {
            Serial.print(rfid.serNum[i], HEX);
            rfid_uid = rfid.serNum[i];
        }

        Serial.println();
    }
    //delay(7000);
    Serial.print("User ID \n");
    Serial.println(rfid_uid);
    make_request(rfid_uid);
}

This is the path to php page

         String method = "GET /ethernet/data.php?rfid_uid=";

String rfid_uid = "";
if (rfid.readCardSerial()) {
    String rfid_uid = "";
    for (int i = 0; i < 4; i++) {
        Serial.print(rfid.serNum[i], HEX);
        rfid_uid = rfid.serNum[i];
    }

    Serial.println();
}

This code has multiple problems:

the variable rfid_uid is defined twice, they are overshadowing each other. The inner part only assigns a value to the rfid_uid delcared in the inside of the if statement, the outer rfid_uid will remain empty
As you can see with Serial.print(rfid.serNum[i], HEX);, the element rfid.serNum[i] is an integer, which is printed as hex. (e.g. 123 = 7B), in rfid_uid = rfid.serNum[i]; you however assign the direct numerical value, without converting it to hex

You can try the following, if you want the serial number as a 4 byte hex string:

String rfid_uid = "";
if (rfid.readCardSerial()) {
    for (int i = 0; i < 4; i++) {
        String uid_part = String(rfid.serNum[i], HEX);
        Serial.print(uid_part);
        rfid_uid += uid_part;
    }

    Serial.println();
}
//rest as before

This should construct a String object from the integer in HEX format and append (using the += operator it to the rfid_uid string). Thus, after 4 iterations, the String value is built up and can be used in the request.


Blend with SD Shield Building a data logging and transmission system here. I've a RedBearLab Blend with built-in BLE capabilities and a (cheap) SD / Data logging shield that looks very suspiciously like it's copied from the Adafruit one.

Using a Stock Arduino Uno board, the Data logging shield works out of the box - both RTC TimeSet and cardinfo come back successfully.

Stacking the shield on the Blend, both examples lead nowhere. The TimeSet states that no connection could be made, and the cardinfo says it can't find the card.

I assume it's a pin conflict of some sort, but I'm really unsure what I should do to debug/fix it.

[edit] As I found out below, the SD Module works now - but I still face the problem of not getting the RTC to work. Neither on the shield nor a Tiny RTC module. Again, both work fine on the Arduino Uno.

[edit2] I had basically the same problem for the RTC module as well - see the answer below.

Sometimes it helps just adding the tags.....

The Blend is a Arduino Leonardo Chip -
and as Lady Ada helpfully points out, you need a special SD Library to use this. The advice on https://learn.adafruit.com/adafruit-data-logger-shield/for-the-mega-and-leonardo is everything I needed to get the cardinfo working, especially the     while (!card.init(SPI_HALF_SPEED, 10, 11, 12, 13)) {
part.

Also, the I2C Pins for the RTC Clock are not the "standard" Analog Pins 4 and 5, but D2 and D3 (see http://arduino.cc/en/Reference/Wire)


Arduino Uno ADC behavior in free running mode I'm using my ATmega328P to sample an analog signal in free running mode. The ADC clock frequency is set to ÷128. I've read that a single analog conversion lasts 13 clock cycles. I would like to know if the number of clock cycles changes if I make the ADC trigger an interrupt after every conversion (ADIE bit set to one). Or will the ADC still use 13 clock cycles and start again on the 14th?

If ADIE is set to zero (no interrupts) will the result of the conversion still be written to ADCL and ADCH? And at what time of the 13 clock cycles is this result written to those registers? This is important to me so I can calculate how much time I have to read those registers.

Would it be possible to set ADIE to zero and instead use a timer interrupt to read ADCL and ADCH every ~1 millisecond. Or am I missing something important?

You may want to take a look at Amanda Ghassaei's tutorials on Arduino DSP techniques or the FFT/FHT code at the Open Music Labs. Both use the Arduino ADC in free running mode. Amanda's code uses interrupts, the Open Music Lab code sits in a tight loop waiting for the conversion to complete.

Based on the Open Music Lab code I can say, yes, the conversion is still written to ADCL and ADCH regardless of the interrupt setting in ADIE. I can't tell from your question how concerned you are about cycle counts, but I don't think you'd see a significant change using interrupts (I'd expect it to be zero). But using interrupts you'll take a hit as you enter and return from the ISR.

As I mentioned in the comment, take a look at Amanda Ghassaei's code. She toggles pin 12 which creates a spike in the trace if you have a scope attached to pin 12 (or a logic analyzer). That will give you a very easy way to determine the actual time to handle the conversion.


Should I control each of the four robot wheel separately or wire two from each side together? I am making a remote controlled Arduino robot. I has 4 DC motors for wheels. I have 2 motor drivers available that control two dc motors each. I was wondering what the downsides are of wiring 2 dc motors together. The DC motors are 6v and the maximum current per channel of my motor driver is 1.2A which should be plenty for the motors. The motor driver that I am using can be found here. Each motor is getting controlled using a PWM signal. The DC motors are controlled separately.

it looks like you have two channels on each controller, so you have some options here. but first I'm going to talk a bit about your motors. If you have a spec sheet for them you can gather most of this info through that, but it doesn't hurt to do some experimentation. A motor will draw max current when it is stalled (is trying to drive but it can't), and you can determine this "stall current" with a multimeter or from the spec sheet. when you're driving the robot, this can occur when you drive up to a wall and try to push through the wall (hint, no robot this size will damage a well built wall) but likely the driver will reach a wall and stop driving (unless she can't see the robot while driving, idk). the lowest current it will draw (aside from zero when it can't...) is it's "free speed" current, this is when it's spinning as fast as it can with no load on it. while you're driving the robot you can expect the current to be between these numbers, if you want to get super fancy (and you want to equip your robot to do this) you could log the instantaneous current every 10ms or however often (this can be useful if you want to diagnose faults, but again its a small robot)... so if you have two motors in parallel (which you want to do because in series one will drive harder than the other), then the current drawn by each will add, so you can double it for two motors.

anyways, here's a few options for the motor configuration:

if two of your motors in parallel draw less than continuous 1.2 amps, you could use a single controller for one robot, controlling left wheels on channel 0 and right on channel 1.

if your motors draw more than that in parallel, you will have to use two channels per side, however you could Y the PWM lines between the motor controller and the arduino

if you are using something like omni wheels and want control over every single wheel, obviously you will want one channel per wheel...


Error while uploading code to ESP8266 through Arduino Mega 2560 I am sorry for posting this question for the nth time but I am still not able to find a solution for this error.

I am trying to upload the WiFiScan(Arduino IDE example program)program code to ESP8266 using Arduino Mega 2560. I followed the procedure given here. And I tried uploading it with "Generic ESP8266 Module" and "Adafruit HUZZAH ESP8266" selected as the Board. But I am still getting the following error.

trying to connect
  espcomm_send_command: sending command header
  espcomm_send_command: sending command payload
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed

Edited to add:

Connections-

ESP8266 - Arduino Mega2560

Tx - Tx1(Pin 18)

Rx - Rx1(Pin 19)

Gnd - Gnd

Vcc - 3.3V (Directly from Arduino's 3.3V pin)

CH_PD - 3.3V (Directly from Arduino's 3.3V pin)

GPIO0 - Push button K2 (refer photo)

RST - Push button K1

While pressing the K2 button(Flash button - GPIO0), I clicked the K1 button(Reset button - RST) and then released K2. According to the document, this should bring the ESP8266 to flash mode. Now when I upload the code, it throws the above error.

After googling for several hours, I was able to figure out the reason. Thanks to this link. Transferring data to ESP8266 with Arduino acting as USB to Serial converter did not work. Using a USB to TTL converter, and following this link you can easily transfer data to ESP8266.


Tried to fix ports on Mac OS X Yosemite. Now nothing works I was having an issue very similar to this one:

Arduino compatible's serial port not showing Mac OSX

Basically I have a clone (VISduino) and it's made with a different USB chip so it needed a driver. Installing the driver didn't help.

http://kiguino.moos.io/2014/12/31/how-to-use-arduino-nano-mini-pro-with-CH340G-on-mac-osx-yosemite.html

Running:

 sudo nvram boot-args="kext-dev-mode=1"

didn't help. So I decided to delete Arduino and reinstall. Then I went through all of the steps again.

Well.... now nothing works. Before doing this I could use:

Adafruit metro
An uno clone
My genuine uno
lightBlue Bean
adafruit trinket and trinket pro
adafruit trinket pro via USB
digikey

I've reinstalled the drivers for these but NOTHING is working now. They were all working before. It just says Arduino Uno on COM1, or digikey on COM1 etc.

And of course my clone (vis duino) isn't working either.

How can I fix this?

The com ports just are not there.

I solved this issue by deleting all of the Arduino files and the Arduino app. I put my sketched folder aside but deleted all libraries.

Restarted the computer.

Installed Arduino fresh.

Restarted the computer.

Installed the drivers.

Ran the command.

Restarted the computer.

Restarted the computer.

Restarted the computer.

Then it worked.


SoftwareSerial together with AltSoftSerial and HardwareSerial The title says it all.

Angone with experience here on this subject?

I want to use all Hardware serial, SoftwareSerial and AltSoftSerial on Arduino Duemilanove with At328.

Is it possible?

in short - Yes. The following compiles and should work

Note the following links detail some subtle issues about HOW to use these various libraries. Some are more optimal depending upon your usage.

http://www.pjrc.com/teensy/td_libs_AltSoftSerial.html#speed

http://forum.arduino.cc/index.php?topic=152122.0;wap2

You might also want to consider just using either Alt or Soft.
Note that NewSoftwareSerial is incorporated in the IDE 1.5.5+

/*
  Software serial multple serial test

 Receives from the hardware serial, sends to software serial.
 Receives from software serial, sends to hardware serial.

 The circuit:
 * RX is digital pin 10 (connect to TX of other device)
 * TX is digital pin 11 (connect to RX of other device)

 Note:
 Not all pins on the Mega and Mega 2560 support change interrupts,
 so only the following can be used for RX:
 10, 11, 12, 13, 50, 51, 52, 53, 62, 63, 64, 65, 66, 67, 68, 69

 Not all pins on the Leonardo support change interrupts,
 so only the following can be used for RX:
 8, 9, 10, 11, 14 (MISO), 15 (SCK), 16 (MOSI).

 created back in the mists of time
 modified 25 May 2012
 by Tom Igoe
 based on Mikal Hart's example

 This example code is in the public domain.

 */
#include <SoftwareSerial.h>
#include <AltSoftSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

AltSoftSerial altSerial;
// AltSoftSerial always uses these pins:
// Board          Transmit  Receive   PWM Unusable
// -----          --------  -------   ------------
// Arduino Uno        9         8         10

void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(57600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  Serial.println("Goodnight moon!");

  // set the data rate for the SoftwareSerial port
  mySerial.begin(4800);
  mySerial.println("Hello, world?");
  altSerial.begin(9600);
  altSerial.println("Hello World");
}

void loop() // run over and over
{
  if (mySerial.available())
    Serial.write(mySerial.read());
  if (Serial.available())
    mySerial.write(Serial.read());

  char c;

  if (Serial.available()) {
    c = Serial.read();
    altSerial.print(c);
  }
  if (altSerial.available()) {
    c = altSerial.read();
    Serial.print(c);
  }
}


Will this buck converter power my arduino? I'm thinking of using something like this: https://www.amazon.ca/Dolity-Converter-Isolated-Switching-Transformer/dp/B07CSZ1174?SubscriptionId=AKIAILSHYYTFIVPWUY6Q&tag=duc12-20&linkCode=xm2&camp=2025&creative=165953&creativeASIN=B07CSZ1174

or this: https://www.amazon.ca/Voltage-Regulator-Converter-Transformer-Protection/dp/B07LC1C4ZZ?SubscriptionId=AKIAILSHYYTFIVPWUY6Q&tag=duc12-20&linkCode=xm2&camp=2025&creative=165953&creativeASIN=B07LC1C4ZZ

to power my arduino.

The reason for this is I have a contained box with a few pieces of equipment (all on ac power) controlled by an Uno. There is a single AC power cord (North American) running from the box to power the whole unit. Obviously this just leaves the Uno.

Sure the standard 5V barrel adapter prongs could be shrink wrapped to the raw AC wires but that's not very clean. I was imagining a module like those converters that could be wired into the VIN pin and gnd after converting the AC input from the main power line going to the box.

The uno is powering an ethernet shield, 4 port relay, sht20 sensor, mh-z16 sensor, and 16x2 lcd display.

Thoughts? Honestly this isn't really my call. My boss doesn't want any plugs or standard outlets inside the box. It's like he only wants it to be formal circuit boards and soldering. No shrink wrap or electrical tape. Yes I realize standard adapters that plug into a wall are already at a price that won't be possible to beat.

Sure the standard 5V barrel adapter prongs could be shrink wrapped to the raw AC wires but that's not very clean.

Also very deadly.  DO NOT DO THIS!!!!  The Arduino will explode (literally. I am NOT joking here!!!) and potentially electrocute you.

Those modules you show are not "buck" regulators. They are SMPS modules - an entirely different thing.

Yes, one of those would be suitable for powering an Arduino from a mains supply, but given your supposition above I rather suspect your skills and knowledge would make wiring it up a dangerous prospect.

Better would be to use a proper off-the-shelf power plug and have someone qualified install a suitable socket inside the enclosure.


A clarification needed about the HC-05 I have just got a new pair of HC-05 Bluetooth modules. I am working on a simple project. I'm trying to move two servo motors using two potentiometers. I followed a simple tutorial to move one servo, and it worked successfully.

How to make the same thing with 2 potentiometers and two servos?

UPDATE:

I have successfully managed to write down something that get to read values from two potentiometers, but I'am still facing problems with the slave part.
Can't figure out the problem.

(Master)

//Master
int potValuePins[] = { A0, A1 };
void setup() {
  Serial.begin(9600); // Default communication rate of the Bluetooth module
   for (auto pin : potValuePins) {
     pinMode(pin, INPUT);
   }
}

void loop() {
 for (auto pin : potValuePins) {
   Serial.write(pin); // Send the pin number
   Serial.write(analogRead(pin)); // Send the pin value with a trailing
 newline as a delimiter
   int value=analogRead(pin);
   Serial.print(" Pin is: ");
   Serial.print(pin);
   Serial.print("\t");
   Serial.print("Value is: ");
   Serial.println(value);
   }
 }

(Slave)

//Slave
#include <Servo.h>
Servo myServo1;
Servo myServo2;

void setup() {
Serial.begin(9600);
myServo1.attach(9);
myServo2.attach(10);
}

void loop() {
if (Serial.available()) {
 char input[3];
 Serial.readBytes(input, 2);
 int pin = input[0];
 int angle = input[1];
 Serial.print("the pin:");
 Serial.print(pin);
 Serial.print("\t");
 Serial.print("the angle:");
 Serial.println( angle);

 switch (pin) {
  case A0:
    myServo1.write(angle);
    break;
  case A1:
    myServo2.write(angle);
    break;
  default:
    Serial.println("Unknown value");
    break;
   }
  }
 }

Looking at the example you linked to, the "communication" between the two ends is just writing a (byte) value between 0 and 255, and reading that on the other end.

One simple (out of many possibilities) to extend this to handle a set of two is just to send 2 bytes in sequence, with the first byte being an identifier of which servo you are denoting.

Where the example master code shows:

// Reading the potentiometer
potValue = analogRead(A0);
int potValueMapped = map(potValue, 0, 1023, 0, 255);
Serial.write(potValueMapped); // Sends potValue to servo motor

You instead write:

// Reading the potentiometer 1
pot1Value = analogRead(A1);
int pot1ValueMapped = map(pot1Value, 0, 1023, 0, 255);
Serial.write(1);
Serial.write(pot1ValueMapped); // Sends pot1Value to servo motor

// Reading the potentiometer 2
pot2Value = analogRead(A0);
int pot2ValueMapped = map(pot2Value, 0, 1023, 0, 255);
Serial.write(2);
Serial.write(pot2ValueMapped); // Sends pot2Value to servo motor

And on the slave side, where the example has:

if (Serial.available() > 0) { // Checks whether data is comming from the serial port
  state = Serial.read(); // Reads the data from the serial port
}
// Controlling the servo motor
myServo.write(state);

You have to separate out the two possible choices:

if (Serial.available() > 0) {
  servo_num = Serial.read();
}
if (Serial.available() > 0) {
  state = Serial.read();
}

switch (servo_num) {
  case 1:
    myServo1.write(state);
    break;
  case 2:
    myServo2.write(state);
    break;
}

Note that you'll also have to declare the servo_num variable, and instantiate two of the Servo objects. The code above is just a guide.

The simple expansion above is not robust, as it's possible that the 2nd byte is not received by the time the 2nd Serial.read() is called, and then that byte would be caught next time around the loop() by the first Serial.read() call and you'd be out of sync. But hopefully, this shows the general concept of how to start developing a protocol that is more complex than just single values.

Edit: What's probably happening is the system is getting out of sync. As I noted, it's not a robust protocol, but I think you may now understand the idea.

You can re-map the servo values to go from 2-255, rather than 0-255, and set the servo_num to either 0 or 1. In the slave, if you get a number <2, then it's a servo selector, otherwise it's a servo value. but then you lose the ability to set the servo to 0 or 1.

Also, you may want to space out the master sending the values, as you are likely sending data faster than the servo could respond. You could put a delay(100) or something in the loop() function, or change your code to use a millis()-based state machine (see the "BlinkWithoutDelay" Arduino example).


Arduino function to fade from one RGB color to the next For my Arduino project I have a Neopixel RGB Strip with 72 LED's.

I can successfully change the colour of any of the LED's (at the moment I'm only setting the first one 0 for testing purposes) so I know my wiring isn't the problem here, it's my coding.

What I would like to do is be able to select a color and then another color and have the first color fade to the next color and so forth (much like the LIFX bulbs behave when using the iPhone application).

This is what I have at the moment:

I am logging output of all the variables to give you an indication of what's going on. I'm not 100% sure on where I'm going wrong or whether there's a much easier way to do what I'm after (I'm open to suggestions).

The function takes a parameter called command, which is a string separated by commas:

e.g. 255, 0, 0 (RED) or 0, 255, 0 (GREEN).

/*******************************************************************************
 * Function Name  : tinkerSetColour
 * Description    : Sets the strip with the appropriate colour
 * Input          : Pin and value
 * Output         : None.
 * Return         : 1 on success and a negative number on failure
 *******************************************************************************/
int Rstart = 0, Gstart = 0, Bstart = 0;
int Rnew = 0, Gnew = 0, Bnew = 0;

int tinkerSetColour(String command)
{
    sprintf(rgbString, "Rstart %i, Gstart %i, Bstart %i", Rstart, Gstart, Bstart);
    Spark.publish("rgb", rgbString);

    sprintf(rgbString, "Rnew %i, Gnew %i, Bnew %i", Rnew, Gnew, Bnew);
    Spark.publish("rgb", rgbString);

    // Clear strip.
    strip.show();

    int commaIndex = command.indexOf(',');
    int secondCommaIndex = command.indexOf(',', commaIndex+1);
    int lastCommaIndex = command.lastIndexOf(',');

    int red = command.substring(0, commaIndex).toInt();
    int grn = command.substring(commaIndex+1, secondCommaIndex).toInt();
    int blu = command.substring(lastCommaIndex+1).toInt();

    int Rend = red, Gend = grn, Bend = blu;

    sprintf(rgbString, "Rend %i, Gend %i, Bend %i", Rend, Gend, Bend);
    Spark.publish("rgb", rgbString);

    // Larger values of 'n' will give a smoother/slower transition.
    int n = 200;
    for (int i = 0; i < n; i++)
    {
        Rnew = Rstart + (Rend - Rstart) * i / n;
        Gnew = Gstart + (Gend - Gstart) * i / n;
        Bnew = Bstart + (Bend - Bstart) * i / n;

        // Set pixel color here.
        strip.setPixelColor(0, strip.Color(Rnew, Gnew, Bnew));
    }

    sprintf(rgbString, "Rnew %i, Gnew %i, Bnew %i", Rnew, Gnew, Bnew);
    Spark.publish("rgb", rgbString);

    Rstart = red, Gstart = grn, Bstart = blu;

    sprintf(rgbString, "Rstart %i, Gstart %i, Bstart %i", Rstart, Gstart, Bstart);
    Spark.publish("rgb", rgbString);

    return 1;
}

The problem is the colors are not fading between themselves.

Apologies if any of this is confusing. I can provide more information if necessary.

Here's the output selecting RED to begin with:

Rstart 0, Gstart 0, Bstart 0
Rnew 0, Gnew 0, Bnew 0
Rend 255, Gend 0, Bend 0
Rnew 253, Gnew 0, Bnew 0

Here's the output selecting GREEN directly afterwards:

Rstart 255, Gstart 0, Bstart 0
Rnew 253, Gnew 0, Bnew 0
Rend 0, Gend 255, Bend 0
Rnew 2, Gnew 253, Bnew 0

And then the output selecting BLUE after that:

Rstart 0, Gstart 255, Bstart 0
Rnew 2, Gnew 253, Bnew 0
Rend 0, Gend 23, Bend 255
Rnew 0, Gnew 25, Bnew 253

There is no delay in there. It will fade very quickly, add a delay e.g. 5ms with n = 200 for a 1 second fade:

int n = 200;
for (int i = 0; i < n; i++)
{
    Rnew = Rstart + (Rend - Rstart) * i / n;
    Gnew = Gstart + (Gend - Gstart) * i / n;
    Bnew = Bstart + (Bend - Bstart) * i / n;

    // Set pixel color here.
    strip.setPixelColor(0, strip.Color(Rnew, Gnew, Bnew));

    delay(5);
}

The other thing is your last value of n in the loop is 199, not 200, and thus Rnew etc don't have the correct final value. Change the comparison to be <= not <:

for (int i = 0; i <= n; i++)


Using Pro Micro without soldering pin I'm a total newbie. I bought a Pro Micro but I didn't know that it can't be used, if you don't solder things in his holes.
I found this picture on Google:

And it seems that exists those stuffs (green and white) to test the circuit before soldering.

Do you know where can I buy them? Or do you know their name?

Thanks.

Perhaps you are looking for items like these from from a well established seller adafruit.com.  However, what you are proposing is not cheap when compared to soldering.  I would recommend you learn soldering as it will likely be the way you want to assemble your final Arduino project.


Can I connect an RFID reader to the ICSP header? I am connecting an RFID reader to my Arduino mega.  The directions that I have found say that I need to use pins 50-53.  I also noticed that the ICSP header contains (what looks like) a secondary connection to these pins:

http://arduino.cc/en/Reference/SPI

Can I connect my RFID reader to the ICSP header:

Yes you can. However the SS isn't present on that header. You can however use any pin you want for SS (if the library you use supports it, that is)


trying to make wemos d1 code modular causes collect2: error: ld returned 1 exit status exit status 1 #include "connection.h"

void setup() {
  Serial.begin(115200);
  Funcs::Connect conn;
  conn.connectWifi();
}

void loop() {

}

then connection.h file:

// connection.h

namespace Funcs
{
  class Connect
  {
    public:
      void connectWifi();
  };
}

and then connection.cpp

#include <Arduino.h>
#include <ESP8266WiFi.h>
#include "connection.h"
const char* ssid     = "ssid";
const char* password = "password";

namespace Funcs
{

  void connectWifi() {
    // Connect to WiFi network
    Serial.println();
    Serial.println();
    Serial.print("Connecting to ");
    Serial.println(ssid);

    WiFi.begin(ssid, password);

    while (WiFi.status() != WL_CONNECTED) {
      delay(10);
      Serial.print(".");
    }
    Serial.println("");
    Serial.print("WiFi connected with ip ");
    Serial.println(WiFi.localIP());

  }
}

On compiling I get this error:

/Library/Arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/HardwareSerial.h:76:
undefined reference to `Funcs::Connect::connectWifi()'

collect2: error: ld returned 1 exit status

collect2: error: ld returned 1 exit status
exit status 1
Error compiling for board WeMos D1 R1.

But I do not have Funcs::Connect::connectWifi() in my code, it was in old code.

You are calling Funcs::Connect::connectWifi() right here:

conn.connectWifi();

since conn is of type Funcs::Connect

But you defined a function Funcs::connectWifi():

namespace Funcs
{

  void connectWifi() {

where I think you meant to have connectWifi be a member of that Connect class.

namespace Funcs
{

  void Connect::connectWifi() {

That's not the only issue with your code, you also create the instance in setup and let it go out of scope after calling just the one function.  But that's a different kind of error.  It's legal code, just probably doesn't do what you want.


What is the voltage between Vin & GND? I have NodeMCU ESP8266N Lolin V3, my 5V relay is powered from Vin of the NodeMCU.
The NodeMCU is powered from 5V USB.

My difficulty is when I measure voltage between Vin & GND, it is of 1.9V, but supposed to be around 5V as it is directly attached with usb 5V supply. Actually my relay is not working with the power tapped from Vin, but relay's led & NodeMCU  led are blinking but relay coil does not trip.
Please confirm is my NodeMCU having problems as voltage between vin & GND read 1.9V.
https://drive.google.com/file/d/1Z6jYX4sCLmRxnWbtBYZCNW6LpckokaC9/view?usp=drivesdk

The voltage on Vin when you power that board thru USB is not relevant ... Vin is not the pin you are looking for

You clearly have a Lolin NodeMCU (V3) board - the existence of Gnd and VU (looks like VV in your picture!!) between A0 and S3 pins indicates that

In documentaion easily found by searching for Lolin V3 pinout - VU is described a USB power output

Use this pin to connect to JD-VCC on the relays

I've just now successfully done this with a 4 relay board

I would connect (nodemcu -> relay)

3V3 to VCC
VU to JD-VCC
Gnd to Gnd
Dn to INm - i.e. choose a D pin on the NodeMCU and connect to an IN pin on the relay


arduino mega buzzer output I have project by Arduino mega which have 22 inputs and 22 outputs and buzzer reset and output reset pushbuttons , it have two status

if the input is high(not continuous ) the output will on and the buzzer will be on, if  output reset pushbutton is pressed  the output will off , if buzzer reset pushbutton  is pressed the buzzer will off.
if the input is always high (continuous high signal on input ) the output will on and the buzzer will be on, in this case we will not reset the output even if the output  reset pushbutton is pressed , and we will be able to reset the(turn off) buzzer by the  buzzer reset pushbutton, and wait until  input state to change to high again to repeat procedure

help me with editing my code

    //int input[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,23,24}; //input pins (23 for reset ,24 for buzzer reset)
//int output[] = {26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 24, 34, 44, 45, 46, 47, 48,49}; //output pins (49 for buzzer)

int in1 =     2;

int in25 =   26;// for output reset
int in26 =   27;// for buzzer reset

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

int out1 = 28   ;

int out24= 51   ;
int out25= 52   ; // output for buzzer

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

int buttonState1 =  0;

int buttonState24 =  0;
int buttonState25 =  0; //for  reset
int buttonState26 =  0; //for buzzer reset

//unsigned long previousMillis = 0;        // will store last time buzzer was updated
//const long interval = 10000;           // interval at which to buzzer (milliseconds)
//int buzzerState = LOW;             // buzzerState used to set the buzzer

void setup() {

  pinMode(in1 , INPUT);

  pinMode(in24 , INPUT);
  pinMode(in25 , INPUT);
  pinMode(in26 , INPUT);

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

pinMode(out1, OUTPUT);
pinMode(out2, OUTPUT);

pinMode(out24, OUTPUT);
pinMode(out25, OUTPUT);

digitalWrite(out25, LOW); // buzzer LOW

}

void loop() {
  buttonState1 = digitalRead(in1);
  if (buttonState1 == HIGH) {
    digitalWrite(out1, LOW);
    //digitalWrite(out25, LOW);
    //delay(10000);
    //digitalWrite(buzzer, LOW);
  }

  buttonState25 = digitalRead(in25); //read reset button state from input (25) pin 26
  if (buttonState25 == HIGH )

  {
    digitalWrite(out1, HIGH); //reset out1
    //digitalWrite(buzzer, LOW);
  }

  //else {
   // buttonState26 = digitalRead(in26); //read the buzzer reset button state from input (26)pin 27
   // if (buttonState26 == HIGH) {
    //  digitalWrite(out25, HIGH);

   // }
  //}

    //   while (digitalRead(input1) == HIGH);
    //digitalWrite(buzzerrelay, LOW);

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

 buttonState2 = digitalRead(in2);
  if (buttonState2 == HIGH) {
    digitalWrite(out2, LOW);
   // digitalWrite(out25, LOW);
    //delay(10000);
    //digitalWrite(buzzer, LOW);
  }

  buttonState25 = digitalRead(in25); //read reset button state
  if (buttonState25 == HIGH )

  {
    digitalWrite(out2, HIGH); //reset the output
    //digitalWrite(buzzer, LOW);
  }

 // else {
  //  buttonState26 = digitalRead(in26); //read the buzzer reset button state
    //if (buttonState26 == HIGH) {
    //  digitalWrite(out25, HIGH);

    //}
 // }

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

  //  }
 // }

  }

Any time you have the same sequence of code repeated over and over with slight variations, that is a "code smell" (an indication that you may be using the wrong approach.)
You should use arrays of pin numbers as you have in the first couple of commented-out lines, and write code that loops through those arrays, as well as functions that take parameters and can do the same thing using different values that are passed in.
Don't try to tackle a problem like this without learning the skills and concepts you need. You said "...I am new to Arduino and arrays , and now I'm focusing on solving buzzer problem." That is a mistake. Code like you have posted is hard to write, hard to read, and much harder to maintain.


UNO R3 + WiFi ATmega328P+ESP8266 (32Mb memory) USB-TTL CH340G For Arduino Uno - External ESP8266 Pins This board have pins to ESP8266's GPIOs.
What is Tout pin ?
On the back of the board it label pins :GPIO12, GPIO02, and another GPIO02 ? a continuity test shows that they are not connected. So what is it ?

From esp8266 datasheet:

TOUT - ADC pin. It can be used to test the power-supply voltage of VDD3P3 (Pin3 and Pin4) and the input power voltage of TOUT (Pin 6). However, these two functions cannot be used simultaneously.

from the pinout PDF of the Uno+WiFi board:


esp_partition_get_sha256() mismatches PHP's hash() function in HTTPUpdate Disclaimer: It may be that this question belongs to a PHP forum instead of this one. However, this question is also very ESP32/Arduino related. Please correct me if this is the case.

The scenario:

Implementing self-update routines for my ESP32 project, using HTTPUpdate
Using a server-side PHP script to decide which binary image to serve to the device, or return HTTP 304 return code if no updates available.
Using the sketch's MD5 and SHA-256 hashes provided by the HTTPUpdate library as request headers, server-side, to check binary version.

The problem:

The MD5 hash contained in the request header "x-ESP32-sketch-md5" is the same as the MD5 hash calculated by a simple md5() call using the raw binary for the currently running version.
The SHA256 hash contained in the request header "x-ESP32-sketch-sha256" is not the same as the hash obtained by calling PHP's hash("sha256", $v) (where $v contains the same raw binary).

Example:

MD5 (HTTPUpdate): c93d814989b53a24a0164e561b6a8bf8
MD5 (PHP): c93d814989b53a24a0164e561b6a8bf8 (no difference)
SHA256 (HTTPUpdate): 5634674253E095600CD863A34287FCA742BCFCF9B5BF409870DD65AF0ADEF7A0
SHA256 (PHP): 1ECDDF3215520C79AAD13BBC1D116D9286910490DF316B9B203FCBFC89CBCCC2 (different)

Am I doing something wrong?

Note: The esp_partition_get_sha256() function is called internally by the update() method of the HTTPUpdate library.

PHP Code (for calculating the hashes):

<?php

$v = file_get_contents("fw.bin");

print("MD5: ". md5($v)."\r\n");
print("SHA256: ".hash("sha256", $v)."\r\n");

Arduino code (the relevant part):

// Called once or twice a day
void update_fw()
{
    Serial.println("Checking for updates...");

    t_httpUpdate_return ret = httpUpdate.update(client, "http://my_server/fw/check_fw.php");  // For now it only logs the headers and returns HTTP 304 code

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

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

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

PHP code (logs headers and returns HTTP 304 code):

<?php

$headers = getallheaders();

if (!file_exists("log.txt"))
{
    file_put_contents("log.txt", print_r($headers, true));
}

http_response_code(304);            // No updates.

exit;

Thanks in advance.

Your problem stems from a misunderstanding of what the functions are doing.

Your MD5 hashes are the hash of the binary file itself. And so they match.

Your PHP SHA256 is the hash of the binary file (like the MD5), but the ESP's SHA256 is not.

The file itself contains an SHA256 hash of the content of the file, not the whole file.  The function esp_partition_get_sha256 merely returns that SHA256 hash.

According to the SDK documentation:

  For apps with SHA-256 appended to the app image, the result is the appended SHA-256 value for the app image content. The hash is verified before returning, if app content is invalid then the function returns ESP_ERR_IMAGE_INVALID. For apps without SHA-256 appended to the image, the result is the SHA-256 of all bytes in the app image. For other partition types, the result is the SHA-256 of the entire partition.

If you were to take the binary file and somehow strip off the extra sha256 information and then perform a hash of the results you should (theoretically) get the same hash, which would be the same has as is contained within the file itself.


Reading from SPIFFS - What's the best way to deal with a string (or char) array with undefined length? I've read that it's best to avoid using String in Arduino so I'm ready to use a char array if it's better.
I'm reading the file names from an SD Card and my goal is to store them in an array and then be able to read that array. What I'm currently doing is:

String lib_arr[100];
int lib_arr_size;

and then

File dir = SD.open("/");
int c = 0;
while (true) {
  File entry = dir.openNextFile();
  if (!entry) {
    // If no more files
    lib_arr_size = c - 1;
    break;
  }
  if(strcmp(entry.name(), "SYSTEM~1") == 0) {
    continue;
  }
  lib_arr[c] = entry.name();
  entry.close();
  c++;
}

and then

for (int i = 0; i < lib_arr_size; i++) {
  if(i == pos) {
    tft.print("> ");
    tft.println(lib_arr[i]);
  } else {
    tft.println(lib_arr[i]);
  }
}

This is not a solution because, for my purposes, the String lib_arr[100] can be 1000 or 10000 or 100000... and I found out that by increasing that value the global variables use skyrockets and Arduino says that it's out of memory. My goal is memory optimization. I don't know how to go about this problem.

Well, you cannot use more memory than you have. If the length of file names is (probably/possibly) too much, you just cannot store it in memory. Some alternatives:

Use some compression... This will save you a bit, but at the end if you don't know how much the maximum bytes you need to store is, it will not help much
Use external SRAM memory... You need to write your own memory functions. Also a slight performance hit.
Use SD card memory... As SRAM, but much slower. Also not sure if you can use the same SD card to write on.
The best solution, but could be a big performance hit, is not to store at all the file names, but go through the file names and process what you need along the way. This is not always possible or feasible though. In your solution you can print the file names directly without storing (but I guess you want to do some additional processing).


sro4m-2 waterproof ultrasonic sensor I bought this waterproof ultrasonic sensor about 5 of them with the part number SR04M-2 Written on the PCB silkscreen Which is different from the usual SR04t-0.2, they are just not working, I don't know if its using a different communication protocol or its faulty because no output is coming out of the sensor at all.
if anyone out there has ever came across this type and was able to walk his/her way around it should help

I found this code for the SRF05 and it works for the SRO4M-2 as well.
Good Luck!
const unsigned int TRIG_PIN=13; //RX
const unsigned int ECHO_PIN=12;  TX
const unsigned int BAUD_RATE=9600;

void setup() {
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  Serial.begin(BAUD_RATE);
}

void loop() {
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);

  const unsigned long duration= pulseIn(ECHO_PIN, HIGH);
  int distance= duration/29/2;
  if(duration==0){
    Serial.println("Warning: no pulse from sensor");
  } else {
    Serial.print("distance to nearest object:");
    Serial.println(distance);
    Serial.println(" cm");
  }
  delay(100);
}


ESP8266 light sleep - can't wake up I am attempting to implement a light sleep mode on an esp8266 (feather huzzah) which, when a button is pressed, wakes the system up so that it can continue its normal task.

I cobbled together some code from this post, which I've slightly modified:

#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#define WAKE_PIN 5

extern "C" {
    #include "gpio.h"
}

extern "C" {
    #include "user_interface.h"
}

void setup(){
    Serial.begin(115200);
    Serial.println("Setup");

    pinMode(WAKE_PIN, INPUT_PULLUP);
    gpio_init(); // Init GPIO pins
}

void loop(){
    Serial.println("Do something...");
    Serial.println(digitalRead(WAKE_PIN));
    delay(500); //random delay for that stuff to be done

    if(!digitalRead(WAKE_PIN)){ //if we don't detect pin, sleep
        sleep();
    }
    delay(1000);

}

void sleep(){
    Serial.println("Going to sleep...");
    delay(10);
    wifi_fpm_set_sleep_type(LIGHT_SLEEP_T); // set sleep type
    gpio_pin_wakeup_enable(GPIO_ID_PIN(WAKE_PIN), GPIO_PIN_INTR_LOLEVEL);  //LO OR HI?
    wifi_fpm_open(); // Enables force sleep
    wifi_fpm_do_sleep(5000); //Sleep for short time
    delay(100);
    Serial.println("Woke up!");
}

Here is how I have things wired:

So the setup function works as expected, as well as "do something". The button reads high (1) when it is unpressed, and when I push it, it reads low (0) - which sends the ESP to sleep. In the serial monitor, I see:

Going to sleep...
Soft WDT reset

ctx: cont
sp: 3ffef7a0 end: 3ffef9a0 offset: 01b0

>>>stack>>>
3ffef950:  0001260d 00000600 3ffee970 4021fc84
3ffef960:  00001388 402020ba 402020b1 402020a1
3ffef970:  00000000 00000000 3ffee944 40202115
3ffef980:  3fffdad0 00000000 3ffee968 402027d4
3ffef990:  feefeffe feefeffe 3ffee980 40100710
<<<stack<<<

 ets Jan  8 2013,rst cause:2, boot mode:(1,6)

 ets Jan  8 2013,rst cause:4, boot mode:(1,6)

wdt reset

I'm not very experienced with Arduino or Electric Engineering, so I'm not exactly sure what is happening vs. what should happen, but this is my interpretation:

I read somewhere that reset causes are as follows:

reset causes:
    0:
    1: normal boot
    2: reset pin
    3: software reset
    4: watchdog reset

boot device:
    0:
    1: ram
    3: flash

In which case, if soft reset is considered light sleep for the esp, then the rst cause:2 is expected behavior, as it means it was triggered by pin 5. The rst cause: 4 i'm not sure about though - watchdog reset. Seems to be a protective mechanism for the device, in which case maybe the reset of this must coincide with the reset triggered by sleep mode and is normal? Or does it indicate a crash? In any case, I have no idea what all the stack stuff is, but the system does not restart - I cannot get any further readings from the serial monitor after this.

I'm not sure whether GPIO_PIN_INTR_LOLEVEL should be high or low - I couldn't find documentation on this (though I did see it in the [GPIO header source file] on git.5

I read something where someone else had a similar problem and someone made a reference to adding resistors and making sure GPIO 0 should be high, and 15 should be low. The link they posted was dead, but it made me think of something I read about deep sleep, in which you have to wire RST to 0. I actually tried running a wire between RST and holding to the #0 pad that's right by the USB port on the feather huzzah, and after that, the code would actually go to sleep, then wake itself up automatically and resume the normal loop function - but what I want is for only the button to wake up the ESP.

I'm stuck from here. Anyone have any ideas of what might be happening and how to fix it?

You can make the ESP8266 wake from deep sleep by just pulsing RST low briefly. Crudely you can just use your switch to connect it to GND perhaps with a pullup resistor to +v. If you want to be a bit more elegant you could use a small capacitor to smooth out the switch bounce so your code only restarts once. I use this on an ESP8266 that is solar-powered. Most of the time it is in deep-sleep. It wakes up, connects to MQTT and deep sleeps again only when the sensor it is monitoring changes state.


Mkr1000 Wifi Configuration Is there a package similar to esp8266 WifiManager that supports wifi configuration for Arduino mkr1000?
I have searched everywhere and I got nothing

I'll release a new WiFiManager_Generic_Lite, with functionality similar to WiFiManager_NINA_Lite, to provide support specifically to MKR1000 using WiFi101, as well as other generic boards (nRF52, SAMD, SAM-DUE, STM32, Teensy, AVR, etc.) using generic WiFi Shields (AT-command, WiFiNINA, etc.) within several days.
Please hold on,

The new library has just been released : WiFiManager_Generic_Lite in GitHub as well as Platform.io WiFiManager_Generic_Lite in PIO.
The following 2 examples are created specially for you to use and test

MKR1000_WiFi101
MKR1000_WiFi101_MQTT

Please test and post your feedback here. Post issues, certainly many with this new library, on WiFiManager_Generic_Lite issues
Cheers,


How to interface arduino nano with sim900A? I have arduino nano and sim900a modem.

Rx(pin30) and Tx(pin31) pins of arduino shows 3.8VDC respectively and Rx and Tx of SIM900a shows 3.6VDC and 2.8VDC respectively. Could i connect the SIM900a modem directly to the arduino? Since Should i use level shifter between arduino TX(3.8v) and SIM900A modem(3.6v)? Any suggestions?

Thanks..

The bottom of your board shows a chip that gives every hint of being a charge-pump logic-level to RS232 inverting level shifter, to translate from the SIM900A's levels to the RS232 D-Sub connector.

It would appear that the 3 pin header just inside the D-sub would allow you to communicate at these levels.

However, a quick look at the SIM900A docs I could find suggests that these logic levels may be 2.8v, NOT 3.3v, and 3.3v is actually outside absolute maximum rating!

Essentially, you have two problems:

You need to drive and read signals with 2.8v logic, either by modifying your arduino to run at that voltage, or by using a level shifter.  It's possible that a resistor would protect the SIM900A, but that is going to be the most expensive component and so short of finding solid evidence of input protection diodes I'd be more hesitant to do that here than I would in other cases.
You need to make the level shifter not drive a signal into the SIM900A, so you don't fight with it.  You could do this by looking in the documenation (if any) for your board and seeing what accommodations they made for this, looking up the level shifter's  data sheet and finding the enable pin, or merely desoldering it.

Another option would be to make your Arduino talk at RS232 levels using its own shifter board.

Finally, there's a sort of hackish option:  Connect the transmit data from the SIM900A to a 3.3v Arduino, but connect the transmit from the Arduino through a simple inverter (tinylogic, whatever) to the RS232 receive pin.


How to convert RGB values to Intensity I made an arduino color sensor with tcs3200 and arduino uno. I have coded the arduino to find the RGB values when I place the color paper below the sensor. How can I derive the intensity using the RGB values.

There is no simple way to have a formula from the RGB values to intensity.
Also, there is intensity that can be measured with an intensity meter/sensor, but what people (humans, or each individual) consider more intensity (perceived intensity) is not fully related.
However, some things I found when I had a similar problem:

Typically a LED value of 0 is OFF, 1 is shining a little and 255 a lot. However, the difference in (perceived) intensity between value 1 and 10 is much higher than between e.g. 100 and 255.
Also, each LED color has a different intensity, e.g. red seems more bright than blue or green, with the same R, G or B value for the DMX lights I have, as can be read from the remarks from Duncan C and Majenko below, red is less bright than others.
Also, it depends on the physical device probably (it could have an internal algorithm to convert an RGB value to some power driven to the LED(s)).

What you can do is measure for each value and color the intensity with an intensity meter or sensor.
Or, in case you are more interested in the perceived intensity, manually check two LEDs with values to and create your own intensity algorithm.
I ended up having 3 arrays (for R, G, B), having for each value from 0-255 an 'intensity' value. I did it partly by measuring, partly by manually checking.


Parallel connection to Wiegand 26bit RFID readers I have situation where I need to read RFID cards. There is already installed Roger security system, Roger gate control board and two rfid readers in parallel. By default board and RFID readers communicate in RACS(some sort of coded protocol) but at the moment system is configured to communicate in Wiegand26. Earlier I used chinese wiegand26 reader with Arduino with no problem.

With Arduino I need to read card read by RFID readers.
Then I process data and make HTTP POST request.
Arduino is supplied from Roger board ~13.5V DC I do not get anything in arduino, even if I connect RFID readers directly to arduino.

CLK is D0 to Arduino Nano pin 2
DTA is D1 to Arduino Nano pin 3

This question is not related only to Arduino.

I want to ask is it possible to do? To read data maybe I need some additional electronics?

What i also noticed that when Arduino is connected in parallel the Roger board not always reads the card from RFID readers.

Roger PR402-BRD
And two readers PRT62LT

This is copy of Electronics.stackexchange

It looks to me like the Wiegand interface is an open-collector interface (like I2C), which is why they can be wired in parallel like that.

As long as the Arduino has both connections set to INPUT (not INPUT_PULLUP and certainly NOT OUTPUT) it shouldn't interfere at all.

By the way, for Wiegand, the two signals are DATA0 and DATA1.  To transmit a 0 the DATA0 line is pulled low. To transmit a 1 the DATA1 line is pulled low.

You should also check that the idle voltage on the lines is indeed 5V as it should be.  Anything more than that could cause the Arduino to chip the voltage to 5V through its internal ESD protection diodes.

Also you must ensure that the Arduino has its ground pin connected to the ground connection of the Wiegand system (which it should be since you are powering it from that).


How to read sound sensor readings and light up sensor with water sensor if the readings is above threshold & when water is detected for 2 mins? I am student that is new to Arduino and working on a project to trigger an alert if the sound level detected exceeds the threshold for a period of 2 mins. But I am stuck, would like to check how do I write a code to analog read sound sensor input and light up sensor if the readings is above datum for 2 mins? I had simple code but it triggers the light up immediately. :/

I have combined the coding together and this is the new code that worked with the help gotten:

    #define led 4 // led to D4
const int soundsensor= A0; //sound sensor to A0
const int threshold= 100; // to set the threshold value for sound sensor
int ssanalogread; //name of sound sensor analog read
bool wasOver;//add to globals
unsigned long firstDetect;

void setup() {
  Serial.begin(9600);
  pinMode(led,OUTPUT);
  pinMode(soundsensor,INPUT);// to get input from sound sensor

} // end void setup

void loop() {

     sound1();

} // close void loop

void sound1() {

  ssanalogread=analogRead(soundsensor); // reads analog data from sound sensor
  Serial.println(ssanalogread);

   if ((ssanalogread > threshold)){ //replace if else
      if(!wasOver){
       firstDetect = millis();
   }
   if(millis() - firstDetect > 1*10*1000){
      digitalWrite(led,HIGH); //turns led on if the sensor reads more than threshold
   } //end if
      wasOver = true;
   } // end first if
  else {
     wasOver = false;
     digitalWrite(led,LOW);
  } // end else

} //end loop

//this code works and is ok to run. can adjust the timing

You set a timestamp when the sound first exceeds the threshold and only set the output high when millis() - firstDetect > 2*60*1000

//add to globals
bool wasOver;
unsigned long firstDetect;

//replace if else
if ((ssanalogread > threshold)){
   if(!wasOver){
       firstDetect = millis();
   }
   if(millis() - firstDetect > 2*60*1000){
      digitalWrite(led,HIGH); //turns led on if the sensor reads more than threshold
   } //end if
   wasOver = true;
} else {
   wasOver = false;
   digitalWrite(led,LOW);
}


Arduino and Raspberry Pi - initiate I2C communication as slave I would like to interconnect Raspberry Pi and Arduino over I2C.

RPi will act as MASTER while Arduino is SLAVE.

I understand that I2C is designed that only master can send messages to slaves and then wait for responses.

I have sensor connected to Arduino, Arduino check periodically sensor value. My intent is, when sensor value exceed defined limit, inform RPi - send message to it. I want RPi as MASTER, because it also can query Arduino anytime. Can I start communication as SLAVE device?

Is it possible somehow? Do I need to use different bus than I2C?

You need to use a separate signalling method to alert the Pi that a sensor value is ready to be collected.

This is usually done using an interrupt signal. Your Arduino changes the state of a GPIO pin which is connected to a GPIO pin (through suitable logic level translation as necessary) on the Pi. When the Pi sees that pin change state it requests the data from the Arduino.

It is most common to have the transition from HIGH to LOW as an interrupt signal (aka Active Low) since that allows a simple wired-OR arrangement (open drain GPIOs with a pullup resistor) to allow more than one device to raise the same interrupt.


Arduino-compatible micro-controller with both I2C and CAN I am looking for a controller that works with Arduino (i.e. there is official or third-party support for the controller in the Arduino IDE and core libs) and has both built-in CAN and I2C buses. I was looking at the ATMega automotive series (16M1, 32M1, 64M1, 32C1, 64C1) but it does not mention I2C/TWI in the datasheet at all.

(I know I can bitbang I2C, I know there is MCP2515 for CAN over SPI.)

Thanks!

EDIT: The application in mind is a bridge between a few I2C sensors and CAN, no complex logic. High performance is not necessary, plus it will drive costs upwards.

Many options come to mind:

Bluepill board
Literally any board with I2C and CAN buses from the STM32 series, as searchable on their website (https://my.st.com/content/my_st_com/en/products/microcontrollers.html)
ESP32

A Bluebill board is programmable with mbed, STM32HAL (CubeMX) and Arduino, all of which have either CAN libraries for the CAN peripheral or have it even built-in in the OS (mbedos).

The Bluepill board is extremely low cost ($1.81 with free shipping from aliexpress) and features an STM32F103C8 microcontroller with 128kB Flash and 20kB RAM. Its peripherals include two I2C and one CAN bus.

Infos & Datasheet: http://www.st.com/en/microcontrollers/stm32f103c8.html, http://wiki.stm32duino.com/index.php?title=Blue_Pill

For flashing and debugging the chip you should have one cheap ST-Linkv2 clone (~3$ from china).

For programming environments you can use:

Arduino IDE (STM32Duino Arduino Core for STM32F1/F3/F4 chips: http://wiki.stm32duino.com/index.php?title=Boards_Manager_package)
PlatformIO, more general purpose and more powerful (https://platformio.org:443/boards?count=15&filter%5Bmcu%5D=STM32F103C&page=1&sorting%5Bname%5D=asc)

As frameworks you can use:

Arduino (see above)
ARM mbedos (builds upon STM32HAL, natively supported by PlatformIO)
STM32HAL (e.g. with project files for an IDE generated by STM32CubeMX)

Documentation references:

https://os.mbed.com/docs/v5.8/reference/can.html
https://www.st.com/resource/en/user_manual/dm00154093.pdf (Chapter 8)
https://github.com/Locoduino/Commanders

8 Bit microcontrollers from STM8AF series have a few micros with 1 I2C and 1 CAN bus: See http://www.st.com/en/microcontrollers/stm8af-series.html?querycriteria=productId=SS1583

Ready buyable evaluation board: http://www.st.com/en/evaluation-tools/stm8a-discovery.html (you want the STM8AF5288 one)

The toolchain changes then, of course. See https://my.st.com/content/my_st_com/en/extended-query.html?querycriteria=productId=LN1759$$associatedTo=SS1584


Arduino self programming I have noticed that some atmel chips can do "self programming" and I'm doing a hobbyist project where I need to change the "setting" of my arduino without code-reuploading through Arduino IDE.

Is it possible to do that ?
If it's possible. Please give me some basic though about how to do it.

Thanks in advance !

There are two areas of non-volatile storage in an Arduino: Flash and EEPROM.

Flash is where your program and constant values are stored. Variables with default values also have their default values stored in Flash.

EEPROM is a much smaller area with no real fixed purpose - you can store whatever values you want in there.

Flash can only be written to by code that is in the bootloader area of flash. This is important. A program cannot modify itself. Only the bootloader can modify a program - and then only in chunks ("pages"). It has to erase a whole page before it can write data to it.

The reason why you can't modify Flash from your main program is simple: Flash is the only place code can be executed from. If you erase the page of flash that contains the code that is programming the Flash then everything dies. Horribly. So it's stopped in its tracks by not allowing it to happen in the first place.

EEPROM, conversely, can be written to by anything - the bootloader or the main program. And on top of that individual values can be modified at will - no need to erase pages.1

So to answer the question behind your question ("How can I store and modify settings?"): it's quite simple - store them in EEPROM.

The IDE has examples of how to use the bundled EEPROM library, and there are more details in the Arduino reference manual.

1: Some systems don't have EEPROM, so they emulate it using Flash. These systems still have to erase the Flash in pages, but they try to do it transparently. Some (such as the ESP8266) use a commit() method to update a batch of values. Others, such as chipKIT boards, use wear levelling and separately indexed writing to reduce the need to erase pages.


Serial.read() is getting a whole string rather than just a character? From the arduino documentation, the Serial.read() function is supposed to return a single character at a time from incoming serial messages. So if I program the arduino with the following:

#include "SPI.h"

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

void loop() {
  if (Serial.available() > 0) {
    char data1 = Serial.read();
    Serial.print(data1);
  }
}

And I open the serial monitor and send "Hello, World!" I would expect the received message to be the individual characters printed one at time but instead I get back the whole message. So what gives? What am I not understanding?

You only think it is a string, it actually returns character by character. You can know by adding something like a delay after you Serial.print(). What the program actually does is that it receives one character each time you type one and it prints it, then the void loop repeats.


Audio Visualizer (not working properly) Parts

Arduino Uno R3 (Atmega328 - assembled)
Adafruit Bicolor LED Square Pixel Matrix with I2C
Backpack
Electret Microphone Amplifier - MAX4466 with Adjustable Gain
Half-size Breadboard
Breadboarding wires

Description
I have been following the build guide for the "Piccolo Music Visualizer" on the Adafruit website (https://learn.adafruit.com/piccolo?view=all), using all of the same components and code (following the guide exactly as shown). I first tested the 8x8 matrix to see if it was working properly, and it works beautifully. The problems started when I wired up the electret microphone...

In regard to how I wired this to the breadboard, I followed the example for the R3 on the Adafruit guide (since that's my current version):

Note
The files (code) used for this project are found here: (https://github.com/adafruit/piccolo). The ffft file is supposed to be saved to the library (this worked for me). The Piccolo file is supposed to be saved to the Sketchbook (this did not work for me - kept giving error messages when trying to reference it). I instead copied the code found in the Piccolo file, and saved it as a new sketchbook file. Let me know if this might be the cause of the problem. This is my first arduino project, so I am still trying to figure out how the IDE works.

Problem
The electret microphone is supposed to pick up audio and the LED matrix should display a waveform based on the loudness and frequency of the audio. Instead, I only have 2 bars on the bottom left lighting up (the effect is static - wont respond to volume or frequency changes). Oddly, when pulling out the microphone from the breadboard, the waveform begins displaying as it should, but in a glitchy/unstable form. I figured the problem was with the adjustable gain on the microphone, but no matter how much I adjust the screw only the 2 bars are affected and still static (when adjusted to the left only green LED, in middle is green and orange, to the right is red/orange/green on the matrix).

A little confused as to what the problem could be... is the microphone broken, code malfunctioning, wiring incorrect, etc.

Pictures to reference (DropBox link):
- See comment below for link (must have 10 rep to use more than 2 links in post)
(zip file contains 3 pictures: "wiring", "when_on", "pulling_out_mic")
Photos are over 2MB so I couldnt upload here.

It sounds like a dry joint; the fact that the LED matrix seems to work 'better' when you're fiddling with the microphone board makes me think that the problem lies entirely with that little board.

Try adding more solder; the more the merrier.


ArduinoJSON: Using a reference to a reference when parsing array of arrays I started to play around with the ArduinoJson library to parse data I got from one of my APIs (the format of the JSON data I get from my API can be improved for sure, but the software I had to implement the API with is rather limited in formatting JSON strings). The data is formatted as an array of arrays like this:

[["P101","1.2345","bar(a)"],["P102","1234.567","mbar"],["P103","2345.678","mbar"],["P104","2.3456","bar(a)"]]

In order to get a first impression about how much memory is needed I used ArduinoJSON's Assistant to analyse my dataset, calculate memory requirements and get a very basic code snippet for parsing the data. Code snippet generated by the assistant is as follows:

const size_t bufferSize = 4*JSON_ARRAY_SIZE(3) + JSON_ARRAY_SIZE(4) + 90;
DynamicJsonBuffer jsonBuffer(bufferSize);

const char* json = "[[\"P101\",\"1.2345\",\"bar(a)\"],[\"P102\",\"1234.567\",\"mbar\"],[\"P103\",\"2345.678\",\"mbar\"],[\"P104\",\"2.3456\",\"bar(a)\"]]";

JsonArray& root = jsonBuffer.parseArray(json);

JsonArray& root_ = root;

JsonArray& root_0 = root_[0];
const char* root_00 = root_0[0]; // "P101"
const char* root_01 = root_0[1]; // "1.2345"
const char* root_02 = root_0[2]; // "bar(a)"

JsonArray& root_1 = root_[1];
const char* root_10 = root_1[0]; // "P102"
const char* root_11 = root_1[1]; // "1234.567"
const char* root_12 = root_1[2]; // "mbar"

JsonArray& root_2 = root_[2];
const char* root_20 = root_2[0]; // "P103"
const char* root_21 = root_2[1]; // "2345.678"
const char* root_22 = root_2[2]; // "mbar"

JsonArray& root_3 = root_[3];
const char* root_30 = root_3[0]; // "P104"
const char* root_31 = root_3[1]; // "2.3456"
const char* root_32 = root_3[2]; // "bar(a)"

I did not test this, yet but had a look at the produced snippet and stumbled upon these lines:

JsonArray& root = jsonBuffer.parseArray(json);

JsonArray& root_ = root;

What is the exact advantage of using address-references root, root_ and e.g. root_1 here? Those should, as far as I understood the code, reference to the same data at the end. Is it for better readability only?

The advantage of reference above pointers:

References cannot be NULL, so it's much safer to use them
Address of a reference cannot be acquired, this means a calling function cannot mess up anything outside the type (value) being passed.

For passing a reference to an address the same advantages applies (cannot be NULL, address cannot be changed).

Also, address arithmetic (address + xxx or address - xxx) cannot be used, which prevents tricky programming errors where values outside a variable's memory space can be changed.


Infrared sensor has a frequency to activate it? I am trying to understand 2 sensors that I have here. One says that is "infrared sensor of 38kHz" and the other is "infrared optical reflexive sensor -> http://www.robosoftsystems.co.in/wikidocs/index.php?title=TCRT_5000_Reflective_Optical_Sensor"

I thought that infrared sensor would tell me if an infrared light is passing on it. Infrared light has a wavelenght, right? Can infrared light be emited in different frequencies? Or the frequency of infrared light is the same to all infrared lights?

The 38kHz sensor (such as the Vishay series e.g TSOP1838) are designed for use with IR remotes and IR barrier type applications. They are designed to work with IR emitters that oscillate the IR at 38Khz and additionally modulate that frequency with lower frequency pulses. The sensor (receiver) is designed to have high gain at 38Khz and demodulates the signal. The demodulated output signal pulses can be directly decoded by a microprocessor. The main benefit is reliable functioning even in disturbed ambient light thus protecting against uncontrolled output pulses.


need to make my partners pill box turnover sensitive ive done some arduino stuff back in uni like 7 years ago; and reserached premade items-ive looked online at many pill organisers and the best and cheapest one is $149 and isn't shipping to the UK rite now. but basically my partner needs to take 1 pill a day without fail. second set of pills is less urgent and not an issue if he misses, but basically is there like a thing I could whip together to sense when he has turned the pill case over that day or not? maybe sync to phone(would be super useful)  so he knows when he has actually taken it.

I wouldn't go with a "turn-over" sensor, but would just use a (big) button. I'd go with something like an ESP8266/ESP32. Those can connect to WiFi. Then have it send a push notification when being pressed (that is; the pill has been taken). Maybe light up an LED to also indicate the pill has been taken. Turn off the led at midnight. Also send a different notification when the button hasn't been pressed before, say noon.
For push notifications, you can use PushSafer, PushBullet, or Prowl (which I had most success with).
Have a look at Kevin Darrah article, and youtube channel. He uses it's own boards, but most of the code will work on any ESP board.
But try to imaging how the system would work, in your head first. Just throwing technology at a problem isn't always the best solution. My grandma has 7 pill boxes, one for each week. Which helped to keep track of whether a pill was taken that day.
Best of luck.