Connecting ESP8266 to Arduino Uno I want to get data from ESP to my Arduino. I added firmware v2 to my ESP and it works correctly in my serial USB to TTL and shows the JSON data that I send to it.

But when I connect to my Uno serial it shows some unknown chars.

#include <SoftwareSerial.h> //Including the software serial library
#define DEBUG true
SoftwareSerial esp8266(2, 3); // This will make the Arduino pin 2 as the RX pin and Arduino pin 3 as the TX. Software UART
/* So you have to connect the TX of the esp8266 to the pin 2 of the Arduino and the TX of the esp8266 to the pin 3 of the Arduino. This means that you need to connect the TX line from the esp to the Arduino's pin 2 */

void setup() {
  Serial.begin(115200); // Setting the baudrate to 9600
  esp8266.begin(115200); // Set it according to your esp’s baudrate. Different esp’s have different baud rates.
  pinMode(11, OUTPUT); // Setting the pin 11 as the output pin.
  digitalWrite(11, LOW); // Making it low.
  pinMode(12, OUTPUT); // Setting the pin 12 as the output pin..
  digitalWrite(12, LOW); // Making pin 12 low.
  pinMode(13, OUTPUT); // Setting the pin 13 as the output pin.
  digitalWrite(13, LOW); // Making pin 13 low.
  sendData("AT+RST\r\n", 2000, DEBUG); //This command will reset module to default
  sendData("AT+CWMODE=2\r\n", 1000, DEBUG); // This will configure the mode as access point
  sendData("AT+CIFSR\r\n", 1000, DEBUG); // This will get ip address and will show it
  sendData("AT+CIPMUX=1\r\n", 1000, DEBUG); // This will configure the ESP8266 for multiple connections
  sendData("AT+CIPSERVER=1,80\r\n", 1000, DEBUG); // This will set the server on port 80
}

void loop() {
  if (esp8266.available()) {
    // Checking that whether the esp8266 is sending a message or not (Software UART Data)
    while (esp8266.available()) {
      // Checking whether ESP8266 has received the data or not
      char c = esp8266.read(); // Read the next character.
      Serial.print(c);
      // Storing the response from the ESP8266
    }
  }
}

String sendData(String command, const int timeout, boolean debug) {
  // Function to send the data to the esp8266
  String response = "";
  esp8266.print(command); // Send the command to the ESP8266
  long int time = millis();
  while ((time + timeout) > millis()) {
    // ESP8266 will wait for some time for the data to receive
    while (esp8266.available()) {
      // Checking whether ESP8266 has received the data or not
      char c = esp8266.read(); // Read the next character.
      response += c; // Storing the response from the ESP8266
    }
  }
  if (debug) {
    Serial.print(response);
   // Printing the response of the ESP8266 on the serial monitor.
  }
  return response;
}

Prints this for me:

???AR)?WS?TZ?eO?C?AJ+CIFSR
+CIFSR:APHP,"192.168.4.1"
+CIFSQ:APMAC,"62:01:94:22:96:7e"

OK
AZ??R????jC?u?H?AT+CIPSERVDR=1,80

OK
0,CONNECT

+IPD,0,385:POST / HTTP/1.1
cache-control: no-cache
Postman-Token; 45494ff7-b3e1-400f-8afc-fcda26514705
Content,Type: application/jsonUser-Agent: PostmanRunthme/6.1.6
@ccept: */*Host: 192.178.4.1
accept-encoding: gzip, defl`te
content,length: 14Connection: keep-alive
{"name":"`li"}0,CLOSED

My correct JSON is: {"name":"ali"}. But it shows incorrectly. And I set the mt serial library to #define _SS_MAX_RX_BUFF 1024.

How can I fix this?

My connection is:

Software serial doesn't work reliably at 115200. You need to use a lower baud rate:

Connect the ESP8266 back to your serial USB to TTL setup.
Send the following command to reconfigure the ESP8266 to do AT communication at 9600 baud: AT+UART_DEF=9600,8,1,0,3
Change line 9 of your sketch to esp8266.begin(9600);. This will cause the Uno to communicate with the ESP8266 at 9600 baud.
Upload the revised sketch to your Uno and connect it back up to the ESP8266.


Possible arduino burned (5V shorted to Vin), explanations and suggestions Please apologize my english.
I am working in a project using an original arduino uno, one generic servo (no factory marks) and one HC-SR04 sensor.

I make a circuit like the one here: http://s24.postimg.org/43jra5l9h/mycircuit_bb.png ([url=http://postimg.org/image/lgu1p0gkh/][img]http://s24.postimg.org/lgu1p0gkh/mycircuit_bb.jpg[/img][/url], sorry, upload of image not allowed due reputation)

As you can see from the picture I accidentally connected green into Vin instead of GND. (If the image won't load, that means that my positive is connected to arduino 5V and the ground of the circuit is connected to arduino Vin)

Now my board turn on the lights but I am unable to execute the program already in the microcontroller as aslo I cannot upload a new program to it. (It gives some error message of failed to connect).

I think I burned the microcontroller(mc) by short circuiting 5V and Vin.

That said, I have three questions:

1 - Is there any way to find out if I really burned my board using just a low budget multimeter? And if I did, which parts I need to replace?
I have access to some spare ATMEL mc and I think I could replace and reprogram them by using another arduino board. However, I am affraid that I may have burned few other items and just by replacing the mc will not give me back all the funcionallities of a new board.

2 - I have basic knowledge of electronics, could someone explain to a beginner like me which impact did that mistake could/have make in all components of the circuit? (Arduino board, the servo and the sensor)

3 - Even before the accident, the circuit just work well for few minutes. I read tons of pages and tried a lot of suggestions, most of them related with power supply (capacitors to avoid flutuations, One battery just for the servo, one battery just for the sensor...) and none gave me good results.
I am wondering what are the alternatives to power up this simply circuit, in particular I am looking for this possibilities: Complete external power supply (by using AC to DC adapters), Complete internal power supply (Using just batteries) and a mix of those two (Using AC to DC and batteries). I have no access to a external DC power supply generator other than batteries.

If you have another Uno then your best bet is either:

1) Swap the suspect processor into the known good board, test it.

2) to buy a replacement chip (ATMega 328-PU), use this link to flash it, if it works you win, if not you can at least use the new processor again.

I have done this myself & it worked well, it isn't easy to be sure any other way as the chip needn't fail in a predictable manner. The chances are it will take a large current if it's dead, until it burns out & goes open circuit. Once the magic smoke has come out you know it's dead... the Arduino power supply is reasonably capable of looking after itself so your chances are good.


IDE compiles incorrect file after renaming them I am using the stand alone Arduino IDE to build some projects, and I have a few .cpp files now, but during work I renamed them .c and back. When compiling the project now (with Ctrl-R), it is still trying to compile the .c files. But, I don't even see them on disk!
Changing the .cpp makes no difference. I am used to IDEs having some kind of project file, or a "clean project" option, but I cannot find those here.

The Arduino IDE does not monitor changes to open files. So if you rename or change a file externally (i.e. in another editor), the IDE won't update the file contents. Therefore, after such a change, a restart might be necessary.
Note: If you use another editor to change a file but only compile (and upload) in the IDE, this will work, because the compiler correctly reads the updated file. But editing the source in the IDE and an external editor at the same time might overwrite either change!


"Serial does not name a type error" I m getting serial does not name a type error, expected declaration before '}' token line 69

const int trigPin = 9;
const int echoPin = 10;
const int buzzer = 11;
const int ledPin = 13;

// defines variables
long duration;
int distance;
int safetyDistance;

void setup() {
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input
  pinMode(buzzer, OUTPUT);
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600); // Starts the serial communication
}

void loop() {
// Clears the trigPin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);

// Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

// Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);

// Calculating the distance
  distance = duration * 0.034 / 2;

  safetyDistance = distance;
  if (safetyDistance <= 5) {
    digitalWrite(buzzer, HIGH);
    digitalWrite(ledPin, HIGH);

    tone(buzzer, 1000);
    delay(100);
    noTone(buzzer);
    delay(100);
  }

  else {
    digitalWrite(buzzer, LOW);
    digitalWrite(ledPin, LOW);
  }
  if (safetyDistance > 5 && safetyDistance <= 10) {
    digitalWrite(buzzer, HIGH);
    digitalWrite(ledPin, HIGH);

    tone(buzzer, 3000);
    delay(3000);
    noTone(buzzer);
    delay(3000);
  } else {
    digitalWrite(buzzer, LOW);
    digitalWrite(ledPin, LOW);
  }
  }
  Serial.print("Distance: ");
  Serial.println(distance);

}

if (safetyDistance > 5 && safetyDistance <= 10) {
    digitalWrite(buzzer, HIGH);
    digitalWrite(ledPin, HIGH);

    tone(buzzer, 3000);
    delay(3000);
    noTone(buzzer);
    delay(3000);
  } else {
    digitalWrite(buzzer, LOW);
    digitalWrite(ledPin, LOW);
  }
  }                           //<--
  Serial.print("Distance: ");
  Serial.println(distance);

}

There is a duplicate } after the else clause is closed. Remove it and your code will compile.


Decision maker loop problem Today, I've started a decision maker, using a Arduino UNO R3, a button and a RGB led.
This project makes a decision for you (yes, no, or maybe) when you don't know your own decision about something.

The code I used in the project is the following one (written by me):

#define out OUTPUT
#define in INPUT
#define H HIGH
#define L LOW

int red = 2;
int green = 3;
int blue = 4;

int randomValue = 0;

int button = 5;
int buttonState = 0;

void setup(){
    pinMode(red, out);
    pinMode(green, out);
    pinMode(blue, out);

    pinMode(button, in);
}

void loop(){
    buttonState = digitalRead(button);
    if(buttonState == H){
        randomValue = random(0,4);
        if(randomValue == 1){
            digitalWrite(red, H);
            delay(200);
            digitalWrite(red, L);
            clear();
        }
        if(randomValue == 2){
            digitalWrite(green, H);
            delay(200);
            digitalWrite(green, L);
            clear();
        }
        if(randomValue == 3) {
            digitalWrite(blue, H);
            delay(200);
            digitalWrite(blue, L);
            clear();
        }

    }
}

The connections are correct, and the code also. The problem is: when I push the button, the LED starts showing random colors, and what I want is for the LED to show one color per push.

What can I do?

There is one basic concept that you are lacking.  At the moment you are looking to see if the button is pressed, not when the button has been pressed.

Instead of just looking to see if it is HIGH you need to look if it was LOW but is now HIGH. It's that transition from LOW to HIGH that you need to use as your trigger for when to set the LED colour, and that means remembering the state of the button the last time you went through the loop.

buttonState = digitalRead(button);
if (buttonState != oldButtonState) {
    oldButtonState = buttonState;
    if(buttonState == H) {
        // Do your stuff
    }
}

oldButtonState is defined the same as buttonState.


Does a normal Ultra-Sonic sensor (HC SR04) sense through a Football Net like obstacle? I am planning to to use ultrasonic sensors mounted on a drone for obstacle avoidance. I am not sure if the sensors would be capable of detecting a Net Like obstacle in its path.

There is always a chance of picking up the net for a split second, but most likely, you will never accurately detect the net with this type of sensor. There is too little to detect.


How to separate a specific frequency signal from a summation of a few signals? I want to calculate THD. SO how do I isolate the fundamental frequency from a signal with harmonics?
I have a signal V which is a sum of V1, V2 and V3. V1=A1sin(w1t+phi1), V2=A2sin(w2t+phi2) and V3=A3sin(w3t+phi3). I want to find out the magnitude/amplitude of a known frequency w1 in the signal. How do I proceed? Should I use the FFT library? If yes then how?

What exactly are you trying to do?  If you want to measure THD from an external signal, an Arduino is probably not the best choice.  It only has 10-bit ADCs and they are DC-coupled. You can build a simple circuit (https://www.daqarta.com/dw_rrll.htm) to shift an AC-coupled input to DC for the Arduino, but you will still have only 10-bit resolution.  I haven't looked deep enough into the library that chrisl mentions to see how big an FFT it can perform in the limited RAM of an Arduino, but I suspect the spectral resolution would be so poor as to be unhelpful for real-world THD measurements.
The way you describe the signal makes me think that this is an academic exercise, not a real-world problem.  If so, you don't need an Arduino or any other hardware, just run the FFT on your main computer.   If you do need to make real-world measurements, an ordinary sound card on your computer is a better way to go.  See https://www.daqarta.com/dw_0d0t.htm for an example.  The sound card approach has the added advantage that it can generate a low-distortion test signal to drive the device whose distortion you are trying to measure.  That allows a "trick" (called "Spectral Line Lock" in the example) to get even better resolution, by making the test signal synchronous with the sample rate so you don't need window functions.
If you really want to measure THD with an Arduino, consider an approach used in what used to be called a "wave analyzer".  The block diagram is shown here:
https://www.daqarta.com/dw_0h0p.htm.  This is essentially a one-spectral-line analyzer, which actually can be more selective than an FFT.  You basically multiply the input signal by the sine and cosine of the reference frequency (the fundamental) and then rectify and filter the results, and combine RMS-wise.  That gives you the fundamental value (or any individual harmonic you tune the reference to), so to get THD you divide by the RMS of the overall input signal.


How to pass JsonObject from ArduinoJson to ESP8266WebServer object? I am learning the ArduinoJson.h library and creating jsonOject:

JsonObject& prepareResponse(JsonBuffer& jsonBuffer) {
  JsonObject& root = jsonBuffer.createObject();
  JsonArray& tempValues = root.createNestedArray("temperature");
  tempValues.add(t);
  JsonArray& humiValues = root.createNestedArray("humidity");
  humiValues.add(h);
  JsonArray& dewpValues = root.createNestedArray("dewpoint");
  dewpValues.add(pfDew);
  JsonArray& EsPvValues = root.createNestedArray("systemv");
  EsPvValues.add(pfVcc / 1000, 3);
  return root;
}

As per the example given here. However since I am using an ESP8266WebServer to create a server object from ESP8266WebServer.h, I cannot pass a JsonObject to server.send(.....).

  no matching function for call to 'ESP8266WebServer::send(int, const
  char [10], ArduinoJson::JsonObject&)'

void outputJson() {
  StaticJsonBuffer<500> jsonBuffer;
  JsonObject& json = prepareResponse(jsonBuffer);
  writeResponse(client, json);
  server.send ( 200, "text/json", json );
}

void writeResponse(WiFiClient& clnt, JsonObject& json) {
  clnt.println("HTTP/1.1 200 OK");
  clnt.println("Content-Type: application/json");
  clnt.println("Access-Control-Allow-Origin: *");
  clnt.println("Connection: close");
  clnt.println();
  json.prettyPrintTo(clnt);
}

As far as I know, the only way is to serialize the JsonObject to a String:

String createJsonResponse() {
  StaticJsonBuffer<500> jsonBuffer;

  JsonObject &root = jsonBuffer.createObject();
  JsonArray &tempValues = root.createNestedArray("temperature");
  tempValues.add(t);
  JsonArray &humiValues = root.createNestedArray("humidity");
  humiValues.add(h);
  JsonArray &dewpValues = root.createNestedArray("dewpoint");
  dewpValues.add(pfDew);
  JsonArray &EsPvValues = root.createNestedArray("systemv");
  EsPvValues.add(pfVcc / 1000, 3);

  String json;
  root.prettyPrintTo(json);
  return json;
}

void outputJson() {
    server.send(200, "text/json", createJsonResponse());
}

By the way, I recommend that you use the ArduinoJson Assistant to compute the size of the JsonBuffer.


safety for power electronics I'm quite new to Arduino. I have build a number of projects successfully, like potentiometers, serial communication, DAC, sensors, motors etc.

I use a laptop to power my Arduino project and Atmel Studio to program and upload to the Arduino. I have created a project with 2 motors and I have successfully used a separate power supply (a transformer) to power the motors.

Now I want to continue my experiments but I'm afraid of the possibility to cause any problem to my laptop.

When I made the circuit with the 2 power sources (laptop for the Arduino, transformer for the motors) I had to connect the 2 grounds together.

So my question is that:

Can someone explain me or point me to some information about power electronics so to be absolutely sure that I won't cause any problem to the laptop?

Should I use optocouplers, or diodes etc? Is there a way to avoid the 2 grounds connection? What is the reason to connect both grounds (of the 2 power supplies) in the first place?

Connecting the grounds together is required since without that there would be no circuit for the current to flow through.  Take this simple block diagram for instance:

In the top diagram there are two complete circuits - the green one (Arduino's 5V power) and the blue one (device's 12V power).  The communication between the Arduino and the Device can't happen because there is no circuit (red).

In the bottom diagram the red circuit has been completed by joining the grounds together.  That means that the current has some way to get back to where it came from (which current always has to do) so the signals you send can actually get through.

To avoid having to connect the grounds together you need something called Galvanic Isolation.  This involves using some method that is not electricity to connect the two circuits together.  That could be using light in the form of an opto-coupler, or magnetism in the form of a transformer, or even something even more physical like a relay.  In that situation you have an arrangement like this:

The ground connection that was part of the red circuit above has now been sliced in half (red and orange now) and the isolation device is responsible for passing the signal from one side to the other.

Galvanic isolation is highly desirable when:

You are controlling a different type of current (e.g., using DC to switch AC)
You are working with voltages considerably higher than your drive voltage (e.g., switching mains)
You have different ground potentials (e.g., you have a long distance connection)


Can't get constant reading with load cells I'm really a newcomer to arduino and I'm trying to build a scale with four SEN-10245 load cells and a HX711. My issue is that I can't get constant readings in the serial monitor and I'm not sure if my coding is right or if I did the right setup.
I made the following setup, based on some examples I found online:

The code I'm using is as follows:

    #include <hx711.h>
    Hx711 scale(A1, A0);
    void setup() {
    Serial.begin(9600);
    }
     void loop() {
     Serial.println(scale.averageValue());
     delay(200);
    }

link for the library github: https://github.com/aguegu/ardulibs/tree/master/hx711

Please help me, i'm a total beginner.

Assuming everything is hooked up correctly, your issue is likely related to electromagnetic noise (aka electromagnetic interference, EMI). Load cells output very small voltages, which is why you need the HX711 amplifier. Your long wires are essentially acting as antennas, picking up the electromagnetic noise in the room. One easy way to reduce the noise is to twist the wires together. You can also shield the wires by wrapping them with aluminum foil and attaching the foil to ground.

Making the wires much shorter would likely also help. That would be a good test to see if it helps.

The power supply could also be creating noise. I have found that the 5v line coming from a computer is often quite noisy. This is harder to fix, but an easy way to test if this is the issue is to power the Arduino with a 9V battery. Just make sure you plug it into the Vin pin, not the 5V pin, because the 9V needs to be regulated down to 5V.


Read encoder output by using an optocoupler I have a 512 pulses encoder with four wires: +5V, ChannelA, ChannelB, GND and I'm using it as feedback for my motor position (max 80 RPM) on Arduino UNO. Everything works fine, but I need also to generate a +5V signal everytime ChannelA is HIGH since I need to use it to trigger further actions.
I was thinking to read ChannelA by using an optocoupler in order to split the signal and use it both for feedback and for the +5V signal. Is it possible?
Is there any other easier solution to do that?
EDIT: I try to explain better what the additional device must do.
The device is a video camera system that takes a +5V signal from the encoder to trigger some actions by software (create key frames or more) and we need it for our computer vision system. I just need to use the encoders both for the motor feedback and to trigger the video camera. The signal is always +5V so I do not have problems with voltage levels. What do you suggest? I do not have to drive loads from channelA output, I just need the +5V signal to trigger the video camera.
Can I split the channelA output and use it both for the motor controller and the video camera inputs?
EDIT2:
Following the useful suggestions of @st2000 I tried to think to a solution like this:

Do you think it can work?
EDIT3: I changed swapped the motor controller and the video system positions in the circuit and I changed the voltage source from +12VDC to +5VDC for the motor controller since it accepts only +5V signals as input.

EDIT4: Following the suggestions of @st2000, I changed the circuit design by placing in parallel both devices (motor controller and video system) by using the optocoupler (6N136) only for the video output to isolate it from the whole system.

People sometimes use optical couplers when anticipating large voltage differences or the potential for large voltage differences.  This may always be the case as in a light dimmer.  Or may preventative as in ground loop mitigation for MIDI connections.  If you anticipate these types of situations then an optical coupler may be a good design choice.
Alternatively if the signal is changing between 0 volts and 5 volts and the fan out of the signal is larger then the existing load and the new load combined and the new load is 5 volt tolerant then the signal might be able to drive both loads.
You might seek out the specifications of the 3 connected devices in question.  At the very least, discover the current the encoder output will support.  Then measure the resistance to ground of the input to the motor controller and the resistance to ground of the input to the video equipment.  Find the parallel resistance of these two resistance and calculate the current at 5 volts.  If the current is substantially less then the specified capacity of the encoder, the encoder might be able to drive the 2 loads.  This assumes many things such as no ground loops being present.  There are so many variable it is difficult to be predict the outcome.


OTA-program SPIFFS on the ESP8266 Something I'd like information on is whether it is possible to upload a SPIFFS filesystem image to the ESP8266. In theory it might work: It can be uploaded over USB, and according to the logs the flash location changes, but that's about it. PlatformIO also seems to offer an Upload SPIFFS option in a platform that's set to an OTA port, but that could just be it not checking the upload type.

So, what I want to know is how I can configure (or otherwise make) a SPIFFS image OTA-uploadable. I have two main OTA methods: Option One is the default Arduino OTA library, and Option Two is a re-skin of the OTA method-whose-name-is-forgettable where I can upload a file on a webpage hosted by the ESP8266 and it will read the file and update its firmware.

I'm assuming that there's a configuration parameter for this somewhere, but I don't know where to start looking, and the documentation on these libraries has a few very basic examples that don't cover complex or advanced use cases.

(The web server--though essentially unrelated to this issue, it's a great example--is the most egregious of these; the code is complex and now templated too, so I can't make sense of it, and the "examples" consist largely of compressed javascript that doesn't show the user anything. Then you get to the interesting stuff like actually getting the real size of an uploading file, or want to know how uploading things actually works (or why it fails), or you want to serve a file piecemeal by assembling bits of text (in the same way that debug statements usually make use of multiple Serial.print() statements), and there's just nothing)

Basicly OTA supports the upload of *.bin files. Wether this contains compiled code or a filesystem (SPIFFS/LittleFS) is irrelevant. BUT The space for the OTA (partition) has to be min the size of the *.bin plus an overhead for processing. So with 4MB at all, you would need 2.5MB OTA for 1.5MB App/SPIFFS. To tweak partition sizes (or custom partitions) you have to go into the boards.txt file.OTA - Details and Info here

File system - Details and Info here


Communication between Arduino and python: serial port sending empty data Arduino code:

this code is provided communication between sensor gy-521 and arduino. I read data by the command "1", after 1000 samples arduino is waited for new command for read data.

Arduino code works well in arduino port.

#include<Wire.h>
const int MPU=0x68;
int16_t AcX,AcY,AcZ;
unsigned long time;
bool allow = false;
//int incom = 0;

void setup(){
  Wire.begin();
  Wire.beginTransmission(MPU);
  Wire.write(0x6B);
  Wire.write(0);
  Wire.endTransmission(true);
  Serial.begin(19200);
  while (!Serial);// wait for serial port to connect. Needed for native USB port only
}

void loop(){
  if (allow){ //if allow == true, read data

    for (int i = 0; i < 1000; i++){
      Wire.beginTransmission(MPU);
      Wire.write(0x3B);
      Wire.endTransmission(false);
      Wire.requestFrom(MPU,12,true);
      AcX=Wire.read()<<8|Wire.read();
      AcY=Wire.read()<<8|Wire.read();
      AcZ=Wire.read()<<8|Wire.read();

      time = millis();
      Serial.print(time);Serial.print(",");Serial.print(AcX);Serial.print(",");Serial.print(AcY);Serial.print(",");Serial.println(AcZ);
      delay(0);
    }
    Serial.println(0); //see UPD.3
    allow = false;
  }
}

void serialEvent() {
  while (Serial.available()){ //wait for command
    int incom = Serial.read() - '0';
    Serial.println(incom);
    if (incom == 0){ //if 0 - stop
      allow = false;
      delay(100);
    }
    if (incom == 1){ //if 1 - read data
      allow = true;
      delay(100);
    }
  }
}

Python code:

    def sensors(self):

        self.arduino_port_sensor.reset_input_buffer() #clear buffer

        self.arduino_port_sensor.write(str(1).encode()) #send command to arduino - read data

        main_array = []

        pbar = tqdm(total=self.time_observation) #just to see the progress

        while True:

            values = self.arduino_port_sensor.readline().decode().rstrip().replace(" ", "") #read data, some manipulation for cleaning
            main_array.append(values)

            pbar.update(1)

            if values == '': #if data is empty
                print('!!!!')
                continue
            if values == '0': #see UPD.3
                break

        pbar.close()
        ...bla bla...

I call this function time to time, then in some step, arduino stops sending data -- it sends empty string.

It looks like:

PS. In this code I use 2 ports: for sensor and for motor, 2 different arduino. The principe of working second arduino with motor the same, but it works without any problem (I just send command with "action" to arduino with motor, and then receive answer "received back")

Question: what's wrong with python? how to fix this problem?

UPD

Initialization:

arduino_port_sensor = serial.Serial('/dev/tty.usbmodem143101', 19200, timeout = 1)

UPD.2

It receive command - "1" - read data, the interruption occurs while reading data:

UPD.3

Also i changed the code of arduino -- added the "0" after loop.

UPD.4

If I recall this function after arduno stopped sending data, I get this:

There can be different reasons for your issue. But from the update you added later, we can at least say that your Arduino sometimes doesn't receive the character "1". And when that happens, your Python gets stuck in the infinite loop of trying to read something from the serial port.

As your Arduino responds with "1" when it receives "1", you can base your application on that i.e. if Arduino doesn't respond with "1", keep sending "1".

I wrote a sample program based on your code. I removed the "Wire" part in the Arduino code as I don't have your sensor. I would urge you to test with this Arduino code to make sure that Your sensor is not blocking your Arduino. Wire read can be blocked forever depending on the IC you are trying to read (and if you don't have a timeout).

int16_t AcX,AcY,AcZ;
unsigned long time;
bool allow = false;

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

void loop()
{
  if (allow) //if allow == true, read data
  {
    for(int i = 0; i < 10; i++)
    {
      AcX = 1;
      AcY = 2;
      AcZ = 3;

      time = millis();
      Serial.print(time); Serial.print(",");
      Serial.print(AcX);  Serial.print(",");
      Serial.print(AcY);  Serial.print(",");
      Serial.println(AcZ);
    }
    Serial.println('0');
    allow = false;
  }
}

void serialEvent()
{
  while (Serial.available()) //wait for command
  {
    int incom = Serial.read() - '0';
    Serial.println(incom);
    if (incom == 0)          //if 0 - stop
    {
      allow = false;
      delay(100);
    }
    if (incom == 1)          //if 1 - read data
    {
      allow = true;
      delay(100);
    }
  }
}

In the Python code, I checked if I received "1" from Arduino. If not I kept trying.

import serial
import time

def sensors():
    # Clear receive buffer
    arduino_port_sensor.reset_input_buffer()

    while True:
        # Send command to arduino to send data
        arduino_port_sensor.write('1'.encode())

        # As arduino send LF and CR at the end, let's strip those from the end
        response = arduino_port_sensor.readline().rstrip(b'\r\n ').decode()

        # Arduino should respond with the cmd that it received,
        # if not, send cmd again
        if response == '1':
            # Arduino acknowledged
            break
        else:
            print('Did not receive 1. Retrying...')

    main_array = []

    while True:
        values = arduino_port_sensor.readline().rstrip(b'\r\n ').decode()

        if values == '':
            print('!!!!')
            # This should never happen, but if it does happen, try to read again
            continue
        elif values == '0':
            # print(main_array)
            # We are done receiveing packets
            break
        else:
            # We are still receiving packets
            main_array.append(values)

arduino_port_sensor = serial.Serial('COM50', 19200, timeout=3)

# Let PySerial get ready
time.sleep(3)

while True:
    sensors()
    time.sleep(1)


Why is my CNC shield smoking? Is it safe to keep on for long periods of time? I am working on a project that involves moving stepper motors, and the device will have to be on for upwards of hours. I am moving the bipolar NEMA17 stepper motors using a Protoneer CNC shield V3 on top of an Arduino UNO and DRV8825 stepper drivers. Though I haven't left the motors on for too long, whenever I do for longer periods, maybe 5 minutes or more, smoke starts being emitted around the 4 pins I connect my motors with. My question is that, if anyone has had a similar issue before, if they could explain why this occurs. I would also like to know if the stepper drivers are actually being protected by the heatsinks, because they can get ridiculously hot even after a few minutes and I'm worried that they wouldn't be able to last more than 15 minutes before exploding. Hopefully there's enough information here for someone to understand what's going on, but I'd glad to give more if that helps get a better idea of what's going on here. Thank you!

Those NEMAs are big ones - i suspect too big for the little A4988 chips - which can only provide 2A when actively cooled and generally only for short periods. I wouldn't try to push more than 1.7ish Amps for any length of time.
You will also need to set the vREF correctly for the motors you are using - if this is not set you will either provide too little current or too much current.
Look up the specifications for the NEMAs you have - and upgrade the Stepper controller to something more like a TB6600 that can handle greater current.
Also when the Steppers are not being used - disable (if you dont need them to hold) this will turn off the drivers and let them cool between runs/moves.


How to upload Arduino C code to mBot? I am trying to program mBot using Arduino IDE. I am connected to the mBot using USB on COM7, I am able to upload a code created in mBlock 3.4.11 fine, using "Arduino Mode" as the editing mode. I would like to proceed to more complex coding now and for this I want to be able to edit the source code directly. The source code seen in the MBlock application seems to be read only, there is a button which should allow editing the code, called "Edit with Arduino". When I press this button, the Arduino IDE opens and I am able to edit the code. The trouble is I seem to be unable to send the code edited this way into the mBot.

When I use the Arduino IDE Sketch/Upload menu item, the code is compiled, but when sending it, I always get following error:

  avrdude: stk500v2_ReceiveMessage(): timeout

Note: I was editing and uploading Arduino code before with both Ardino IDE and VisualStudio visualMicro (now Arduino IDE for Visual Studio) without any issues.

I do not know exactly how is the mBlock application handling the upload, but while doing so a folder with the project is created, which contains the following buildprefs.txt - perhaps this could help to understand what it is doing:

build.arch = AVR
build.board = AVR_UNO
build.core = arduino
build.core.path = X:\Users\UserName\mblockExe\Arduino\hardware\arduino\avr\cores\arduino
build.extra_flags =
build.f_cpu = 16000000L
build.mcu = atmega328p
build.path = X:\Users\UserName\AppData\Local\Temp\build3998294614124133332.tmp
build.project_name = project_followLineAuto0_0.cpp
build.source.path = X:\Users\UserName\AppData\Roaming\com.makeblock.Scratch3.4.11\Local Store\scratchTemp\project_followLineAuto0_0
build.system.path = X:\Users\UserName\mblockExe\Arduino\hardware\arduino\avr\system
build.usb_flags = -DUSB_VID={build.vid} -DUSB_PID={build.pid} '-DUSB_MANUFACTURER={build.usb_manufacturer}' '-DUSB_PRODUCT={build.usb_product}'
build.usb_manufacturer = "Unknown"
build.variant = standard
build.variant.path = X:\Users\UserName\mblockExe\Arduino\hardware\arduino\avr\variants\standard
build.verbose = true
build.warn_data_percentage = 75
compiler.S.extra_flags =
compiler.S.flags = -c -g -x assembler-with-cpp
compiler.ar.cmd = avr-ar
compiler.ar.extra_flags =
compiler.ar.flags = rcs
compiler.c.cmd = avr-gcc
compiler.c.elf.cmd = avr-gcc
compiler.c.elf.extra_flags =
compiler.c.elf.flags = {compiler.warning_flags} -Os -Wl,--gc-sections
compiler.c.extra_flags =
compiler.c.flags = -c -g -Os {compiler.warning_flags} -ffunction-sections -fdata-sections -MMD
compiler.cpp.cmd = avr-g++
compiler.cpp.extra_flags =
compiler.cpp.flags = -c -g -Os {compiler.warning_flags} -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD
compiler.elf2hex.cmd = avr-objcopy
compiler.elf2hex.extra_flags =
compiler.elf2hex.flags = -O ihex -R .eeprom
compiler.ldflags =
compiler.objcopy.cmd = avr-objcopy
compiler.objcopy.eep.extra_flags =
compiler.objcopy.eep.flags = -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0
compiler.path = {runtime.tools.avr-gcc.path}/bin/
compiler.size.cmd = avr-size
compiler.warning_flags = -w
compiler.warning_flags.all = -Wall -Wextra
compiler.warning_flags.default =
compiler.warning_flags.more = -Wall
compiler.warning_flags.none = -w

Be sure to select correct board (Arduino UNO) and port.

See this guide for details:
https://www.arduino.cc/en/Guide/ArduinoUno#toc5


Adafruit Motor Shield steppers not turning The Adafruit Motor Shield is connected to 2 steppers which are wired correctly and work when I just use the onestep function. I understand that I cannot drive both at once, so I am using a while loop with two if statements. The Motors were wired:

The left motor was wired:

Green -> m3+
White -> m3-
Red -> m4+
Blue -> m4-

The right motor was wired:

Red -> M2+
Blue -> M2-
Green -> M1+
Black -> M1-

Here is the code:

#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_MS_PWMServoDriver.h"

Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_StepperMotor *leftMotor = AFMS.getStepper(200, 2);
Adafruit_StepperMotor *rightMotor = AFMS.getStepper(200, 1);
//79 steps per half inch
//half inch is a coordinate
//declaring global variables for Hypotenuses (cord lengths)
int leftHyp;
int rightHyp;
int prevX = 0;
int prevY = 0;
//space from shaft to shaft is 30"
//calculating function
void CordCalc(int xCord, int yCord)
{
    Serial.begin(9600);
  //cords start at 0,0
    xCord = xCord - prevX;
    yCord = yCord - prevY;
    int xSquared = sq(xCord);
    int ySquared = sq(yCord);
    int addSquares = xSquared + ySquared;
    int leftHyp = sqrt(addSquares);
  //now for the right
    int rightX = 60 - xCord;
    int rightXsq = sq(rightX);
    int rightSquares = rightXsq + ySquared;
    int rightHyp = sqrt(rightSquares);
  //leftMotor->step(leftHyp * 79, FORWARD, MICROSTEP);
  //rightMotor->step(rightHyp * 79, FORWARD, MICROSTEP);
    int lStepsTaken = 0;
    int rStepsTaken = 0;
    leftHyp = leftHyp * 79;
    rightHyp = rightHyp * 79;
    bool stepsComplete = false;

  //This is the section for moving the Motors
    while(stepsComplete == false) {
        if(lStepsTaken <= leftHyp) {
            leftMotor->onestep(FORWARD,DOUBLE);
            lStepsTaken++;
            Serial.print("Left");
        }

        if(rStepsTaken < rightHyp) {
            rightMotor->onestep(FORWARD,DOUBLE);
            rStepsTaken++;
            Serial.print("Right!");
        }

        if(rStepsTaken >= leftHyp && lStepsTaken >= leftHyp) {
            stepsComplete = true;
        }
    }

    int prevY = yCord;
    int prevX = xCord;
    stepsComplete = false;
}

void setup()
{
// direction from project point of view
    int leftLength = 0;
    int rightLength = 0;
    leftMotor->setSpeed(122);
    rightMotor->setSpeed(122);
    Serial.begin(9600);

    CordCalc(15, 15);
}

void loop()
{
}

Loop is empty on purpose because only need to move to coordinates once.

The missing line was afms.begin(); which starts communication with the adafruit motor shield.


RGB LED Strips with Arduino I am trying to control an RGB LED strip with an Arduino. I have followed the tutorials in both of these websites:
Using MOSFETs: https://learn.adafruit.com/rgb-led-strips?view=all

Using LED Amplifiers: http://www.instructables.com/id/LED-Strip-Controller-w-LED-Amp-Arduino/

I have tried both setups and none of them work for me. When I try the setup with the MOSFETs, I am able to control each color but the blue LEDs are dimmer than the red and green, and therefore I can't mix any colors with blue.

When I try the LED Amplifiers, I am not able to control any light at all. Only the blue LEDs light up but the red and green dont. Also the blue LEDs stay ON the whole time and the only way to turn them off is to disconnect them from the DC power source.
What am I doing wrong?

For the mosfet circuit. Are you using an external power supply? The reason why you cannot mix any color might be due to the fact that you're not providing enough current to the led strip, so it just work fine when turning on each channel individually. Check the current the led strip draws (which usually is provided as amp per channel per meter) and use a power supply that can provide enough current for it.

From the adafuit page

  Connect a 9-12V power supply to the Arduino so that Vin supplies the high voltage to the LED strip. If you want, you can also just use a separate wire that connects to a power supply that provides about +12V. Make sure to connect the ground of that supply to the ground of the Arduino/MOSFETs!


Number of elements in an array char What kind of function can I use to know how many elements are in an array char?

sizeof() gives the number of 'spaces' available so it doesn't work for me.

You want strlen.

char foo [100] = "bar";
Serial.println (strlen (foo));   // --> prints 3


Monitoring Power Down Using Arduino UNO and ZMPT101B I am in the process of implementing power down alerting system suing Arduino UNO and ZMPT101B Single phase relay.

My code as follows,

#include <Filters.h> //Easy library to do the calculations

float testFrequency = 50;                     // test signal frequency (Hz)
float windowLength = 40.0/testFrequency;     // how long to average the signal, for statistist

int Sensor = 0; //Sensor analog input, here it's A0

float intercept = -0.04; // to be adjusted based on calibration testing
float slope = 0.0405; // to be adjusted based on calibration testing
float current_Volts; // Voltage

unsigned long printPeriod = 1000; //Refresh rate
unsigned long previousMillis = 0;

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

void loop() {

    RunningStatistics inputStats;                //Easy life lines, actual calculation of the RMS requires a load of coding
    inputStats.setWindowSecs( windowLength );

    while( true ) {
        Sensor = analogRead(A0);  // read the analog in value:
        inputStats.input(Sensor);  // log to Stats function

        if((unsigned long)(millis() - previousMillis) >= printPeriod) {
            previousMillis = millis();   // update time every second

            Serial.print( "\n" );

            current_Volts = intercept + slope * inputStats.sigma(); //Calibartions for offset and amplitude
            current_Volts= current_Volts*(40.3231);                //Further calibrations for the amplitude

            Serial.print( "\tVoltage: " );
            Serial.print( current_Volts ); //Calculation and Value display is done the rest is if you're using an OLED display

            if (current_Volts <229) {
                test_loop();
            }
        }
    }
}

void test_loop(){
    Serial.print( "Warning!! Server Room Power Down" );
    delay(1000);
}

I am getting the correct voltage reading. When power down it says power down. But when power got up, it still shows power down with older reading. I think the reason for this because my code unable to stop the loop. And if I remove the delay (1000) in test_loop function it works, But my intention to use this sms alerting system and for that I need this delay to stop unnecessary alerts.

My code for SMS Alerting,

Serial.print( "\tVoltage: " );
Serial.print( current_Volts ); //Calculation and Value display is done the rest is if you're using an OLED display

if (current_Volts <229) {
    SendMessage();
}

void test_loop() {
    mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
    delay(1000);  // Delay of 1000 milli seconds or 1 second
    mySerial.println("AT+CMGS=\"xxxxxxxxx\"\r"); // Replace x with mobile number
    delay(1000);
    mySerial.println("Warning!! Server Room Power Down");
    delay(100);
    mySerial.println((char)26);// ASCII code of CTRL+Z
    delay(150000);
    mySerial.println("AT+CMGD=2");
}

This code works for the very first outage but after power up also it send power down. First part of serial priniting in test_loop code of Serial.print is used for debugging.

Got a answer for the issue,

Attaching code for anyone interested.

/*
   Design by Vinod Amarathunga 26.08.2018
   FSSG R&D Team
*/

#include <OneWire.h>
#include <DallasTemperature.h>
#include <SoftwareSerial.h>
#define ONE_WIRE_BUS 2
SoftwareSerial mySerial(11, 10); //SIM800L Rx Tx
char msg;
String textMessage;

bool D7_alarmSent = false;
bool Temp_alarmSent = false;

OneWire oneWire(ONE_WIRE_BUS);

DallasTemperature sensors(&oneWire);

void setup()
{
  mySerial.begin(9600);   // Setting the baud rate of GSM Module
  Serial.begin(9600);    // Setting the baud rate of Serial Monitor (Arduino)
  delay(100);
}

void PowerSMS()
{
  Serial.println("Warning!! Server Room Power Down");
  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"No1\"\r");
  delay(1000);
  mySerial.println("Warning!! Server Room Power Down");
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
  mySerial.println("AT+CMGD=2");

  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"No2\"\r");
  delay(1000);
  mySerial.println("Warning!! Server Room Power Down");
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
  mySerial.println("AT+CMGD=2");

  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"No3\"\r");
  delay(1000);
  mySerial.println("Warning!! Server Room Power Down");
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
  mySerial.println("AT+CMGD=2");

}

void SendMessage()
{

  Serial.println("Warning!! Server Room Temperature is Critical");

  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"No1\"\r"); // Replace x with mobile number
  delay(1000);
  mySerial.println("Warning!! Server Room Temperature is Critical");
  mySerial.println(String("Reading : ") + sensors.getTempCByIndex(0) + String("*C"));
  delay(100);
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
  mySerial.println("AT+CMGD=2");

  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"No2\"\r");
  delay(1000);
  mySerial.println("Warning!! Server Room Temperature is Critical");
  mySerial.println(String("Reading : ") + sensors.getTempCByIndex(0) + String("*C"));
  delay(100);
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
  mySerial.println("AT+CMGD=2");

  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"No3\"\r");
  delay(1000);
  mySerial.println("Warning!! Server Room Temperature is Critical");
  mySerial.println(String("Reading : ") + sensors.getTempCByIndex(0) + String("*C"));
  delay(100);
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
  mySerial.println("AT+CMGD=2");

}

void loop()
{
  sensors.requestTemperatures(); // Send the command to get temperature readings
  delay(1000);
  Serial.println(String("Temp Reading : ") + sensors.getTempCByIndex(0) + String("*C"));
  Serial.println(String("Voltage Digital: ") + digitalRead(7));
  Serial.println(Temp_alarmSent ? "True" : "False" );
  Serial.println(D7_alarmSent ? "True" : "False" );
  Serial.println("***********");
  ReceiveMessage();

  if (digitalRead(7) == 1 || sensors.getTempCByIndex(0) > 29 || D7_alarmSent == true || Temp_alarmSent == true ) {
    if (digitalRead(7) == 1 ) {
      if (!D7_alarmSent) {
        D7_alarmSent = true;
        PowerSMS();
      }

    }

    else if (sensors.getTempCByIndex(0) > 29 ) {
      if (!Temp_alarmSent) {
        Temp_alarmSent = true;
        SendMessage();
      }

    }

    else {

      if (D7_alarmSent){                  //alarmSent == true means that previous state was "Power Down"
          SendMessage_After_Power_Down();          //Send message
          D7_alarmSent = false;
          Temp_alarmSent = false;             //Reset alarmstate
        }

    }
  }

}

void SendMessage_Normal()
{
  Serial.println("Temperature and Power is OK");

  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"No1\"\r");
  delay(1000);
  mySerial.println("Temperature and Power is OK");
  mySerial.println(String("Reading : ") + sensors.getTempCByIndex(0) + String("*C"));
  delay(100);
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);

  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"No2\"\r");
  delay(1000);
  mySerial.println("Temperature and Power is OK");
  mySerial.println(String("Reading : ") + sensors.getTempCByIndex(0) + String("*C"));
  delay(100);
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);

  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"No3\"\r");
  delay(1000);
  mySerial.println("Temperature and Power is OK");
  mySerial.println(String("Reading : ") + sensors.getTempCByIndex(0) + String("*C"));
  delay(100);
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);

}
void SendMessage_After_Power_Down(){

  Serial.println("Power Back Online");

  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"No1"\r");
  delay(1000);
  mySerial.println("Power Back Online");
  delay(100);
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);

  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"No2\"\r");
  delay(1000);
  mySerial.println("Power Back Online");
  delay(100);
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);

  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"No3\"\r");
  delay(1000);
  mySerial.println("Power Back Online");
  delay(100);
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);

  }

void ReceiveMessage()
{
  if (mySerial.available() > 0)
  {
    mySerial.println("AT+CNMI=2,2,0,0,0"); // AT Command to recieve a live SMS
    delay(1000);
    textMessage = mySerial.readString();
    Serial.print(textMessage);
    delay(10);
  }
  if (textMessage.indexOf("Status") >= 0) {
    SendMessage_Normal();
    mySerial.println("AT+CMGD=2");

  }
}


Serial.read has garbled data after a Serial.write I'm using the Serial1 of the Arduino Leonardo to send and receive data with another MCU. The following code will always retrieve garbled data:

byte streamReadResponse;
Serial1.begin(115200);
Serial1.setTimeout(9000);
Serial1.print(cmd);
Serial1.print('\r');
Serial1.flush();  //wait for all the data to be sent to the serial
streamReadResponse = Serial1.readBytesUntil('>', data, dataLength);

But, if I add a delay(50) before the Serial1 read, I would get the expected output. The value 50 was found by trial and error.

What am I missing? Why is the flush() command not working as expected?

I've finally found that when the MCU  to which Arduino is talking to was initialized, it would send spurious data to the Serial - I guess it would start first with a lower baud rate, and then switch to the programmed baud rate of 115200.

To fix this, I had to flush the Arduino serial RX before sending any data. So:

byte streamReadResponse;
Serial1.begin(115200);
Serial1.setTimeout(9000);
while (Serial1.read() >= 0)
           ; // do nothing
Serial1.print(cmd);
Serial1.print('\r');
Serial1.flush();  //wait for all the data to be sent to the serial
streamReadResponse = Serial1.readBytesUntil('>', data, dataLength);


ESP-12F responds only to a few basic AT commands I previously read a few guides and tutorials about the ESP8266 and i just started using the ESP-12F module as i think that it is a terrific replacement for Arduino with the added benefit of Wi-Fi. I only have the module itself which is basically a metal casing so, i wired up the ESP-12F module according to this schematic.

My USB-TTL board is operating at 3 V for its VCC and also for the TX and RX logic levels. I use Arduino IDE 1.8.9 (i made sure that i am using the latest stable version) and then set the COM port to the USB-TTL RS232 connected to the ESP12F and typed "AT" and got a response "OK". Then, i tried, "AT+RST" and got a big bunch of text which proved that there is successful communication with the ESP module. But then, i tried to connect the ESP-12F to my Wi-Fi network, so i entered: AT+CWJAP_CUR="SSID","password" replacing the SSID and password with my own and it gave the response "ERROR", so i tried the old format AT+CWJAP="SSID","password" and again i got "ERROR". So, what am i doing wrong? How to fix this? I was thinking that maybe the firmware on my ESP is old and needs to be updated, so i entered "AT+GMR" and i got this info:

19:07:27.560 -> ready
19:07:27.560 -> AT+GMR
19:07:27.560 -> AT version:1.2.0.0(Jul  1 2016 20:04:45)
19:07:27.560 -> SDK version:1.5.4.1(39cb9a32)
19:07:27.560 -> Ai-Thinker Technology Co. Ltd.
19:07:27.560 -> Dec  2 2016 14:21:16
19:07:27.560 -> OK

Do i need to update my module to be able to connect it to my Wi-Fi? If yes, how? I want to update it as safely as possible as this is my only ESP module and i don't want to inadvertently damage it.

You can't connect to an access point until you put the module into Station mode.

AT+CWMODE=1

That will put it in STA mode.  You can alternatively make it an access point (AP mode) with:

AP+CWMODE=2


Arduino uint8_t to String or char- retrieve from usb device My code returns uint8_t format when is cast to char and Display on LCD it works fine but I want to get that scanned code for further processing. not only to display on LCD 16x2 , but it returns some strange symbols. Any Idea?

#include <LiquidCrystal.h>
#include <avr/pgmspace.h>
#include <hid.h>
#include <hiduniversal.h>
#include <usbhub.h>
#include <Usb.h>
#include <usbhub.h>
#include <avr/pgmspace.h>
#include <hidboot.h>
#include <SPI.h>
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
USB     Usb;
USBHub     Hub(&Usb);
HIDUniversal Hid(&Usb);
HIDBoot<HID_PROTOCOL_KEYBOARD>    Keyboard(&Usb);

class KbdRptParser : public KeyboardReportParser
{
  void PrintKey(uint8_t mod, uint8_t key);
protected:
  virtual void OnKeyDown  (uint8_t mod, uint8_t key);
  virtual void OnKeyPressed(uint8_t key);
};

void KbdRptParser::OnKeyDown(uint8_t mod, uint8_t key)
{
    uint8_t c = OemToAscii(mod, key);

    if (c)
        OnKeyPressed(c);
}

/* what to do when symbol arrives */
void KbdRptParser::OnKeyPressed(uint8_t key)
{
static uint32_t next_time = 0;      //watchdog
static uint8_t current_cursor = 0;  //tracks current cursor position

    if( millis() > next_time ) {
      lcd.clear();
      current_cursor = 0;
      delay( 5 );  //LCD-specific
      lcd.setCursor( 0,0 );
    }//if( millis() > next_time ...

    next_time = millis() + 200;  //reset watchdog

    if( current_cursor++ == ( DISPLAY_WIDTH + 1 )) {  //switch to second line if cursor outside the screen
      lcd.setCursor( 0,1 );
    }
  char keys=(char) key;
    Serial.println(keys);
// char add =keys.indexOf(5)+keys.indexOf(6)+keys.indexOf(7)+keys.indexOf(8);
    Serial.println(keys);
    lcd.print(keys);
};

KbdRptParser Prs;

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

    if (Usb.Init() == -1) {
        Serial.println("OSC did not start.");
    }

    delay( 200 );

    Hid.SetReportParser(0, (HIDReportParser*)&Prs);
    // set up the LCD's number of columns and rows:
    lcd.begin(DISPLAY_WIDTH, 2);
    lcd.clear();
    lcd.noAutoscroll();
    lcd.print("Scan Your Code");
    delay( 200 );
}

void loop()
{
  Usb.Task();
}

A unit8_t is an 8 bit unsigned integer - it can have any value between 0 and 255, and can be compared to any numeric value in that range.

You can do "further processing" on the received uint8_t value whether it is a printable ASCII value or not.


Resistor - Correct value for optocoupler, but dont have that size I am making a shutter for my camera using a Arduino and an optocoupler.
I understand most of most parts, but unsure about the resistor because I don't have the correct size. 5V will be coming from the Arduino, and the 4N35 will need 1.3V 10mA. This leads to a 380Ω resistor.
Now I only have 100Ω, 220Ω, 330Ω, and 1kΩ resistors. I have read I shouldn't use anything lower than 380Ω and only use higher but 1kΩ seem a little too high haha.
Just looking for some pointers please.

1kΩ will be just fine. But if you want lower you could take two 1kΩ and place them in parallel - that will give you 500Ω.
BTW - 1kΩ will give you ((5-1.3)/1000=) 3.7mA through the diode of the optocoupler, and 500Ω will give you ((5-1.3)/500=) 7.4mA.


Peak counting in serial Arduino I want to count peak of photocell data with serial communication in Arduino.

Here is the question. My problem is when I count one of the peaks it continues the counting and doesn't stop counting. My project is count Michelson Morley fringes with a photocell and Arduino.

If somebody can help me with the coding part I would appreciate it.

Here is the code that I used:

int count=0;
int val;
int data;

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

void loop() {
  data=analogRead(A0);
  val=map(data,0,1023,1000,0);
  if(val>700) {
   count++;
  }
  Serial.println(count);
  delay(100);
}

This picture shows what I am trying to achieve:

Example Michelson Morley fringes:

keep in mind that since you used

delay(100)

your 'loop' code runs in 10HZ (10 times a second)
So, every time you are lighting on your sensor, if its for longer than 1/10 of a second, you are likely going through several instances of 'loop', in which the condition

(val>700)

is satisfied.

If you know that your peaks are going to take several loops, and only want to count each peak once- a simple way would be to make sure you dropped from the previous peak before incrementing the counter. you can achieve that with something like:

int count=0;
int val;
int data;
bool inPeak = false;

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

void loop() {
  data=analogRead(A0);
  val=map(data,0,1023,1000,0);
  if(val>700) {
     if (!inPeak)
     {
        count ++;
        inPeak = true;
     }
  }
  else
  {
      inPeak = false;
  }

  Serial.println(count);
  delay(100);
}


Arduino LED matrix and 2D array, data seems to be corrupting Duplicate of this question

I'm trying to drive an 8x8 LED matrix with an arduino nano, but I can't get the LEDs to display what I tell it to.

I'm using this LED Matrix

Here's my code:

int row1 = 2;
int row2 = 3;
int row3 = 4;
int row4 = 5;
int row5 = 6;
int row6 = 7;
int row7 = 8;
int row8 = 9;

int col1 = 10;
int col2 = 11;
int col3 = 12;
int col4 = 18;
int col5 = 14;
int col6 = 15;
int col7 = 16;
int col8 = 17;

void setup() {
  int i;
  for(i = 2; i <= 18; i++) {
    pinMode(i,OUTPUT);
  }
  for(i = 2; i <= 9; i++) {
    digitalWrite(i, HIGH);
  }
}

void loop() {

  int display [8][8] = {
  {1,0,0,0,0,0,0,0},
  {0,1,0,0,0,0,0,0},
  {0,0,1,0,0,0,0,0},
  {0,0,0,1,0,0,0,0},
  {0,0,0,0,1,0,0,0},
  {0,0,0,0,0,1,0,0},
  {0,0,0,0,0,0,1,0},
  {0,0,0,0,0,0,0,1}
  };

  updateScreen(display);
}

void updateScreen(int screen[8][8]) {

  Serial.begin(9600);
  int i;
  for (i = row1; i <= row8; i++) {
    Serial.println(i-1);
    digitalWrite(i, LOW);
      digitalWrite(col8, screen[i-2][0]);
      Serial.print(screen[i-2][0]); Serial.print("|");
      digitalWrite(col7, screen[i-2][1]);
      Serial.print(screen[i-2][1]); Serial.print("|");
      digitalWrite(col6, screen[i-2][2]);
      Serial.print(screen[i-2][2]); Serial.print("|");
      digitalWrite(col5, screen[i-2][3]);
      Serial.print(screen[i-2][3]); Serial.print("|");
      digitalWrite(col4, screen[i-2][4]);
      Serial.print(screen[i-2][4]); Serial.print("|");
      digitalWrite(col3, screen[i-2][5]);
      Serial.print(screen[i-2][5]); Serial.print("|");
      digitalWrite(col2, screen[i-2][6]);
      Serial.print(screen[i-2][6]); Serial.print("|");
      digitalWrite(col1, screen[i-2][7]);
      Serial.println(screen[i-2][7]);
      delay(1);
      blank();
    digitalWrite(i, HIGH);
  }

}

void blank() {
  digitalWrite(col1, LOW);
  digitalWrite(col2, LOW);
  digitalWrite(col3, LOW);
  digitalWrite(col4, LOW);
  digitalWrite(col5, LOW);
  digitalWrite(col6, LOW);
  digitalWrite(col7, LOW);
  digitalWrite(col8, LOW);
}

And here is the output:

1
1|0|0|0|0|0|0|0
2
0|1|0|0|0|0|0|0
3
0|0|1|0|0|0|0|0
4
0|0|0|1|0|0|0|0
5
0|0|0|0|1|0|0¾j
6
0|0|0|0|0|1|0|0
7
0|0|0|0|0|0|1|0
8
0|0|0|0|0|0|0|1

So I can tell that the error (probably) isn't my wiring, because those array values are clearly wrong, I have no idea where the ¾j is coming from.

Your initial problem can be sorted out by using a longer delay.

void updateScreen(int screen[8][8]) {

  Serial.begin(9600);
  int i;
  ........
      delay(100); //Longer time duration
      blank();
    digitalWrite(i, HIGH);
  }

}

As far as the chess pattern is concerned, it displays correctly for me.

void loop() {

  int display [8][8] = {
  {1,0,1,0,1,0,1,0},
  {0,1,0,1,0,1,0,1},
  {1,0,1,0,1,0,1,0},
  {0,1,0,1,0,1,0,1},
  {1,0,1,0,1,0,1,0},
  {0,1,0,1,0,1,0,1},
  {1,0,1,0,1,0,1,0},
  {0,1,0,1,0,1,0,1}
  };

  updateScreen(display);
}

Check your array declarations for errors.


Arduino Due: enable reentrant interrupt I'm using the TC3 interrupt on my Arduino Due to run some code periodically, like this:

void TC3_Handler() {
  TC_GetStatus(TC1, 0); // Remove interrupt flag
  // My code...
}

However, as I've found out, the CPU will not service the same interrupt a second time while the interrupt is running. By editing the priorities of each interrupt source, it's possible for a higher priority interrupt to preempt and run over this interrupt (so nested interrupts are possible), but priority manipulation alone does not allow reentrant interrupts.

I'd like to know if there is any way to make this interrupt reentrant.

does not allow reentrant interrupts.

a few suggestions:

1) understand what "reentrant interrupts" means;

2) see if you need it;

3) see what needs to be done to get it to run on your hardware;

4) see if your code does what needs to be done.

hope it helps.


What happens if you write >10000 times to the flash memory of an ATmega? I realized that I'm uploading code every 5 minutes and doing relatively intensive trial-and-error development, and that this habit could cause problems down the road, especially if I'm working on a custom board (non-Arduino) where the chip isn't readily replaceable.

What will happen?

I noticed that avrdude verifies the written flash. So will it simply start noticing errors and possibly be unable to write without failing?

Or will it work sometimes, sometimes not?

Example of heavy use: A custom PCB where easy replacement of the MCU is not possible. 10,000 writes would equal 100 days, each 8 hours of development, with flash write every 5 minutes.

I have several habits that drive frequent flash writing: I inject benchmarks into my code, test speed improvements of small optimizations, program size optimizations, and so on.

I now try to restrain myself from flashing too frequently and doing more code revisions before testing, rather than testing immediately.

In conclusion: Yes, it's unlikely, and arguably, if you're working full-time on a board, less intensively, for, say, a year, you can probably afford to buy another board when the first one starts failing the flash-verification.

What will happen?

it may not pass parity check. so uploading code wouldn't be possible.

with that said, I have never had one flash-based mcu failure due to endurance. that's countless mcus since as far as I can remember.

to give you some sense of design headroom, I wrote-to and then read-back from eeprom on a pic over several hours @ 10ms per read/write, without a failure. that eeprom is rated 1M in endurance.

so unless you get some weird parts or you write to it repeatedly over a long period of time, flash failure is unlikely a practical issue.


Can I hook up two micros to one GPS module? I've worked with a few different GPS modules. Most of them seem to just pump out data and not really interact with the micro controller.

I have a quadcopter (Cheerson CX 20 Big Sky) It has a gps break out board that looks similar to the one I've worked with before. Is it likely that I connect another micro controller to this board? I want to add a cellular module to my quad.

I know that the answer may be "it depends" but before I start testing and researching I just want to know if it's even likely to work.

If the gps is just barfing out coordinates and not interacting with the main board I think it could work. I could just tap in and "listen" -- is this even a possibility?

You are quite wrong. The answer is not "it depends", but "yes".

You can have any number of devices listening to (receiving) the transmitted data. You can only have one device sending anything back to whatever it is that is broadcasting the data if you need to configure it in any way. That shouldn't be a problem of course if you have one main controller that does that configuration and everything else is just a passive listener.  Just be sure that you don't connect the transmit pins of the passive listeners to anything (unless you want to use them for a completely unrelated purpose to transmit serial data to something else).

The only caveat is that each device you add as a listener will increase the load on the GPS's transmit pin and eventually the slew rate will become too slow and the signal will become distorted. If this ever becomes an issue reducing the baud rate can combat it to a certain extent. For serial though you would need quite a lot of devices for it to become an issue. Two devices certainly won't ever be an issue.


NRF24L0 wireless modules I have two arduinos (one uno and another nano) with NRF24L0 modules attached to both and they are communicating between each other. All good.

However, I have a load of different ones and have switched them with the working receivers to test them but they just refuse to work despite the pinouts being correct.

Does the pinout vary between manufacturers or something else perhaps? What really perplexes me is that some of the modules I've tried are brand new (just taken out of the antistatic)

I have followed https://maniacbug.wordpress.com/2011/11/02/getting-started-rf24/

Any help would be really appriciated. Thanks

I was having the same kind of problems (even with new modules) when supplying them by mistake with 5v instead of 3,3V. It even happened that the system was working fine for days after the communication problems due to wrong power supply started to appear.

Also many people have reported similar problems(sometimes communicating, sometimes not) with this module due to poor built-in decoupling especially when using relatively long cables between arduino and module. Just to make sure, put a decoupling capacitor near the module's power and ground pins.

(this is more of a comment but I cannot comment due to reputation.)


Calculating with millis() The following code works fine until I turn the if (tijd - action >= 500) into if (tijd - action >= 1000)

I wonder why this fails.

If I just loop and print the tijd - action it has no problem with it and runs well beyond 1000.

The Logic Analyzer on the software serial only returns '255' when it fails, I also wonder what that means.

The core I use is this one
The chip I use is an ATtiny85
I run this using the Arduino IDE 1.8.2

[update]

with "start"

Sketch uses 3070 bytes (37%) of program storage space. Maximum is 8192 bytes.
Global variables use 146 bytes (28%) of dynamic memory, leaving 366 bytes for local variables. Maximum is 512 bytes.

with "starting"

Sketch uses 3072 bytes (37%) of program storage space. Maximum is 8192 bytes.
Global variables use 148 bytes (28%) of dynamic memory, leaving 364 bytes for local variables. Maximum is 512 bytes.

script

#include <SoftwareSerial.h>
#include <avr/sleep.h>
#include <avr/wdt.h>

#define TX_PIN 4
#define RX_PIN -1

#ifndef cbi
  #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
  #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif

SoftwareSerial mySerial(RX_PIN, TX_PIN);

unsigned long tijd;
unsigned long action = 0;

volatile boolean f_wdt = 1;
ISR(WDT_vect) {
  f_wdt=1;
}

void system_sleep() {
  cbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter OFF

  set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here
  sleep_enable();

  sleep_mode();                        // System sleeps here

  sleep_disable();                     // System continues execution here when watchdog timed out
  sbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter ON
}

void setup_watchdog(int ii) {
  byte bb;
  int ww;
  if (ii > 9 ) ii=9;
  bb=ii & 7;
  if (ii > 7) bb|= (1<<5);
  bb|= (1<<WDCE);
  ww=bb;

  MCUSR &= ~(1<<WDRF);
  // start timed sequence
  WDTCR |= (1<<WDCE) | (1<<WDE);
  // set new watchdog timeout value
  WDTCR = bb;
  WDTCR |= _BV(WDIE);
}

void setup() {
  mySerial.begin(2400);
  mySerial.print("Starting..");
  setup_watchdog(8);
  pinMode(0, OUTPUT);
}

int zie = 0;

void loop() {
  if (f_wdt==1) {
    digitalWrite(0, HIGH);
    tijd = millis();
    mySerial.print(".");
    mySerial.print(tijd - action);
    zie+=1;
    if (tijd - action >= 500) { // fails when set to 1000
      digitalWrite(0, LOW);
      action = tijd;
      mySerial.print("z");
      mySerial.print(zie);
      mySerial.print(".");
      system_sleep();
    }
  }
}

if I change the string "Starting.." to "Start" it will run fine! This probably has something to do with filling up the RAM of the Tiny, right?

That symptom does suggest RAM overflow, in spite of the relatively low RAM use (28%) reported during compilation.

To reduce memory use slightly more, you can move the string "Starting.." to PROGMEM by changing from line 1 below to line 2.

  mySerial.print("Starting..");     // line 1
  mySerial.print(F("Starting.."));  // line 2

To save another handful of RAM bytes, change lines like mySerial.print("."); and mySerial.print("z"); to mySerial.print('.'); and mySerial.print('z');.  That is, you are printing single-character strings; each string has a null terminating byte; instead just print single characters.

References and discussion of the F() macro include 1, 2, 3, 4, 5 and also see  How do I squeeze code to fit onto an ATTiny.  Also, there are some really compact software serial libraries targeted for ATtinies, which may save hundreds of bytes of flash and dozens of bytes of RAM.


Arduino Pro Mini and Electronic Speed Controller (ESC) I want to send servo signal to ESC and Servo with my 3.3V Arduino Pro Mini.

Can the ESC/Servo read 3.3V signal from Arduino Pro Mini? Or do I need to make some level shifter to make 5V signal?

The ESC should have no problem with 3v3 signal.


I want my arduino mega to read from all 4 serial ports at the same time, running sequentially through each one I currently have the code running through Serial1, which works exactly as I want it to:

int RFIDResetPin = 13;

void setup()
{
  Serial.begin(9600);
  Serial1.begin(9600);
  Serial2.begin(9600);
  pinMode(RFIDResetPin, OUTPUT);
  digitalWrite(RFIDResetPin, HIGH);
  Serial.println("Arduino is ready");
}

void loop(){

  char tagString1[13];
  int index = 0;
  boolean reading1 = false;
  ///////////////////////////////////////
  //this reads from the reader installed
  //on serial1, which is pin 19
  //////////////////////////////////////
  while (Serial1.available() > 0) {

    int readByte1 = Serial1.read(); //read next available byte

    if (readByte1 == 2) reading1 = true;
    if (readByte1 == 3) reading1 = false;

    if (reading1 && readByte1 != 2 && readByte1 != 10 && readByte1 != 13) {
      tagString1[index] = readByte1;
      index++;
    }
  }
  Serial.print("Reader 1: "); //read out any unknown tag
  Serial.println(tagString1);

  clearTag(tagString1); //Clear the char of all value
  resetReader(); //reset the RFID reader
}

void resetReader() {
  ///////////////////////////////////
  //Reset the RFID reader to read again.
  ///////////////////////////////////
  digitalWrite(RFIDResetPin, LOW);
  digitalWrite(RFIDResetPin, HIGH);
  delay(150);
}

void clearTag(char one[]) {
  ///////////////////////////////////
  //clear the char array by filling with null – ASCII 0
  //Will think same tag has been read otherwise
  ///////////////////////////////////
  for (int i = 0; i < strlen(one); i++) {
    one[i] = 0;
  }
}

However, I want to add serial0, 2, and 3 as well. there are 2 main questions I have
1) is it possible to have copy paste this section of the code:

    while (Serial1.available() > 0) {

    int readByte1 = Serial1.read(); //read next available byte

    if (readByte1 == 2) reading1 = true;
    if (readByte1 == 3) reading1 = false;

    if (reading1 && readByte1 != 2 && readByte1 != 10 && readByte1 != 13) {
      tagString1[index] = readByte1;
      index++;
    }
  }
  Serial.print("Reader 1: "); //read out any unknown tag
  Serial.println(tagString1);

  clearTag(tagString1); //Clear the char of all value
  resetReader(); //reset the RFID reader
}

while changing some of the variable names to connect the other serial ports? I saw something here, but don't know how to implement it, or if it even would work for me.

and
2) since I am routing the incoming data through serial0, Is it possible to have this code working on it as well?

The Arduino already reads from the 4 serial ports at the same time. Or
at least as close to “at the same time” as possible with a single CPU:
every time a byte is received at one port, an interrupt is triggered
that reads the byte from the UART and puts it into a buffer. You can
then get it from the buffer using Serial.read().

What you now have to do is move the bytes from these buffers (which
belong to the Arduino hardware serial library) into you own buffers for
further processing. You can do this by checking the ports sequentially
and processing each one in turn. Everything will be fine as long as you
do not have blocking code in there. If you do block, then you run the
risk of having one of the library buffers overflow. The code you posted
is non-blocking, so you are fine.

  is it possible to have copy paste

You should avoid programming by copy-and-paste. It's not that it won't
work (it will), but you would be creating a maintenance nightmare.
Instead, put the code you would want to copy-paste into a function, and
call that function as many times as required. For example:

void handlePort(Stream &port, const char *readerName, char *tagString)
{
    boolean reading1 = false;
    while (port.available() > 0) {
        int readByte1 = port.read(); //read next available byte

        if (readByte1 == 2) reading1 = true;
        if (readByte1 == 3) reading1 = false;
        if (reading1 && readByte1 != 2 && readByte1 != 10 && readByte1 != 13) {
            tagString[index] = readByte1;
            index++;
        }
    }
    Serial.print(readerName); //read out any unknown tag
    Serial.print(": ");
    Serial.println(tagString);

    clearTag(tagString); //Clear the char of all value
    resetReader(); //reset the RFID reader
    }
}

And you call it in loop():

handlePort(Serial1, "Reader 1", tagString1);
handlePort(Serial2, "Reader 2", tagString2);
...


I'm working on a NodeMCU project and have a small doubt about LEDs and resistors In my NodeMCU I want a statement to turn on an LED, which is easy, just use pinnumber, HIGH. But, what I'm trying to do here is connect multiple LEDs to one pin like this:
I just wanted to know if this will work and whether all the LEDs will turn on by one command write (pinnumber, high) or do I have to do something else to this circuit?
Please help I'm a noob to electronics.
And also, is the resistor correct(1k ohm) or is it 220ohm, because different places suggest different things.

No! Most likely it will not work.
An LED lights up if the Voltage between the Anode (one side of the LED) and cathode (the other leg) exceeds a so called forward voltage (Vf).
This Vf depends on the creation process and differs between different colors. Vf can be between abt. 1.8 Volt (red LEDs) and abt. 4.2 Volt (blue LEDs). Even if the LEDs would have the same color, they might have different forward voltages. If you arrage 4 LEDs in parallel, like you did above, the Voltage over the 4 LEDS is as low as the Vf of the LED with the lowest Vf among the four. If the four LED would not have equal (Vf)s, only one LED will light up and all others stay dark or just glow a little bit.
The sum of the current that flows through the 4 LEDs must also flow through the resistor. So the resistor must let pass 4 times the current that is required for one LED. An normal 3mm or 5mm LED works best at about 10mA to 20mA. Let's say the LEDs have all the same Vf = abt. 2 Volts, and you choose to drive them with 15 mA.
You need 60 mA in sum for the 4 LEDs, that must pass the resistor. You can compute the required resistance with  Ohms law. R = U / I.

R is the resistance in Ohms.

U is the voltage over the resistor in Volts.

I is the current through the resistor in Ampere.
U = Voltage of the ESP (3.3 Volt) minus
the lowest forward voltage of the LEDs (2 Volt)
I = the wanted current 60mA = 0.06 Ampere
R = (3.3-2) / 0.06 = 140 / 6 = abt. 23 Ohm
(27 Ohm resistors should be available.)

The resistor depends on the Voltage of the ESP, the kind of the LED and the amount of current you need to reliably light up the LEDs. You can not just take values from schematics or discussions the internet. Also 60 mA is very much current for the ESP pin. That might be a problem.
The best way the Light up 4 LEDs from one pin would be to use one resistor for each LED and a MOS FET Transistor that is connected to 5 Volts with its Drain pin, the parallel LED resistor pairs with its Source and to the ESP pin with its Gate. You should also be sure that the MOS FET you use is able to switch with a 3.3 V voltage from the ESP on its Gate.
If you did not understand what I have written, I advice you to learn the basics before experimenting further. The values above are all useless if the conditions change.


I2C_graphical_LCD_display, fatal error: avr/pgmspace.h: No such file or directory I have a problem with an ESP32 devkit V1 card. I'm trying to connect a WG12864A Winstar mod graphics display via the I2C MCP23017 adapter (RobotDyn), using Nick Gammon's I2C_graphical_LCD_display.h library.

Everything works well by connecting it to the Arduino Uno - Duemilanove board. Loading the sketch LCD_Demo_Using_I2C present in the library is compiled correctly without errors.

If I connect the display to ESP32 devkit V1, I try to compile it I get the following error:

C: \ Users \ Topolino \ Documents \ Arduino \ libraries \ I2C_graphical_LCD_display-master / I2C_graphical_LCD_display.h: 62: 26: fatal error: avr / pgmspace.h : No such file or directory.
Compilation terminated.
exit status 1
Error during compilation for DOIT ESP32 DEVKIT V1 card.

I tried to compile it with PlatformIO presents the usual compilation error.
You can help me, someone has some ideas to solve the problem.

The authors of the ESP32 core didn't bother to create a proper set of compatability shims for the PROGMEM system - chiefly because it's not needed for ESP32 operation.

We did for chipKIT, though, and you can grab a copy of ours here and place it in with the core files for the ESP32 in your Arduino installation (you only need the pgmspace.h file, and place it in an avr folder inside the core source folder).

It's completely architecture agnostic and basically defines some pretty much empty macros, and maps _P variants of various functions to the non _P alternatives.


Connecting Arduino Android Wirelessy I am working with Arduino and Android. I am interested in connecting Arduino (Mega 2560 ADK) to my Android tablet (Nexus 7) wirelessly. The chepaest option is via bluetooth but the communication in not reliable. Now I would like to connect it via WiFi. But I don't want to use WiFi shield on my Arduino.

As Arduino can send the information to my laptop via serial USB connection will it be possible to put this information on my home WiFi network and get it on my Android device by connecting it to the same WiFi network?

Yes, if the laptop and tablet are on the same network communication will be possible. One way to implement this would be to have a client/server setup that communicates over TCP/IP.

The laptop can act as a TCP/IP server and also communicate through the serial interface to your arduino. Many languages will be able to do this, Java, C/C++, Python, whatever you're comfortable with.

The android tablet can then connect to the TCP/IP server as a client and send and receive data through your WiFi. Have a look at the android documentation.

This would a simple solution but for a more permanent solution you could also setup a web server on your laptop, look into the apache webserver. Your tablet would be able to communicate with the web server through http requests. The web server can then start further scripts to send data to the arduino or maintain a serial connection depending on your implementation.


Where to connect an external power source for an Arduino motor driver shield to? I have a BYJ48 stepper motor and an ULN2003A motor driver shield shield.

In many tutorials I read:

  do not to draw current from the 5V on the Arduino rail, but use an
  external power source, since the motor can draw quite some current

Which of these options to they mean by this?

  Connect an external power adapter to the Arduino and connect the
  ULN2003A board to the Vin pin and GND on the Arduino

or

  Connect the motor shield itself to an external power adapter and connect it to the + and - pin on the motor shield

or perhaps both are valid solutions?

The board I use is this one.

There are two things you need to do:

Prevent the motor drawing its power from the micro-controller board.
Make sure that all the grounds are connected but avoiding motor current return through the micro-controller board.

simulate this circuit – Schematic created using CircuitLab

Figure 1. A good wiring configuration. The heavy wires carry the motor current.

Note that there is one ground connection between the micro-controller and the motor system. The return current for the 12 V supply does not pass through the micro-controller board.


How to detect patterns in an FFT output? I have an FFT output from a microphone and I want to detect a specific animal's howl from that (it howls in a characteristic frequency spectrum). Is there any way to implement a pattern recognition algorithm in Arduino to do that? Thanks!

It depends.

First you need to break the problem in steps:

If you can make a static analysis, than there is a chance. Meaning, if you can record a snapshot of the howl, and than spend some time processing it.
If you need to process it (almost) real time, than I am almost sure the Arduino is way too slow for that. In the next steps will be clear why, and otherwise you can use the next steps to get some idea how to do the analysis.
Assume you can do a snapshot of the sound, than you have to store it. The Arduino has only 2 KB of SRAM which is way too small. I assume you want a decent frequency (let's say 40 KHz) of mono (1 channel) samples, which is 40 KB of memory.
You need to record this (probably any sound sensor will be fast enough), and store it to some device, either external SRAM (fastest, most expensive), external EEPROM (somewhere in the middle) or SD card (might be slow). EEPROM/SD cannot be written 'forever' so if you want to process a sample every second, you might run in trouble.
Than you need to run your algorithm over the static data. I do not know this algorithm, if you have to iterate many times, forget about using SD, use SRAM or EEPROM.
Otherwise, read a few blocks (typically 2 or 3, to get 1 or 1.5 KB) and process it. I hope you can store the result also in the Arduino, otherwise write it (if you write much, probably SRAM is the only well feasible solution).

As you can see, you have to break your problem into smaller pieces, and check how the algorithm works (does it need a lot of data, or a snapshot), can it be processed in pieces, or does it need to iterate over the entire sample data a lot, are there intermediate results need to be stored etc.

Note there might be other solutions:

If you need more speed, try an Arduino Due
If you need more (internal) SRAM, try a Mega (8 KB) or Due (48 KB)


Are static variables in a function bad? For my code I use a couple of static variables.
But when I search the internet, they seem "evil".

For example: I have a function which will be executed every loop (5ms looptime).
to increase the speed I added some static variables to it.
Is the way I am doing this bad? Are there simple solutions for it?

Code:

int ProgFormula() {
  static int StartPosition;
  static int DeltaPosition;
  static int LoopTime = 5;
  static int AccelerationLoops;
  static int TotalLoops;
  static int EndOne;

  static float VelocityLoop;
  static float VelocityFactor;

  int Setpoint;

  if (Iteration == -1) {
    StartPosition = PID.ActualPosition;
    DeltaPosition = abs(SetPosition - StartPosition);
    VelocityLoop = Velocity / (1000 / LoopTime);
    TotalLoops = DeltaPosition / VelocityLoop;
    if (TotalLoops <= (AccelerationLoops * 2)) {
      AccelerationLoops = (TotalLoops / 2);
      VelocityFactor = (VelocityLoop * 0.5 / AccelerationLoops) / 2;
    }
    else {
      AccelerationLoops = 70;

      VelocityFactor = VelocityLoop * 0.5 / AccelerationLoops;
    }
    TotalLoops = DeltaPosition / VelocityLoop + AccelerationLoops;
    EndOne = (VelocityFactor * pow(AccelerationLoops, 2));
  }
  else if (Iteration >= 0 && Iteration <= AccelerationLoops) {
    if (StartPosition < SetPosition) {
      Setpoint = VelocityFactor * pow(Iteration, 2) + StartPosition;
    }
    else {
      Setpoint = -VelocityFactor * pow(Iteration, 2) + StartPosition;
    }
  }
  else if (Iteration > AccelerationLoops && Iteration <= (TotalLoops - AccelerationLoops)) {
    if (StartPosition < SetPosition) {
      Setpoint = VelocityLoop * Iteration - EndOne + StartPosition;
    }
    else {
      Setpoint = -VelocityLoop * Iteration + EndOne + StartPosition;
    }
  }
  else if (Iteration >= (TotalLoops - AccelerationLoops) && Iteration <= TotalLoops) {
    if (StartPosition < SetPosition) {
      Setpoint = -VelocityFactor * pow((TotalLoops - Iteration), 2) + DeltaPosition + StartPosition;
    }
    else {
      Setpoint = VelocityFactor * pow((TotalLoops - Iteration), 2) - DeltaPosition + StartPosition;
    }
  }
  else {
    Setpoint = Setpoint;
  }
  return(Setpoint);
}

Is it better to avoid statics? If so why?

Thanks in advance,
Koen

I made up a test by adding enough to the posted code to get it to compile:

float ActualPosition, SetPosition, Velocity;

int Iteration;

int ProgFormula() {

  static int StartPosition;
  static int DeltaPosition;
  static int LoopTime = 5;
  static int AccelerationLoops;
  static int TotalLoops;
  static int EndOne;

  static float VelocityLoop;
  static float VelocityFactor;

  int Setpoint;

  if (Iteration == -1) {
    StartPosition = ActualPosition;
    DeltaPosition = abs(SetPosition - StartPosition);
    VelocityLoop = Velocity / (1000 / LoopTime);
    TotalLoops = DeltaPosition / VelocityLoop;
    if (TotalLoops <= (AccelerationLoops * 2)) {
      AccelerationLoops = (TotalLoops / 2);
      VelocityFactor = (VelocityLoop * 0.5 / AccelerationLoops) / 2;
    }
    else {
      AccelerationLoops = 70;

      VelocityFactor = VelocityLoop * 0.5 / AccelerationLoops;
    }
    TotalLoops = DeltaPosition / VelocityLoop + AccelerationLoops;
    EndOne = (VelocityFactor * pow(AccelerationLoops, 2));
  }
  else if (Iteration >= 0 && Iteration <= AccelerationLoops) {
    if (StartPosition < SetPosition) {
      Setpoint = VelocityFactor * pow(Iteration, 2) + StartPosition;
    }
    else {
      Setpoint = -VelocityFactor * pow(Iteration, 2) + StartPosition;
    }
  }
  else if (Iteration > AccelerationLoops && Iteration <= (TotalLoops - AccelerationLoops)) {
    if (StartPosition < SetPosition) {
      Setpoint = VelocityLoop * Iteration - EndOne + StartPosition;
    }
    else {
      Setpoint = -VelocityLoop * Iteration + EndOne + StartPosition;
    }
  }
  else if (Iteration >= (TotalLoops - AccelerationLoops) && Iteration <= TotalLoops) {
    if (StartPosition < SetPosition) {
      Setpoint = -VelocityFactor * pow((TotalLoops - Iteration), 2) + DeltaPosition + StartPosition;
    }
    else {
      Setpoint = VelocityFactor * pow((TotalLoops - Iteration), 2) - DeltaPosition + StartPosition;
    }
  }
  else {
    Setpoint = Setpoint;
  }
  return(Setpoint);
}

void setup ()
  {
   ProgFormula ();
  }  // end of setup

void loop ()
  {

  }  // end of loop

Disassembling this I got the following assembler:

000000a8 <_Z11ProgFormulav>:
  a8:   6f 92           push    r6
  aa:   7f 92           push    r7
  ac:   8f 92           push    r8
  ae:   9f 92           push    r9
  b0:   af 92           push    r10
  b2:   bf 92           push    r11
  b4:   cf 92           push    r12
  b6:   df 92           push    r13
  b8:   ef 92           push    r14
  ba:   ff 92           push    r15
  bc:   0f 93           push    r16
  be:   1f 93           push    r17
  c0:   cf 93           push    r28
  c2:   df 93           push    r29
  c4:   00 91 0c 01     lds r16, 0x010C
  c8:   10 91 0d 01     lds r17, 0x010D
  cc:   8f ef           ldi r24, 0xFF   ; 255
  ce:   0f 3f           cpi r16, 0xFF   ; 255
  d0:   18 07           cpc r17, r24
...
 4ec:   cb 01           movw    r24, r22
 4ee:   df 91           pop r29
 4f0:   cf 91           pop r28
 4f2:   1f 91           pop r17
 4f4:   0f 91           pop r16
 4f6:   ff 90           pop r15
 4f8:   ef 90           pop r14
 4fa:   df 90           pop r13
 4fc:   cf 90           pop r12
 4fe:   bf 90           pop r11
 500:   af 90           pop r10
 502:   9f 90           pop r9
 504:   8f 90           pop r8
 506:   7f 90           pop r7
 508:   6f 90           pop r6
 50a:   08 95           ret

0000050c <setup>:

So that function (ProgFormula) has taken up:

0x50a - 0xa8 = 1122 bytes

Now by removing the "static" declarations, like this:

   int StartPosition;
   int DeltaPosition;
   int LoopTime = 5;
   int AccelerationLoops;
   int TotalLoops;
   int EndOne;

   float VelocityLoop;
   float VelocityFactor;

It now compiles to:

000000a8 <_Z11ProgFormulav>:
  a8:   6f 92           push    r6
  aa:   7f 92           push    r7
  ac:   8f 92           push    r8
  ae:   9f 92           push    r9
  b0:   af 92           push    r10
  b2:   bf 92           push    r11
  b4:   cf 92           push    r12
  b6:   df 92           push    r13
  b8:   ef 92           push    r14
  ba:   ff 92           push    r15
  bc:   0f 93           push    r16
  be:   1f 93           push    r17
  c0:   cf 93           push    r28
  c2:   df 93           push    r29
  c4:   c0 91 04 01     lds r28, 0x0104
  c8:   d0 91 05 01     lds r29, 0x0105
  cc:   8f ef           ldi r24, 0xFF   ; 255
  ce:   cf 3f           cpi r28, 0xFF   ; 255
  d0:   d8 07           cpc r29, r24
...
 27e:   cb 01           movw    r24, r22
 280:   df 91           pop r29
 282:   cf 91           pop r28
 284:   1f 91           pop r17
 286:   0f 91           pop r16
 288:   ff 90           pop r15
 28a:   ef 90           pop r14
 28c:   df 90           pop r13
 28e:   cf 90           pop r12
 290:   bf 90           pop r11
 292:   af 90           pop r10
 294:   9f 90           pop r9
 296:   8f 90           pop r8
 298:   7f 90           pop r7
 29a:   6f 90           pop r6
 29c:   08 95           ret

0000029e <setup>:

That is now:

0x29e - 0xa8 = 502 bytes

Conclusion

Adding "static" has made the function over twice as long. Presumably it is also slower. After all, those extra instructions have be doing something.

  to increase the speed I added some static variables to it.

Your belief that making variables static increases the speed does not seem to be supported.


easy_install pip on Arduino Yun fails I want to install pip on the Yún which is running Linino OS but every time I execute the standard steps for opkg i.e.

# opkg update
# opkg install distribute
# okpg install python-openssl
# easy_install pip

Error

Searching for pip
Reading http://pypi.python.org/simple/pip/
Couldn't find index page for 'pip' (maybe misspelled?)
Scanning index of all packages (this may take a while)
Reading http://pypi.python.org/simple/
No local packages or download links found for pip
error: Could not find suitable distribution for Requirement.parse('pip')

What is the reason behind this?

Kernel Information

Linux Arduino 3.3.8 #1 Fri Nov 14 08:57:34 CET 2014 mips GNU/Linux

Found this Arduino Forum Thread helpful.

# wget \
https://pypi.python.org/packages/source/p/pip/pip-6.0.8.tar.gz#md5=2332e6f97e75ded3bddde0ced01dbda3\
  --no-check-certificate
# easy_install pip-6.0.8.tar.gz

Apparently the PyPi Package Site is now HTTPS and hence --no-check-certificate option should be used. Also MD5 Checksum of the package needs to attached in the link in order to avoid a HTTP 404 Error


How to read input pin on MCP23017? I'm working to develop a simple code for MCP23017 that I want to use to run LCD128x64.

I was succeeded to set IODIRB as output and blink LED as a test.

Now I want to read the pin state, but I couldn't. Here's my code. I'm using the nice twi library that comes with Wire library.

uint8_t mcp23017_read(uint8_t add_reg){
    uint8_t data;
    twi_writeTo(MCP23017_ADD,add_reg,2,1,0);
    twi_readFrom(MCP23017_ADD,data,1,1);

    return data;
}

I've tried this version too:

uint8_t *mcp23017_read(uint8_t add_reg){
    uint8_t data[1];
    twi_writeTo(MCP23017_ADD,add_reg,2,1,0);
    twi_readFrom(MCP23017_ADD,data,1,1);

    return *data;
}

==================================================

Here's Arduino call function:

void loop() {
  // put your main code here, to run repeatedly:
  data = mcp23017_read(GPIOB);
  Serial.println(data);
  delay(100);
}

I don't know how this lib works. But I'm pretty sure that you have to pass a pointer onto the data variable into the twi_readFrom method.

uint8_t mcp23017_read( uint8_t add_reg )
{
    uint8_t data;
    twi_writeTo( MCP23017_ADD, add_reg, 2, 1, 0 );
    // I inserted an & below
    twi_readFrom( MCP23017_ADD, &data, 1, 1 );

    return data;
}

Or in case of the second function:

// I removed the star operator
uint8_t mcp23017_read(uint8_t add_reg)
{
    uint8_t data[1];

    twi_writeTo( MCP23017_ADD, add_reg, 2, 1, 0 );
    // you pass the pointer to the array element 0
    twi_readFrom( MCP23017_ADD, data, 1, 1 );

    // I returned the element 0
    return data[0];
}

Update:

Just for completeness: The OP found also a failure on the write function. He had posted a separate answer, I voted up to mark it. Because this is the accepted answer, I also copied his post to here for completeness and the readers convenience.

Original post by R1S8K:

  OK, I found a the answer and it was a good lesson in dealing with
  functions that receives pointers.

  I forgot that the writeTo function also receives a pointer and I have
  to pass an array for both read/write functions.

void mcp23017_read(uint8_t *add_reg, uint8_t *buffer){
    twi_writeTo(MCP23017_ADD, add_reg, 1, 1, 1);
    twi_readFrom(MCP23017_ADD, buffer, 1, 1);
}