Esp8266-01 AT commands returns random chars and/or "ERROR" I'm trying to make my esp8266 work with my arduino.

But when I send AT commands I get some weird symbols and some functions return "ERROR"

Here's the code I'm using.

#include "SoftwareSerial.h"

SoftwareSerial esp8266(6, 7); // RX, TX

void setup()
{
  Serial.begin(9600); // serial port used for debugging
  esp8266.begin(115200);  // your ESP's baud rate might be different
}

void loop()
{
  if(esp8266.available())  // check if the ESP is sending a message
  {
    while(esp8266.available())
    {
      char c = esp8266.read();  // read the next character.

      Serial.write(c);  // writes data to the serial monitor
    }
  }

  if(Serial.available())
  {
    delay(10);  // wait to let all the input command in the serial buffer

    // read the input command in a string
    String cmd = "";
    while(Serial.available())
    {
      cmd += (char)Serial.read();
    }
    // send to the esp8266
    esp8266.println(cmd);
  }
}

Here's the Serial Monitor:

AT

OK
AT+RST

OK

 ets Jan  8 2013,rst catse:2, boot lode:(3,7)

loab 0x40100000& len 1396, qoom 16
tail 4C�,kk�������e
load 0x3fge8000, len 776, room 4 tak0  t0�v�
�!jH+��
����(j5�!
,�2%1�

j
�sl��o�
Ai,Thinker Technology Co. Ltd.

invalid
AT+CWMODE?

+CWMODE:1

OK

AT+GMR

AT version;0.25.0.0(Juo  5 2015 17:27:16)
SDK version:1.0
ryJ 0

AT+CWLAP

+CWLAP:(4,"�P��R�*bj��b���*��2��*����Ҋ�b�Jj
��*A�B�br������Յź�aj��b����2j
":6�*AՉ����J
"�́������

The commands where, AT, AT+RST, AT+CWMODE?, AT+GMR, AT+CWLAP

Why am I getting this weird symbols and etc? I haven't upgraded the firmware, should I?  There other commands I tried return "ERROR" or even "ERROQ"

I don't have a USB to TTL or any other board. I connected my board in the arduino with this schematic:

Cap = 10uF
VolReg = LM1117 3.3v

The problem is mainly in using Serial and SoftwareSerial together. Or it can be due the esp getting less current than it requires from the Arduino(you are also damaging your Arduino!), use an external 5V source (I use my computer USB)

Why dont you directly use Serial for communication with pins 0 and 1. Just upload a blank sketch, connect Arduino Tx, Rx to esp's Tx, Rx(reverse Tx, Rx if not working). What you type into Serial will then be sent to the esp. Later if you wish to communicate to esp in sketches, use only SoftwareSerial.

Also, the esp is not 5V tolerant so you need to use a level shifter(like the cd4050 ic) or a voltage divider(less efficient) for signals from the Arduino to the esp. 3.3V is considered as a logical HIGH so you dont need to do any changes for signals from esp to the Arduino.

I highly recommend getting a USB TTL converter, this will save you a lot of headaches and debugging will be easy. I did things without it for 1-2months and now I can totally feel the difference.


Seeeduino V3.0 (Atmega 328P) and Rotary Angle Sensor Mystery Message I am attempting to do a simple example with the Rotary Angle Sensor.

Here is my development environment:

Visual Studio 2013 Premium
Arduino Debug Tool

Board setup (Simple as can be single analog input):

Code:

const int ROTARYSENSOR = A0;

void setup()
{
    Serial.println("Setup Start...");
    Serial.begin(9600); //Set the serial communication frequency at 9600 bits per second

    pinMode(ROTARYSENSOR, INPUT);

    Serial.println("Setup End!");
}

void loop()
{
    Serial.println("Loop Start...");

    int value = analogRead(ROTARYSENSOR);
    Serial.println(value); //display on serial monitor
    delay(1000); //wait 1000ms before printing next value

    Serial.println("Loop End!");
}

Issue:

I have a single solution with multiple projects as my sensor playground. All other projects I have so far work flawlessly no issues.  Although with this project (RotaryAngleSensor) I am getting a strange message.

I am not seeing any of the Serial.println() messages. What is printed to the screen after a good 30 seconds is S?

Does anyone know what could be returning this S? to the standard output?

One problem is that you try to generate serial output before you initiate Serial.  This could have odd results beyond just making that message fail.

Serial.println("Setup Start...");
Serial.begin(9600);

Should be

Serial.begin(9600);
Serial.println("Setup Start...");

And of course your posted code never reads the sensor...


Use all pins As digital I/O Increase the number of digital pins

There are many post that explain how to use more than just the standard pins on the various arduinos but none of them explain the limitations and the proplems properly.

Arduino Uno:

1.You can use the analog pins

Pin 14 = Analog in 0
Pin 15 = Analog in 1
Pin 16 = Analog in 2
Pin 17 = Analog in 3
Pin 18 = Analog in 4
Pin 19 = Analog in 5

digitalWrite(14,HIGH);
or
digitalWrite(A0,HIGH);

2.You can't use both SDA , SCL & A4 , A5 as they are basically the same (18,19).

3.You can also use the TX/RX.

  "Don't do it, you break the serial communication..."

  "Never use pins 0 and 1"

  "you can't use the TX/Rx Pins"

You can... but you need to take precautions. Which ones?

It should have software serial over USB, right?

Or do i break the USB serial?

Are there internal Chip problems if i use TX/RX?

As i use those TX/RX pins in the code i probably should not use Serial.print()?

What happens if i forget to remove Serial.print() after uploading the code that use pins 0,1?

How to hardware reset the arduino/bootloader if something goes wrong?

As there are various other Arduino's that use different chips, is the above valid for all Atmel chips?

So, what shuold i know before using those TX/RX or also maybe the other analog pins?

  There are cheap shiftregisters, pwm drivers, led drivers, spi, i2c and
  more ic's to expand your I/O

But if there are not to big problems it means that the arduino has 20 I/O pins...

You could theoretically control:

17x3 = 51 = 17 RGB leds (multiplexing, pwm sourcing&sinking);
14x6 = 84 leds (multiplexing, pwm on 6 rows/colums );
10x10 = 100 leds (multiplexing, high low);
20x(20-1) = 380 leds (charlieplexing, high low);
// yes it would flicker

Correct me if i'm wrong. That means you are able to control 380 "Whatever" using diodes and one arduino.

The main issue is with pins 0 and 1.

Many pins have multiple functions assigned to them, such as A4 and A5 are also the I2C pins, pins 10/11/12/13 are also the SPI pins, etc.  But pins 0 and 1 are the only multi-function pins that actually have something attached to them on the board.

All the other pins, while being multi-function, have their function defined basically by what you attach to them.  Since the pins 0 and 1 are already attached on the board to the USB interface chip their usage possibilities are somewhat more limited.

As soon as you enable Serial in your sketch (Serial.begin()) those two pins can no longer be reliably used for digital IO.

That means that you can either use the hardware serial port or you can use the pins for digital IO, but not both.

Devices connected to pins 0 and 1 can interfere with the serial connection

That includes uploading of sketches.  You have serial data coming in from the PC while the same pins are being affected by other things connected to them.  The most common one is things like GPS modules which connect to those pins and constantly send serial data.  That serial data will conflict with the PC's serial data and neither will arrive right.

How do you upload sketches if the serial is being interfered with by your sketch? How do you "reset" the board?

You don't.  It's not your sketch that's interfering with the serial, it's what is physically connected to those two IO pins that are interfering.  Just disconnect those two pins from whatever is connected and you will be able to upload sketches again.  Many shields now are starting to add a small switch on them to disconnect those pins so you can upload sketches without unplugging the shield.  You can also use the same trick with other devices you wire up to those pins - add a double-pole-single-throw or double-pole-double-throw (and not use one position) to easily isolate both pins from the rest of your hardware when you need to.

Does this affect all Arduino boards?

No, only those that use a USB to Serial bridge chip - that's things like the Uno, Due, Mega, etc.  Boards that have a direct USB connection don't use the TX and RX pins for uploading sketches - they use the dedicated USB D+ and D- pins.  That's boards like the Leonardo, some of the smaller (mini? micro? I forget which) boards, etc.


Shield interfere with Serial Communication I'm new to arduino. I have nexus duino robot as described in http://www.aliexpress.com/item/3WD-48mm-Omni-Wheel-Mobile-Arduino-Robot-Kit-10019/688287804.html, the shield connected with motors and support xbee.

With simple serial comm sketch, I'm able to communicate between arduino and PC if the shield not inserted, but not if I insert the shield as it seem arduino can't receive serial data (still can send data to PC tough). Someone says that the shield might be use RX TX so it interfere with serial comm.

My Questions are, is there a way to check whether the shield use RX TX? If yes, can we make it not interfere with serial comm? Could be other problem causing this serial comm problem?
Thanks in advance.

You really do need to provide information on the shield, there are many versions out there (and I own half of them ).

In essence, unless you are using an alternate serial port (SerialN) or software serial, then YES, your XBee will be using the same lines as your Arduino. If you are using Serial.print or Serial.write to talk to the XBee, then that is a giveaway too.

The reason for this is the XBee talks to your Arduino through the serial port, but the Arduino IDE also talks to your Arduino (for programming and Serial.print) as well. You can only do one successfully.

In answer to your second question, most likely not. It will be the XBee shield causing you your problems.

edit: I thought I would add, I actually have ONE shield that uses RX and TX but also allows for programming at the same time. This is achieved through a series resistor and (in the case of the shield) an amplifier as well.


WiFi repeater using ESP8266 I have a ESP8266 and I wonder if it is possible to create a Wi-Fi signal repeater using this module.

I can create a network so that devices connect it.
I can connect to an existing network.

But I can not connect the network created with the network that I connected

Does anyone know how to do this? or you have any examples?

You can't have a single ESP8266 be both an access point and a client, at least not using the exposed API (recall that the Arduino libaries do not implement much functionality themselves, all they do is call the underlying RTOS API).

Also, a signal repeater is not a radio-only device. It would have to understand the low-level 802.11* protocols and packet types so you don't end up with forwarding loops. You can't do it just by connecting a pair of 8266s back-to-back over SPI and blindly forward packets; there is a lot of networking code that would have to be written.


What's the difference between analogWrite and digitalWrite? As the title states. What's the difference between the two?

analogWrite(pin,0-255) vs digitalWrite(pin,LOW-HIGH)

digitalWrite will set the specified pin to one of two states - HIGH/LOW, which equate to 5v (3.3v on some boards) and ground respectively.

analogWrite can vary by the type of output used.

If applied to a PWM pin - it will set the pin to a periodic high/low signal, where the percentage of the signal spent high is proportional to the value written.
for example  -

    analogWrite(PWMpin,255)

Will be HIGH 100% of the time, while

    analogWrite(PWMpin,127)

Will be HIGH 50% of the time, and LOW 50% of the time

When applying analogWrite to a DAC pin (available on some boards, like the DUE or MEGA)
analogWrite will actually cause the specified pin to output a voltage level proportinal to the specified analog value

For example, on the Due, with maximal voltage of 3.3v and a default analog resolution of 8 bits -[0:255]

    analogWrite(DACpin,255)

Will cause the specified pin to output 3.3v, and-

    analogWrite(DACpin,127)

Will cause the specified pin to output 1.35v


How do I connect a temperature and heartbeat sensor to an Arduino Uno? I have been using a temperature sensor and heartbeat sensor separately and I am trying to code for temperature and heartbeat sensors. How do I get its output on the Arduino IDE's Serial Plotter?

Code of temperature sensor:

int val;
int tempPin = 1;

void setup()
{
  Serial.begin(9600);
}
void loop()
{
  val = analogRead(tempPin);
  float mv = ( val / 1024.0) * 5000;
  float cel = mv / 10;
  float farh = (cel * 9) / 5 + 32;

  Serial.print("TEMPRATURE = ");
  Serial.print(cel);
  Serial.print("*C");
  Serial.println();
  delay(1000);

  /* uncomment this to get temperature in farenhite
    Serial.print("TEMPRATURE = ");
    Serial.print(farh);
    Serial.print("*F");
    Serial.println();
  */
}

If you separate your code into functions you may understand what you want to do better.

In the listing above, you have code that reads the temp and prints the temp.  So creating two functions ReadTemp() and ShowTemp() will make the code in loop look cleaner and easier to read.  i.e.

void loop()
{
    const float cel = ReadTemp();
    DisplayTemp(cel);
    delay(1000);
}

float ReadTemp(void)
{
    val = analogRead(tempPin);
    float mv = ( val/1024.0)*5000;
    float cel = mv/10;
    // float farh = (cel*9)/5 + 32;
    return cel;
}
void ShowTemp(const float& cel)
{
    Serial.print("TEMPRATURE = ");
    Serial.print(cel);
    Serial.print("*C");
    Serial.println();
}

In you sketch for the hearbeat monitor you should have some code that reads the heartbeat and some that prints it.  If you create two functions ReadHB() and ShowHB() you will be able to easily add them to the above loop function.

I've never used the serial plotter, but if you wrap it in a function called PlotTemp() and PlotHB() then you can slot them in instead of the Show functions.


Digital RGB LED animation I've been trying to get colours fade into each other for a project I'm working on.
I have achieved this with the rainbow effect that some from Adafruit's example code, however I want to be able to choose the colours (eg. dark blue into light blue).

I've got the colours changing and fading, however the fade turns off all the LEDs and starts to increase the brightness of the new colour. I need the colours to blend rather than fade out and increase in brightness.

Is anyone able to point me in the right direction?

#include "LPD8806.h"
#include "SPI.h"
#define stripSize 64

int nLEDs = 160;

int dataPin  = 2;
int clockPin = 3;

// First parameter is the number of LEDs in the strand.  The LED strips
// are 32 LEDs per meter but you can extend or cut the strip.  Next two
// parameters are SPI data and clock pins:
LPD8806 strip = LPD8806(64, dataPin, clockPin);

// You can optionally use hardware SPI for faster writes, just leave out
// the data and clock pin parameters.  But this does limit use to very
// specific pins on the Arduino.  For "classic" Arduinos (Uno, Duemilanove,
// etc.), data = pin 11, clock = pin 13.  For Arduino Mega, data = pin 51,
// clock = pin 52.  For 32u4 Breakout Board+ and Teensy, data = pin B2,
// clock = pin B1.  For Leonardo, this can ONLY be done on the ICSP pins.
//LPD8806 strip = LPD8806(nLEDs);

void setup() {
  // Start up the LED strip
  strip.begin();

  // Update the strip, to start they are all 'off'
  strip.show();
}

void loop() {
  //turnAllOn(strip.Color(30,30,30),4000);
  fade(0, 127, 0, 100); //red, green, blue, delay - fade up all pixels one color
  //turnAllOn(strip.Color(30,100,30),4000);
  fade(50, 127, 02,100); //red, green, blue, delay - fade up all pixels one color
  //turnAllOn(strip.Color(100,30,100),4000);
  fade(50, 127, 50, 100); //red, green, blue, delay - fade up all pixels one color
}

void fade(uint32_t r, uint32_t g, uint32_t b, uint32_t wait) {
  int i, j;
  for (j=0; j < 384; j++) {
    for (i=0; i < strip.numPixels(); i++) {
      strip.setPixelColor(i, strip.Color((r*j)/1000,(g*j)/1000,(b*j)/1000));
    }
  strip.show();
  }
  delay(wait);
}

void turnAllOn(uint32_t c, uint32_t wait) {
  int i;
  for (i=0; i < strip.numPixels(); i++) {
    strip.setPixelColor(i, c);  // turn all pixels on
  }
  strip.show();   // write all the pixels out
  delay(wait);
}

uint32_t Wheel(uint16_t WheelPos)
{
  byte r, g, b;
  switch(WheelPos / 128)
  {
    case 0:
      r = 127 - WheelPos % 128;   //Red down
      g = WheelPos % 128;      // Green up
      b = 0;                  //blue off
      break;
    case 1:
      g = 127 - WheelPos % 128;  //green down
      b = WheelPos % 128;      //blue up
      r = 0;                  //red off
      break;
    case 2:
      b = 127 - WheelPos % 128;  //blue down
      r = WheelPos % 128;      //red up
      g = 0;                  //green off
      break;
  }
  return(strip.Color(r,g,b));
}

Currently, your fade function is starting at 0 and effectively interpolating up to the desired colour. To fade between colours, you would need the sketch to remember the previous colour it used, and start fading from that instead of from 0.

The approach I'd use is to start by calculating how much each component needs to change by on each step. For example, if you want to fade from 100 to 200 across 50 steps, then it needs to change by +2 on every step. If you wanted to do the same in reverse (200 to 100) then it would have to change by -2.

One of the problems is that each component will probably be changing by a different amount (red might go from 0 to 200, but blue might only go from 50 to 70). If you're using integers all the time then it could result in some uneven transitions, so I'd recommend using floating point instead. It's technically slower (less efficient), but probably not enough to worry about.

This is how I'd probably write it:

void fade(uint8_t oldR, uint8_t oldG, uint8_t oldB, uint8_t newR, uint8_t newG, uint8_t newB, uint32_t numSteps, uint32_t waitPerStep)
{
    // Guard against division by zero
    if (numSteps == 0) numSteps = 1;

    // Calculate how how much each colour needs to change on each step
    const float
        stepR = (newR - oldR) / (float)numSteps,
        stepG = (newG - oldG) / (float)numSteps,
        stepB = (newB - oldB) / (float)numSteps;

    // These values will store our colours on the way along
    float r = oldR, g = oldG, b = oldB;
    uint8_t byteR = oldR, byteG = oldG, byteB = oldB;

    // Go through each fade step
    const uint16_t numPixels = strip.numPixels();
    for (uint32_t step = 0; step < numSteps; ++step) {
        // Move one step towards the target colour
        r += stepR;
        g += stepG;
        b += stepB;

        // Round the colours to integers here so we don't have to do it repeatedly in the loop below
        byteR = (uint8_t)(r + 0.5f);
        byteG = (uint8_t)(g + 0.5f);
        byteB = (uint8_t)(b + 0.5f);

        // Apply the colour to each pixel
        for (uint16_t pixel = 0; pixel < numPixels; ++pixel) {
            strip.setPixelColor(pixel, byteR, byteG, byteB);
        }

        strip.show();
        delay(waitPerStep);
    }
}

As you can see, you pass it the old colour (which you're fading from) and the new colour (which you're fading to). As I mentioned above, this means your sketch has to remember which colour it previously used, as I don't think the library provides a way to read the current colour back.

I've included some optimisations in there to make it run faster. There's more you could do to optimise it even further, if necessary.

To use this, you'd do something like this:

// Fade from black to red and pause briefly
fade(0, 0, 0,  255, 0, 0,  100, 10);
delay(500);

// Fade from red to purple and pause briefly
fade(255, 0, 0,   255, 0, 255,  100, 10);
delay(500);

// Fade from purple to green and pause briefly
fade(255, 0, 255,  0, 255, 0,  100, 10);
delay(500);

I've made a couple of other changes compared to your own fade function function. First of all, I've made it so that you can set the number of steps to fade over. This can be quite useful because bigger colour changes will need more steps to look smooth.

I've also modified the wait parameter. In your code, you put the delay after the entire fade was complete, which seems like an odd approach. It makes more sense to allow a small delay between each step of the fade, so you can control how fast it goes.

In my example above, you can see the 100, 10 parameters at the end of each call to fade(). That means it will divide the colour change into 100 steps, with a delay of 10ms between each step. The result is that each fade will take roughly 1 second (not counting the time taken to actually update the LED strip).


ADC noise when sharing ground from external supplies i have resistor based sensor, when i test it using arduino connect to PC using serial monitor  without sharing ground to other circuit it has a nice value between 300-650 in adc range and the error/ accuracy reading just have about 5 value (ex: 607-612) if there is no condition change in the sensor.

But the problem comes when i sharing the ground to the other circuit. The accuracy is messed up bigger than 60 adc value (570-660) with the same condition without sharing ground.

My circuit is powered by PSU 24V and 24V driver to produce input signal for electric pressure regulator. The arduino ground is sharing because to control the input of the 24V driver. Here my circuit in the attachment.

So there is two ground from PC (i need it to use serial monitor) and the PSU 24V

How to eliminate the noise? Is there any way to control the 24v driver and read the sensor at the same time without sharing ground? Maybe using two controller with master/slave? Or there is any advice?

You've created what's known as a "Ground Loop".  You have 2 grounds in your circuit, your 24v PS has a ground and the PC supplying 5V to your Arduino has a ground.  They are not likely to be equivalent and will cause many unwanted side effects.

You can reduce some noise using RC or RLC circuits on your power supply pins.  It's probably best to use only a single power supply (and ground).


Stepper motor based clock movement with DS3231 I am working on a clock movement that is powered using a stepper motor and the GSM2 driver board. The delay between steps needed to achieve 1 rpm on the second hand works out to 25 ms. In my current setup, I am sending pulses to the driver board using the delay() function. This works reasonably well, although it is not accurate enough for me. To remedy this problem, I ordered a DS3231 RTC module, thinking I could use that to replace delay()/millis(). However, I can't figure out how to achieve millisecond resolution using the RTC. It seems like it should be strait forward given the oscillator on board the RTC is 32kHz. I am new to arduino programming and am out of my comfort zone with this one.

Does anyone know of a way to achieve the 25 ms pulses we need while still retaining the accuracy of the RTC? Is it possible to use the RTC to correct the output produced by the built in delay()/millis() function? How would you then translate that output to pulses sent to the stepper motor driver board?

Internet research produces some mixed results on whether or not this is possible. I have yet to see an example of a clock with millisecond resolution. The theory behind it makes sense, but I don't know where to start.

It is unclear, why you need the high accuracy, and you didn't include your code. So my explanations will be as broad as your question.

"millisecond resolution" is a broad term. Generally you have to consider 2 different errors.

The jitter for every millis() value
clock drifting over time

You can eliminate the second point quite easily using the RTC with the Time library. It uses the RTC as a reference, so that you don't have the clock drifting this much. Though, you would have to use the libraries functions for all time related things, since it does not change the value of millis() or it's siblings.

Also, for low differences in the range of a few milliseconds, you should better use micros() instead of millis() (if you are not using the RTCs functions).

  How would you then translate that output to pulses sent to the stepper motor driver board?

It is unclear, why exactly you need "millisecond resolution", and you didn't show us your code. But there are multiple Stepper libraries on the web, for example the standard Stepper library or the AccelStepper library (Accelstepper is more capable, don't know, if you need it). With the AccelStepper libraries you can set a certain speed and target position and then you simply call then run() method (haven't looked up the name, but there is definitely a function like that) until the desired position is reached. The method itself will only pulse the stepper, if it is time to do so. So you are freed from doing all the stuff with millis(), since the library is doing that for you.

Though the libraries are using the Arduinos internal time: millis() and siblings. To change that, you would have to change the library.


Programmatically Upload Arduino Sketch From Android App I am attempting to build an Android app from which I can can upload a .hex file to my Arduino(Leonardo). I am aware of a few apps in the Google Play store that are capable of this functionality but I can't seem to find any actionable resources on how to go about doing this. I am aware that the desktop Arduino IDE uses AVRDude to perform the upload but I don't believe AVRDude is available on Android so I'm at a complete loss here. Does anyone know how I would go about accomplishing this?

After some more searching I now know that the Leonardo(ATMega32u4) uses the AVR109 Protocol to flash new programs onto the hardware but I'm still at a complete loss as to what that process is and how I'd reproduce it in Java.

If I wanted to do this for a conventional Arduino I'd start by figuring out the operations against a serial API to talk to the bootloader, and perhaps test it against something exposing desktop serial ports to Java, as debugging Android host mode stuff is a pain given you have to use ADB-over-wifi. You might try to figure out how avrdude works, for example. Then I'd try to combine that with existing code that is out there for talking serial-over-USB to Arduino boards with the various device-side chipsets. For a leonardo type board the two pieces may be more tightly coupled.

Copy of Chris Stratton's comment which was acknowledged as an answer.


How to perform action if two rfid tag UIDs have been detected? I'm using an rfid-rc522 and I want to print to the serial a string of text if two rfid tags have been read in a given time period.

Essentially this:
 1. First tag is read (print to serial: Tag 1 has been read)
 2. Wait 2 seconds
 3. Second tag is read (print to serial: Tag 2 has been read)
 4. Print to serial: Tag 1 and Tag 2 has been read)
 5. Bonus: Keep this state - and then when a button is pressed (print to serial: Tag 1 and Tag 2 are finished)

I know how to read the UID and print to the serial if one is read.
Thank you so much for your help, it's greatly appreciated.

Here is my code so far:

#include <Adafruit_GFX.h>    // Core graphics library
#include <Adafruit_ST7735.h> // Hardware-specific library
#include <SPI.h>
#include <MFRC522.h>

// For the breakout, you can use any 2 or 3 pins
// These pins will also work for the 1.8" TFT shield
#define sclk 4  // SainSmart: SCL
#define mosi 5  // SainSmart: SDA
#define cs   6  // SainSmart: CS
#define dc   7  // SainSmart: RS/DC
#define rst  8  // SainSmart: RES

Adafruit_ST7735 tft = Adafruit_ST7735(cs, dc, mosi, sclk, rst);

#define SS_PIN 10
#define RST_PIN 9
MFRC522 mfrc522(SS_PIN, RST_PIN);

float p = 3.1415926;

void setup(void) {
  Serial.begin(9600);
  SPI.begin();
  Serial.print("Starting cornhole leaderboard...");
  mfrc522.PCD_Init(); // Init MFRC522 card
  Serial.println("Scan PICC to see UID and type...");
  // Use this initializer if you're using a 1.8" TFT
  tft.initR(INITR_BLACKTAB);   // initialize a ST7735S chip, black tab

  // Use this initializer (uncomment) if you're using a 1.44" TFT
  //tft.initR(INITR_144GREENTAB);   // initialize a ST7735S chip, black tab

  Serial.println("Initialized");

  uint16_t time = millis();
  tft.fillScreen(ST7735_BLACK);
  time = millis() - time;

  Serial.println(time, DEC);

  // large block of text
  tft.fillScreen(ST7735_BLACK);
}

void loop() {

  // Look for new cards
    if ( ! mfrc522.PICC_IsNewCardPresent()) {
        return;
    }

    // Select one of the cards
    if ( ! mfrc522.PICC_ReadCardSerial()) {
        return;
    }

    if (mfrc522.uid.uidByte[0] == 0xA4 &&
       mfrc522.uid.uidByte[1] == 0xB8 &&
       mfrc522.uid.uidByte[2] == 0xB8 &&
       mfrc522.uid.uidByte[3] == 0x96) {
          Serial.println("Nate has checked in to the game.");
          tft.fillScreen(ST7735_BLUE);
          tft.setTextSize(2);
          tft.setCursor(0, 0);
          tft.setTextColor(ST7735_YELLOW);
          tft.print("Nate ");
          tft.setTextColor(ST7735_WHITE);
          tft.println("has checked in ");
          tft.setTextSize(2);
          tft.println("to the game.");
          delay(2000);
          tft.fillScreen(ST7735_BLACK);
    }

    if (mfrc522.uid.uidByte[0] == 0x03 &&
       mfrc522.uid.uidByte[1] == 0xFD &&
       mfrc522.uid.uidByte[2] == 0xBC &&
       mfrc522.uid.uidByte[3] == 0x02) {
          Serial.println("Ted has checked in to the game.");
          tft.fillScreen(ST7735_RED);
          tft.setTextSize(2);
          tft.setCursor(0, 0);
          tft.setTextColor(ST7735_CYAN);
          tft.print("Ted ");
          tft.setTextColor(ST7735_WHITE);
          tft.println("has checked in ");
          tft.setTextSize(2);
          tft.println("to the game.");
          delay(2000);
          tft.fillScreen(ST7735_BLACK);

    }

}

What you can do is store the current time whenever a card is swiped, and then when another card is swiped check how long it's been since the last card was swiped

first create a couple of variables

unsigned long swipedTime;
int tag1 = 0;
int tag2 = 0;
int swipeTimeOut = 10000; // how much time in MS you have to swipe both cards

Next we'll jump down to where where you read the cards.

      if (mfrc522.uid.uidByte[0] == 0xA4 &&
           mfrc522.uid.uidByte[1] == 0xB8 &&
           mfrc522.uid.uidByte[2] == 0xB8 &&
           mfrc522.uid.uidByte[3] == 0x96) {

               ........

               if (tag2 == 1 && millis() - swipedTime < swipeTimeOut ){
                   // both tags have been swiped, print serial message here
                }

                tag1 = 1;
                swipedTime = millis();
        }

        if (mfrc522.uid.uidByte[0] == 0x03 &&
           mfrc522.uid.uidByte[1] == 0xFD &&
           mfrc522.uid.uidByte[2] == 0xBC &&
           mfrc522.uid.uidByte[3] == 0x02) {

               ........

               if (tag1 == 1 && millis() - swipedTime < swipeTimeOut ){
                   // both tags have been swiped, print serial message here
                }
                tag2 = 1;
                swipedTime = millis();

         }

You'll also want to come up with a system for resetting tag1 and tag2 to 0 or "checking them out".


Very long range wireless communication between two arduinos(500-1000 KM) I searched for very long range wireless communications between two Arduinos, but can't find solutions. I don't live in USA, In my country there are regions, where GSM does not work.
I want wireless communication approximately 500-1 000 KMs.
What are options without GSM for that distance wireless communication(500-1000 KM)?

What are options without GSM for that distance wireless communication(500-1000 KM)?

1) use the internet;

2) use narrow band transmission, like qrp;

3) use relays;

4) use satellite phones;

5) use a high-powered lw transceivers.

6) ...


Control Arduino via Wifi directly? I want to build an arduino-based RC Tank, which should be controlled with a notebook or smartphone (Android). Bluetooth would be an easy solution, but the range is a bit short for a RC Vehicle, so I want to controll it via WIFI. I found a ton of examples and tutorials on how to do that but all of them reqire a router which both the arduino and the Smartphone are connected to. Any idea on how to directly control an Arduino with an smartphone via WIFI?

If your computer/tablet/phone can act as a WiFi hotspot, you could use that to avoid the router. Many smartphones have that capability, as do many notebooks (as geometrikal mentioned, it's usually referred to as an 'ad-hoc' network on PCs). Create the network (or turn on hotspot capability), and connect to the network you created from your Arduino.


Is it possible to use ESP8266 modules interchangeably? I discovered that there are multiple types & versions of ESP8266 modules.

I'm wondering:

Build my application around one type (eg ESP-03) and in future swap the module with another (ESP-07), continuing to use the same library and code?

Given the lack of information online, I couldn't find an answer for this online.

yes they are interchangeable since they all use the same chip (esp 8266). However the pin outs of the different modules can (and will be) laid out different. So you have to watch out that your wires are connected to the correct pads on the module.

Also mind that different esp8266 modules can be (stock) loaded with different firmware. If you are using the AT firmware in your current arduino project it can be necessary to flash your new esp8266 module with the same firmware. If you are not sure how to do this you might have a look to the esp8266 forum


Arduino Due 16U2 Programming Port Documentation Are there any documentation or whatsoever on what the 16U2 does when trying to program the Sam3X in Arduino Due?

I reallynwant to know what's wrong with my made up board but can't get pass the No Device Found problem.

Been searching it but I can't find any. I can't understand the hex file burned on the MCU.

The 16u2 is merely acting as a usb to UART adapter. You can just as well use an ft232 or other serial adapter.

Of course the 16u2 needs firmware installing on it in order to function. That firmware is available (possibly bundled with the ide, or for download, not sure at the moment).


Smaller and cheaper alternative to Arduino Uno for permanent projects I have played a bit around with a Arduino Uno that came in a kit with a breadboard and components. Soon I would like to make some more permanent things.

I would prefer a smaller and cheaper unit than the Arduino Uno but that is almost as easy to use as the Arduino Uno, and very similar to use.

Is the Arduino Pro Mini 328 - 5V/16MHz a logical next step?
At 1/6 of the size of the Arduino Uno it is plenty small.
At 10 $ a piece the price is also good.

I understand that I must solder to get it to work. That should not be a problem.

Will I also need a USB serial board to program the unit?

I think the first best choice is to remove the ATMega328p-pu chip from your Arduino UNO and incorporate it into your final circuit.
The chips are only about $1.50.

That way, you can just use your UNO as a programmer instead of the final device that you deploy.

I'm not sure why there isn't more documentation about the proper way to remove the ATMega328p-pu chip and using it on your breadboard, after completing your programming.

I explain exactly how to do this on my blog: http://raddev.us/arduino/post/2018/07/03/arduino-uno-using-your-atmega328p-u-as-stand-alone

But, here are the basics.
First you remove the chip.  It will look like the following after you do so.  (Note: I'm using the Elegoo clone of an UNO).

Next, you apply power to pin 7 and connect pin 8 to GND.

Need A 16MHz Crystal

But, the chip won't seem to run your sketch at this point.
That's because you actually need a crystal to run at 16MHz.

The UNO board has that chip installed and that is why it works.
You can see it here:

Finally you add the 16MHz crystal and a couple of 22pF caps and your chip will run standalone (no UNO).

You add the crystal to pins 9 & 10.  You can see all the details by reading my blog entry or reading the atmega328 datasheet.

Finally, Just Wire Everything Else Up

After that, just wire the rest of your circuit up to the proper pins and you can run your ATMega328p-pu standalone.

It's actually a nice learning experience too.
Just buy replacement atmega328p-pu chips for your UNO and you can create all the projects you want to for very cheap.


Connecting two Arduinos via I2C while I2C Pins A4/A5 are already in use I have the following problem:
Since the BH1750 Sensor only supports two different I2C adresses, but i need to use 6 of those sensors, i wanna use 3 arduinos, 2 nanos, 1 uno and send the data from the nanos to the uno. Problem is that the I2C bus is already in use and while trying to send data, it does not work properly.
Is this even possible? When trying it out, i can't get anything correct

Update:

That's what i tried now:

Results i get are still not correct

#include <Wire.h>
#include <BH1750.h>

// This code will feature the use of 6 gy 30 light sensors

BH1750 active_sensor(0x23); // We will use this adress for stating the active sensor
BH1750 inactive_sensor(0x5C);

void setup(){

  Serial.begin(9600);

  // Setting the input pins for controling the addr pins of the modules
    pinMode(8, OUTPUT);
    pinMode(9, OUTPUT);
    pinMode(10, OUTPUT);
    pinMode(11, OUTPUT);
    pinMode(12, OUTPUT);
    pinMode(13, OUTPUT);

    digitalWrite(8, LOW);
    digitalWrite(9, LOW);
    digitalWrite(10, LOW);
    digitalWrite(11, LOW);
    digitalWrite(12, LOW);
    digitalWrite(13, LOW);

  // Initialize the i2c bus
  Wire.begin();

 // Here we will set the mode of the module
  if (active_sensor.begin(BH1750::CONTINUOUS_HIGH_RES_MODE)) {
    Serial.println(F("BH1750 Advanced begin"));
  }
  else {
    Serial.println(F("Error initialising BH1750"));
    Serial.println("Problem on 1");
  }
}

void loop() {
  get_values();

}

void get_values(){
  int i;
  Serial.println("----");
  for(i = 8; i<=13;i++){
    digitalWrite(i,HIGH);
    delay(50);
    int lux = 0;
    lux = active_sensor.readLightLevel();
    Serial.println(lux);
    delay(50);
    digitalWrite(i,LOW);
    delay(150);
  }
}

Use the ADDR pin as a chip select. Pull both pins high normally. When you want to talk to one, pull the ADDR pin low and use the ADDR = 0 address to talk to the selected device. Then you can have all 6 connected to one Arduino.


How does one **get** attributes for SD files? To be able to set the date and time of the files on my SD card I followed this answer: https://arduino.stackexchange.com/a/39127/49678

Now I am wondering How do I read the values out in the microcontroller?
To clearify, I get the correct timestamps when I remove the SD card and view them on a PC, but I also want to be able to read this on the microcontroller.

Inside SdFile.cpp on line 1025 there is a function called timestamp which is used to set the timestamp but I cant seem to find any function to read it.
https://github.com/adafruit/SD/blob/master/utility/SdFile.cpp

I would prefer a solution where I don't have to add it to the library myself.

The underlying problem I am facing is that I want to log files, and once the memory is full I which to remove the oldest files.

You need to get an SdFile object for your file then use the SdFile::dirEntry method to get the directory entry for the file.

The directory entry (struct directoryEntry) has the timestamps.


Arduino Pro Mini (3.3V version) input voltage range / tolerance I have a few Arduino Pro Mini clones (cheap Chinese stuff) and would like to power them with 12V power supply (same as fan voltage). According to the Arduino Pro Mini spec the RAW pin can take 3.35-12V (3.3V model). In practice this means a 12V PSU cannot be used as they are almost always over 12V with low load. I read that the voltage regulator in this board is capable up to 16V input. I tried plugging in a cheap 12V power adapter that read 15.1V with no load but a component on the arduino clone board actually exploded instantly. The board seems to work still when powered from usb programmer. Component that burned out is just above VCC, RST and GND pins.

Why did this happen? What did I just damage and most importantly what is a safe voltage level to use? I already have a few 12V switching power supplies it would be a shame if I could not use them.

Solution:

In the end it seems to have been a faulty arduino clone, faulty or poor quality power adapter or the fact that I powered the power supply before plugging it to the board's RAW input pin. The cheap 12V switching power supplies work just fine even though my multimeter registers a voltage spike as high as 30V during power up.

The genuine Pro Mini's use a MIC5205 regulator which should accept up to 16V at it's input normally, with an absolute maximum of 20V. It's unlikely that the regulator would be damaged by 15.1V.

However, the component you have indicated that has blown is a capacitor. SMD capacitors are available in different voltage ratings, typically 4V, 6.3V, 10V, 16V, 25V, 35V and 50V (and above, but let's ignore them for this). It's rare to see any intermediate values.

SMD capacitors are very intolerant of being used at a higher voltage than specified. This is especially true of electrolytic and tantalum capacitors. The blown capacitor on the genuine Pro Mini's is polarised (the grey band not he package and the schematic indicates this), so we can infer it is either electrolytic or tantalum. A 10µF SMD electrolytic is unlikely to be in this package, so it is almost certainly a tantalum.

Sparkfun sell 10µF tantalums, and they are rated at 16V. It's quite likely these are the same ones used on the Pro Mini. 15.1V is very close to 16V - in fact, if this is a poorly smoothed power supply, the meter might show 15.1V but the peaks could well be 16V or even 20V. It is recommended that you de-rate the voltage ratings on tantalums by 50% at least.

It's really important to realise that most low-cost DC power supplies are not regulated and produce a very bumpy output voltage with no regulation:

Tantalums also have no tolerance for reverse voltage, so if you did apply reverse voltage, it would pop.

So it is quite likely that you over-volted the cap and blew it. You could replace them with higher rated capacitors - I would go for 35V ones if you want to supply 15.1V. Desoldering and desoldering a single capacitor is relatively easy as long as the pads haven't been damaged. Realistically, you could use a normal leaded 10uF electrolytic between RAW and GND instead of the SMD one.

EDIT: However, looking at the data sheet for the regulator, it shouldn't really matter if that 10uF is there or not:

  A 1μF capacitor should be placed from IN to GND if there is more than
  10 inches of wire between the input and the ac filter capacitor or if
  a battery is used as the input.

Some regulators absolutely require an input capacitor, with others it is just advisable. This looks like it is just advisable. So if it isn't working on external power now, you may have blown the regulator as well.

Even if the clone board uses a different SMD regulator, their characteristics are all very similar. As stated, some do need a capacitor on the input to work, so replacing it might fix it.

There is a further consideration that dropping from 15.1V to 3.3V on a SMD regulator is not a great idea. You will need to burn off a lot of power.

The MC5205 can dissipate 455mW with a minimal PCB footprint (which the Pro Mini has) with a 25°C ambient:

So, we know the maximum power we can dissipate, and we know the voltage drop - we can then calculate the current:

P = (Vin - Vout) * I

0.455 / (15.1 - 3.3) = I

I = 38.5mA

This isn't very much at all. You might want to consider regulating off the board, and probably with a switching regulator rather than linear regulator.

I also note your PS:

  the ground of the 12V PSU is shared with Arduino ground pin, not sure
  if this might be the cause.

If they weren't shared, there would be no way that this could work. They need to be shared otherwise the Vcc from the power supply is not referenced to anything and may as well not be there.


Cannot get any readings from DHT22 Sensor connected to Arduino M0 Pro I have directly connected a DHT22 to my Arduino M0 Pro. I have put a 10k Resistor across the Data & V+ of the sensor pinout. The data is connected to pin 5 and I have it connected to 3.3V output of Arduino.

I am just trying to see some readings from the sensor via the SerialUSB console. I have downloaded and unpacked the DHT libraries that I got on the Adafruit website/GitHub. As far as I know I have these libraries in the right directory - C:\Program Files (x86)\Arduino\libraries\DHT...
I also have installed the Adafruit Unified Sensor library on the IDE.

I am trying to use the Tester program that is provided, this compiles ok but the SerialUSB printout prints:

Failed to read from DHT sensor!
Failed to read from DHT sensor!
Failed to read from DHT sensor!

And so on...

I have tried another DHT22 sensor to no avail.

The only part of the code I have changed is the pin number and changed from Serial to SerialUSB.

Not sure if I have to change anything else? Or am I doing something really silly!

Here is the code:

// Example testing sketch for various DHT humidity/temperature sensors
// Written by ladyada, public domain

#include "DHT.h"

#define DHTPIN 5     // what digital pin we're connected to

// Uncomment whatever type you're using!
//#define DHTTYPE DHT11   // DHT 11
#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321
//#define DHTTYPE DHT21   // DHT 21 (AM2301)

// Connect pin 1 (on the left) of the sensor to +5V
// NOTE: If using a board with 3.3V logic like an Arduino Due connect pin 1
// to 3.3V instead of 5V!
// Connect pin 2 of the sensor to whatever your DHTPIN is
// Connect pin 4 (on the right) of the sensor to GROUND
// Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor

// Initialize DHT sensor.
// Note that older versions of this library took an optional third parameter to
// tweak the timings for faster processors.  This parameter is no longer needed
// as the current DHT reading algorithm adjusts itself to work on faster procs.
DHT dht(DHTPIN, DHTTYPE);

void setup() {
  SerialUSB.begin(9600);
  SerialUSB.println("DHTxx test!");

  dht.begin();
}

void loop() {
  // Wait a few seconds between measurements.
  delay(2000);

  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  float f = dht.readTemperature(true);

  // Check if any reads failed and exit early (to try again).
  if (isnan(h) || isnan(t) || isnan(f)) {
    SerialUSB.println("Failed to read from DHT sensor!");
    return;
  }

  // Compute heat index in Fahrenheit (the default)
  float hif = dht.computeHeatIndex(f, h);
  // Compute heat index in Celsius (isFahreheit = false)
  float hic = dht.computeHeatIndex(t, h, false);

  SerialUSB.print("Humidity: ");
  SerialUSB.print(h);
  SerialUSB.print(" %\t");
  SerialUSB.print("Temperature: ");
  SerialUSB.print(t);
  SerialUSB.print(" *C ");
  SerialUSB.print(f);
  SerialUSB.print(" *F\t");
  SerialUSB.print("Heat index: ");
  SerialUSB.print(hic);
  SerialUSB.print(" *C ");
  SerialUSB.print(hif);
  SerialUSB.println(" *F");
}

Found what the fault was, it was a solder short between pins on a custom PCB that was sitting on top of the Arduino board. My bad! At least I have it working now!


Arduino is freezing during Serial.Print() while passing a char array This problem is on an Arduino Due.
I am trying to populate a char array buffer that is receiving information over a serial port. I am reading the information off of the serial port and storing it into a buffer array and passing it back to the original function call.

First is the code that initializes the buffer and writes the data that the Serial requires in order to issue a response. This function compares many types of expected responses (uint32_t expect) and returns a confirmation as an int.

//Receive a cmd to send over serial and expect a certain response
int SendCommand(char * cmd, uint32_t expect){
  int cmdSuccess = 0, j=0;
  char buffer[500];
  memset(&buffer,0,sizeof(buffer)); //0 out the buffer
  Serial3.print(F(cmd));
  delay(500);

  Response(buffer);

  if (expect == EXPECT_OK){
    for(int i=0;i<sizeof(RESP_OK);i++){
      if(buffer[i]==RESP_OK[i]){ //RESP_OK is an example of a response of length 6
        j++;
    }
  }
    if(j==sizeof(expect)-1){Serial.print(F("\nGOOD RESPONSE!\n")); return 1;}
  }
  else{return 0;}
  delete [] buffer;
}

void Response(char buffer[500])
{
  int index = 0; //message index;
  int count = 0; //used for timeouts
  while(1)
  {
  if(Serial3.available()) //Data will be coming across serial3
  {
    char data = Serial3.read();
    buffer[index]=data;
    index++;
  }
    count++;
    delay(100);
    if(count == 50){
    Serial.println(F("\nEnd of Response"));
    break;
  }

}

Edit: fixed the braces.

Right now, this code is hanging at the last part of Response right before break;. Am I having memory issues by the time it reaches the println at the end?
That last println was actually working until I began passing the buffer as a pointer and not returning it a char* and declaring void Response as char* Response. But the problem with this approach was that the buffer would reduce to sizeof(buffer) = 4 and would strip off the rest of the information when returned.

Edit: As Matt suggested down below, I declared a static const size_t bufferSize and pass it into the Response() call as well as passing in buffer as char*. Then I reset the buffer size by buffer = (char*)malloc(bufferSize).

What I still don't understand curious is the sizeof(buffer) after Response which is returning 4. However, 6 characters are stored into the array during Response. I've changed the pointer call to Response(char* buffer, const int size) with the following:

  if(index<size){
  buffer[index]=data;
  index++;
  }
  else{Serial.print(F("Buffer length exceeded!"));}

Thanks so much for your time!

Sorry, but there are quite a few issues with your code any of which may be contributing to your problem.

memset(&buffer,0,sizeof(buffer)); //0 out the buffer you are taking the address of a pointer and passing it to memset().  buffer is already a pointer of type char*.  Its working, because address of the pointer is the same address as buffer[0], but it is wrong and won't always work.
Serial3.print(F(cmd)); I have never used the F macro, but my understanding is it tells the compiler to store the string in flash memory.  cmd is a variable on the stack, a parameter to the function, so my guess would be the compiler is ignoring the F macro.
500 using a literal value in more than one place is opening you up to problems.  I think you should declare static const size_t BufferSize = 500;
void Response(char buffer[500]) It would be better to pass in a pointer to a char and the size as the parameter, (const char* pBuffer, const int& size) you can treat it the same within your function or you could pass a pointer to the next available item and then return the updated pointer.
1for(int i=0;i strlen(buffer))` then buffer can't contain RESP_OK (its quicker too).

Also the Response function won't compile, because you have too many closing braces (I assume its a copy and paste error).  This is the cause of you code hanging if(Serial3.available()) is inside a while(1) and there is no way of breaking out.  So if you just fix that you code will run.


How do I read numbers from a serial sequence I have read through a number of posts including How do I split an incoming string? However I cannot work out how to extract numbers from a serial string.

My challenge is this;

I send a serial command 'freq\r' to a radio which will return a string like this 'FREQ: 10138.7 RX, INHIBIT TX'. The only thing I want out of this is the 1013 so I can then manipulate it and send out a second serial port. It sounds easy enough but I just don't seem to be able to extract those numbers easily because I don't have a separator to use.

The other thing is if the number is below 10 e.g. 9138 I only want to extract the first 3 numbers then add a leading 0 so I end up with 0913.

Once I have the four numbers I can then divide them so I end up with e.g. 09 and 13 or 10 and 13. I can then send these as HEX to my second serial device.

If you are wondering what the numbers are they are frequencies in kHz which I am extracting from a radio then converting to HEX to tune a pre-selector.

Any help would be greatly appreciated as this is my last stumbling block on this serial translator project. I hope this makes sense.

Thanks

Callum

I don't have a separator to use

You do. There is a space before the integer part of the frequency, and a
decimal point just after it. You can use strchr() to find them. Then,
you will have to prepend a zero if needed, and terminate the string one
character before the decimal point.

The following code does this by overwriting the original string. If you
need to keep that string, you will instead have to copy the relevant
characters to another buffer:

char * get_freq(char *message)
{
    char *space = strchr(message, ' ');
    char *dot   = strchr(message, '.');

    if (!space || !dot || dot - space < 5)
        return NULL;    // invalid message

    if (dot - space == 5)
        *space = '0';   // prepend a zero

    *(dot - 1) = '\0';  // terminate the string

    return dot - 5;
}


Python script not reading from serial unless teensy is rebooted I want to send some analog sensor data from a Teensy 3.2 to a mac running a python script (I am using the usual pyserial module and I send data using Serial.print() in the arduino sketch). I am using Teensy but I guess the same would be true for an Arduino Uno.
The teensy is correctly sending on the serial port the data, as I can see it using the serial monitor. However, only the first time that I run the python script the data are handled by the script itself, if I stop the script then no data seem to be read in the serial buffer. To make the script work I necessarily have to re-launch the Arduino IDE and then upload the sketch.

Indeed the second time I run the script (after having stopped it), I can see that the pyserial function serial_port.inWaiting() does not give any data.

if (serial_port.inWaiting() > 0):
   print("serial_port.inWaiting() > 0") # does not print anything the second time I launch the script

I have checked that the second time that I launch the script the serial connection is open (using self.serial_port.isOpen())

What is preventing the python script to get the serial data the second time? Why serial_port.inWaiting() is not seeing that there is data in the input buffer?

In the arduino sketch code I have added the line while(!Serial); in void setup()

EDIT: I post the code. This is the arduino code (I am testing on teensy so no initial handshaking is required as teensy will not reboot)

int sensor = 0;

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

void loop() {

  sensor = analogRead(0);
  Serial.print(sensor);
}

And this is the python code:

#!/usr/bin/env python3

import serial
import time
import signal
import sys

def keyboard_interrupt(signal, frame):
    serial_port.close()
    time.sleep(2)
    exit(0)

serial_port = serial.Serial("/dev/tty.usbmodem1225061", 115200)

signal.signal(signal.SIGINT, keyboard_interrupt)
signal.signal(signal.SIGTERM, keyboard_interrupt)

if serial_port.isOpen():
    print(serial_port.name + ' is open...')

while True:
    if (serial_port.inWaiting() > 0):
        sensor = serial_port.read().decode("utf-8")
        print('sensor: "{}" '.format(sensor))

Serial communication is always terminated with a specific character (usually \n). The receiving device will accumulate the incoming bytes in a buffer until it receives this terminating character.

To fix the problem simply change the last line of your arduino loop to Serial.println(sensor);

Also note that the arduino might be faster than your python script, meaning that you will get several sensor values per readout. If that's the case you have to add a short delay in the arduino loop.


Serial communication questions I have to arduino's which are communicate using rx/tx. Arduino1 (A1) send data over serial to Arduino2 (A2). My questions are:

1 - If A1 do Serial.print each 50ms and A2 reading serial each 100ms which value will get A2? For example A1 send "1" and after 50ms send "2". Considering A2 will read serial after 100+ ms it will get "2" ?

2 - If A1 send data each 100+ms and A2 read at 50ms which value will get A2 between? For example A1 send "1" and A2 read "1" when read at 50ms but when it read again after 50ms (during that time A1 didn t sent anything ) will read again "1" ?

Thank you

1 - If A1 do Serial.print each 50ms and A2 reading serial each 100ms which value will get A2? For example A1 send "1" and after 50ms send "2". Considering A2 will read serial after 100+ ms it will get "2" ?

The Arduino has a 64 byte (software) buffer.  You will get the numbers in sequence up until that buffer overflows. Then it's not easy to predict what the results will be.

Probably something like:

121212121[...]2121212121212111111111111111

  2 - If A1 send data each 100+ms and A2 read at 50ms which value will get A2 between? For example A1 send "1" and A2 read "1" when read at 50ms but when it read again after 50ms (during that time A1 didn t sent anything ) will read again "1" ?

If there is nothing in the buffer the read function returns -1.  That can be mapped (IIRC) into ASCII (depending on your software) as ÿ so you would get:

1ÿ1ÿ1ÿ1ÿ1ÿ...

You should read my tutorial on reading serial on the Arduino.


Where does the sound come from this board? As the question says, i can't figure out where the sound comes from on this board that i bought, nothing on the manuals and can't see any speaker on the board... It is a "RFID Proximity Entry Door Secure Lock Access Control System"

Thanks.

That looks like a piezo buzzer, the component that had the sticker on it. It's likely louder now, with the sticker removed.


w5100 and nrf24l01 - SoftSPI - Radio not starting I had posted some questions about this project earlier this week. Arduino uno + w5100 ethernet shield + nrf24l01 transeiver.

The w5100 is running a webserver to accept GET requests and parse out the variables - Works all the time

The nrf24l01 is acting as a transmitter and sending data out to other nodes - Only works with no Ethernet code.

What doesn't work is both at the same time. With everything hooked up it parses get fine, gets the variable but I can't transmit it since the radio never seems to fire up. Remove all the ethernet code and leave just the radio code it sends fine.

Code here. http://pastebin.com/SMWC9x4F it errors at 146. Which I assume is the radio never starting since the:

radio.printDetails();

does nothing.

I'm using manicbug's library.

I use the EXACT same send bits in that file to test wireless communication, it works. I only need it to transmit wirelessly when it get data from the network.

Pinouts:

CSN -> 10
CE   ->  9
MISO -> 12
MOSI -> 11
SCK   -> 13
VCC   ->  Separate 3.3 source, not the arduino
GND  -> GND

My guess is this is because both are using SPI.

Tried the softspi method http://pastebin.com/4mv612B7 .

Same thing. I can post GET to it, parse out variables but nothing on the radio side. And I still get no output from radio.printDetails() so it just must not be starting. Commence hair pulling..

EDIT: Bloody hell, printDetails() relies on printf...... that would have been handy to figure out an hour or two ago.  I can get details now. still having communication issues.  Will post more debugging information in a bit.

Issue one:  .printDetails(); uses printh.  If you don't have that included you won't get the information.

Issue two:  The ide gets confused when you have two libraries with the same file.  I compiled my receiver with the softspi file. Once I put the right library in it works.


How to wait Arduino ready with ANY method? Recently I knew, that Arduino restarts any time somebody accesses it's serial port. I was trying to use this feature so that for each request Arduino restarts and give answer on request. Unfortunately, I found this is impossible with shell script, because shell script can't keep port open all time I send requests and wait responses: Arduino restarts on each port touch.

So, I wrote simple C++ program:

#include <iostream>
#include <fstream>

using namespace std;

void help() {
    cout << "bmp180dims usage:" << endl <<
            "bmp180dims port command" << endl;
}

int main(int argc, char* argv[]) {

    if( argc != 3 ) {
        help();
        return 0;
    }

    fstream port;
    string answer;

    port.open(argv[1], std::fstream::in | std::fstream::out);

    port << argv[2] << endl;

    port >> answer;

    cout << answer << endl;

    port.close();

    return 0;

}

Since this program has explicit open and close statements, I was thinking, this program will wait for Arduino answer, because of stream reading functions. But I failed again: this program returns nothing as if it is not waiting.

Why?

Apparently, the only way to communicate with Arduino, is to have daemon program, which always listen it's port. Is this really so?

Arduino-side code is here: How can program/arduino restarted by IDE?

Again, you're not waiting for the bootloader to complete before sending your text:

port.open(argv[1], std::fstream::in | std::fstream::out);
// Board resets and enters bootloader

port << argv[2] << endl;
// You send argv[2] to the bootloader

port >> answer;
// The bootloader doesn't understand what you sent so doesn't reply with anything

You must wait for the bootloader to complete before sending ANYTHING to the Arduino.

The two ways you can do that are:

Insert a sleep(3); immediately after opening the port to give the bootloader a chance to time out and start running your sketch, or
Provide an initial "I Am Ready" message from your sketch that your C++ program waits for before sending the text you want to send to elicit an answer.


Arduino standard libraries location I want to read the source code of an arduino library that comes with the IDE.
Specifically the GSM.h

I dont know the location of the standard libraries that come with the IDE.

I only know the location of the user installed libraries.

So where is the source code of GSM.h?

Ok, i found out the location.
In Win 7, it is C:\Program Files (x86)\Arduino\libraries


Bluetooth connection to HC-05 paired but not connected (in Linux) I have an Arduino Uno connected to an HC-05 Bluetooth sender/receiver chip. I am trying to create a Bluetooth connection between my Acer laptop running under Ubuntu 14.04 LTS and the HC-05 chip.

Ubuntu detects the HC-05 chip, as can be seen below.

phodor@ubuntu: hcitool scan
Scanning ...
    11:22:33:44:55:66   HC-05

I am able to create a pair between my laptop Bluetooth device and the HC-05 chip. However, I am unable to create a connection with that pair from the Ubuntu interface. The "Connection" button cannot be clicked on, as you can see on the figure below.

I tried creating a connection using the terminal, but after that the terminal still did not detect any connection.

phodor@ubuntu: sudo hcitool cc 11:22:33:44:55:66
[sudo] password for phodor:
phodor@ubuntu: hcitool con
Connections:

I also checked that my computer Bluetooth device was working.

phodor@ubuntu: hcitool dev
Devices:
    hci0    AA:BB:CC:DD:EE:FF

Any idea why the connection cannot be created ? Any idea on how to do it using the Ubuntu interface or the terminal ?

you can try this website for more information

http://wiki.micropython.org/official-accessories/Bluetooth-module-HC05


Multiple arduino Wireless communication I would like to know what device and model to use for an application where I will have 1 arduino as a master micro controller waiting to receive data from 5 slave arduino microcontrollers.
The Master arduino will be connected to local network via Ethernet cable so once it receive data from a Slave controller it needs to post to server the information, get a response back and in case the response is a "true" value then the Master need to talk back to the Slave in order to turn a LED on.
There will be cases when maybe 3 of the Slaves will send data at the same time, this doesn't mean at exactly the same millisecond. So I don't know if there will be data lost.
I was reading that Xbee maybe is the best device because it has a feature that will hold the data until there is a success communication with slave.

Is this a doable and "easy" task using Xbee? Anyone that already try to do something like this that can guide me?

I was reading that there is a device nRF24l01 that is very cheap and can do exactly what I need. Just that I don't really know how to start.

Appreciate any advice or help.

It really depends on the communication range and context required.

If your slaves are within 10-20 meters from the master device and the environment is not polluted (in terms of magnetic field) you can achieve good results with very inexpensive nRF24L01+ modules which operate in the 2.4GHz.

If you need to cover greater distances (in the order of 100 meters) or a polluted environment then you have to resort to shorter wavelengths or more powerful devices, but that brings in the question on how are you powering your slaves: on battery power those ranges get pretty power hungry.

Generally speaking I would say this question should be rejected as it's going to start a debate rather than provide a solution.

You can get some introductions on how to use nRF24L01+ modules simply searching online:

some posts on my blog
the Arduino library I always advice
a pretty valid guide


SoftwareSerial runs out of "text" space on ATtiny I have an ATtiny and am trying to send a very large byte array stored in a separate .h file over SoftwareSerial:

for (int i=0; i<numElements; i++) {
    softSerial.println(myList[i]);
}

I imagine it will very slow, which is fine, but I'm getting a cryptic error when compiling:

Firmware.ino.elf section `.data' will not fit in region `text'

It seems that this is due to the println() command running out of memory for some reason – if I comment out the println() command everything works fine. How to fix this?

Your sketch doesn't fit into program memory of the ATtiny. If you comment out the println of the array, the compiler evaluates that the array is not used and doesn't attach it to the program. Then the program fits into memory.

EDIT
Chad suggests some good alternatives below, if you need to store more data than flash or PROGMEM will allow.


Binary message formatter I am currently developing an IoT device with arduino and i want to minimise the data payload. First i used json which is not very efficent in fixed messages (the format will always be the same). Then i found something like messagepack which also sounds nice but i think you could do even better with just binary. I hope to find something like that:

I have a message for example:

#BOOL#INT#INT#FLOAT#BOOL#STRING#

The position of this variables never change so i could represent the message in binary and i could save a lot of bytes. Is there any library which can de/encode such formats and generate messages from given values?

If not i think it would be very useful in further IoT devices!

Passing messages across computers and/or microcontrollers with different architectures can be a real pain (endianness...). So do not fall into NIH / reinventing the wheel traps but keep standing on the shoulders of giants! Several message serialization protocols exist.

BSON
MessagePack
Protocol Buffers
CBOR (Concise Binary Object Representation)
...

Several implementations of such protocols exist (even for Arduino).

I suggest to have a look in a search engine for such protocols and add Arduino.

I've found:

BSON

ardubson

MessagePack

msgpack-mcu
arduino_msgpack
MsgPacketizer
msgpack-arduino
ArduinoJSON serializeMsgPack / deserializeMsgPack

Protocol Buffers

nanopb

CBOR

Arduino-Cbor

...

PS: You might read https://scottlocklin.wordpress.com/2017/04/02/please-stop-writing-new-serialization-protocols/
and have a look at https://xkcd.com/927/
Just choose a giant compatible with your requirements ;-)

https://en.wikipedia.org/wiki/Comparison_of_data_serialization_formats may help


please help with my arduino My problem is when I run code like this:

char directioN;

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

void loop()
{
  if (Serial.available())
  {
    directioN = Serial.read();

    switch (directioN)
    {
      case 'F':
        break;

      case 'B':
        break;

      case 'R':
        break;

      case 'L':
        break;

      default :
        break;
    }

    Serial.print("direction is:");
    Serial.println(directioN);
  }
}

My serial monitor add another input, but the second one is empty; this happened here with char both as with int.

But when i tried the same code in tinkercad it worked fine.

So do I really need a new ATMEGA328 or it can be done by software or something?

**I use an Arduino Uno

So why you don't just ignore it?

if(directionN >= 32){   //check if char is readable ascii character
  Serial.print("direction is:");
  Serial.println(directioN);
}


Arduino radio communications I have an Arduino and I am building a space satellite, just for fun. I'm not going to launch it obviously.

I have built all the sensors and everything works. I was looking into communication because if a satellite is in space it needs to send down the data.

Is it possible to have radio communication between two Arduino or an Arduino and something else that are 100km apart, it doesn't need to particle, I'm just wondering if it is possible and how it works. Is it possible without going out to buy shields?

There are three basic factors that control long distance communication:

Transmitter Power
Receiver Sensitivity
Signal Directionality

The more transmission power you have the "louder" your signal is at the receiver.

The more sensitive your receiver the "quieter" the signals it can pick up.

The more directional (focussed) your signal is the more arrives at the receiver and the less gets sent off elsewhere.

So you would think get all three of those and you're laughing, but it's not that simple:

High power transmission requires high-power power source
Good focus requires heavy and bulky antennae.

Neither of those are very good on a satellite, since you want it to be as small and light as possible and use as little power as possible.

So in general you have a medium to low power transmitter on the satellite with reasonable directionality, and put all the bulk on earth.  That is why satellite dishes are so big.  They give good focus, and the large size captures a lot of the signal making them more sensitive. You can also use very precise electronics to amplify the signal more.

There is, of course, nothing like that in a shield format, so you would have to create your own. The transmitter isn't so hard, since you don't want to have anything too meaty - the hard part comes when you want to make the base station.  If you can afford enough power to transmit a strong enough signal and have it with enough directionality you can use a satellite TV dish (not a little Sky dish, one of the bigger solid round ones - Sky satellites actually have quite powerful transmitters and the massive solar panels to go with it; not really practical for a small home-built satellite).  Getting the receiver and LNB (Low Noise Booster) tuned properly as well is vital - unless you're transmitting at the same frequency as the satellite the dish is intended to receive (which you mustn't or there'll be a lot of annoyed people around - there are specific frequency ranges you are allowed to use) then you will need to ensure the antenna is exactly the right length and that the LNB amplifies and filters the right frequency range.

Once you have got over all those hurdles the receiver is just a simple receiver.

The actual transmitter and receiver circuits themselves can be something fairly off-the-shelf (the lower the frequency the better since that goes further than higher frequencies) - it's what goes between - the antenna and amplifier - that makes it much more special and long range.


Is defining a function improves speed rather computing average for each analog input separately My Arduino controller reads data coming from four different sensors. After the data is read, I individually compute four input average values. I understood that I am having the same lines of code repeated four times. Instead, I want to define a function with an analog pin as input and compute the average. My code is working fine. The question I have is, will this function improve the speed, reduce memory?
My code:
// Samples average
sample_cnt = 1000;

//// Input the pin number and compute average value
float Average_input_value(int analog_pin){
  float avg_val = 0;
  for(int i=0;i<sample_cnt;i++){
    avg_val += analogRead(analog_pin);
  }
  // Divide by Sample count to get the average value
  avg_val = avg_val/sample_cnt;
  return avg_val;
  }

Writing the code out four times, in line, is a little bit faster than calling a function because the function call and return take some time, and the loop instructions take some time, and neither of those contribute to the average calculation.
Writing a function that you use four times, however, is much more readable, is much easier to fix if you've made a mistake because you can fix it once instead of four times, and is much easier to change or replace for the same reason, if that ever becomes necessary. Besides, a good optimizing compiler can often decide when to rewrite your loop as inline several repetitions of the loop contents (called "unrolling the loop"), so hand optimizing is probably not worthwhile.
Where your function will win over 4 repetitions of the calculation code is in the code-space needed. The function is more compact, but slightly slower.


When I open a COM port some pins on Arduino Uno goes low for about 2 seconds I have no idea why this is happening, but after I open COM port to talk with my Arduino (I click "Open" in RealTerm), the state of some pins goes from high to low for about 2 seconds and then goes back to high. Here's my code:

void setup()
{
  pinMode(5, OUTPUT);
  digitalWrite(5, HIGH);
  Serial.begin(9600);
}

void loop()
{
}

In this case pin 5 will behave this way. I've checked it also for pin 6 and pin 8 and they behave in the same manner. I suppose more pins act like that. Why is this happening?

What you see is expected: that's because opening the USB connection to the UNO will automatically trigger a reset of the ATmega chip of the board, hence your sketch will be executed from scratch, ie setup() will be called again then your loop() repeatedly.

Hence what you observe in detail:

open USB connection from PC
open USB connection on Arduino UNO
UNO USB chip (an ATmega16u2) triggers a RESET of the MCU (an ATmega328P-PU)
On reset, the MCU sets all pins to INPUT, i.e. high impedence, hence no voltage can be measured on any pin
Then the bootloader starts, performs some intialization and starts your sketch
Your sketch executes first setup(), so your pin is put in OUTPUT mode and set to HIGH: its voltage is thus measurable (5V)
your sketch loop() gets executed "forever" i.e.until a new reset or power supply disconnection


Arduino Mega read of serial encoder read at 1,024,000 baudrate? Reading a 1.024m baud rate 77 bit stream from a serial encoder- begin.serial1(1024000); is accepted - but no idea if UART can actually run there.

In the screen grab, channel 7 is a 8 microsecond clock pulse generated by the Arduino, channel 6 is the encoder response - always begins 13 microseconds after rising edge of clock pulse, first part is always 10101101, after that it's pretty random as encoder rotates.

I tried unsuccessfully to read the pins at that speed, no way, then tried reading the repeating data at synchronous microseconds +1 to try reading one bit at a time through sequential 77 bit words while not rotating - but clocking varies in Arduino program by up to 8 microseconds over the 2 millisecond repeating patterns though.

I tried the serial read through serial1 port, getting some data, but random... with no terminator to rely on, wondering if anyone has a suggestion as to how to clear/load serial buffer after a long pause (long being almost two milliseconds) followed by the 10101101 that always starts the next read (but could possibly repeat inside of it).

I'm a newbie to these things, just tinkering around thought decoding a serial encoder would be fun... many many many hours later, have learned a bit about them and more so learned how little I know about them :)

I think the problem is that there is more to serial I/O than just bits coming in. Otherwise, if nothing was sending, you would always read 0 from the serial port. Serial has a start and stop bit, for example. I doubt you could use the hardware serial to read in random bits.

If you are going to do this in software, you will have less than 16 clock cycles per bit - enough time to run about 15 instructions. It is not impossible, but very difficult.

There are two ways to read the data in code.

Option 1: Disable interrupts, and hand-write assembler that takes exactly the right amount of time. If you branch, make sure all branches take the same amount of time. I think all assembler instructions on Atmel take 1 cycle. You will need to pad out your loop to a predictable size. At 1.024mhz, the clock will drift by 2.4%, which means you'll either have to supersample (e.g. take one sample every 12 instructions, then throw away the samples closest to the clock interval) or you'll have to make some loops longer than others. If you store 8 bits per byte (as opposed to having an array of 77 bytes, storing 1 bit in each, which would be quicker), then you might get away with making "move to next byte" a different length.  Try to measure each sample in the MIDDLE of the allowed period, or as close to it as you can. You may have to unroll your loops (i.e. instead of "repeat this 77 times", do "do it, do it again, do it again....).

Or you might be able to write an ISR - Your ISR would have to be very short, basically "write the current time to a pre-defined array". Now you have 15 instructions to get the data out, but padding it OUT isn't so critical. With this method, you will get one datapoint per CHANGE (rising or falling signal). I don't know if micros() would be quick enough. Then, once the read is complete, you can post-process the data at your leisure. The ISR will be called at the start of the clock cycle following the change in signal, so this is likely to be easier.

UPDATE:

Micros only has a resolution of 4 microseconds, so you will have to make your own "clock". The easiest way to do this, is to set a counter with about how long you think it will take (, then hand-code a loop to decrement this, until zero. As far as I can make out, the decrement loop should take 2 cycle (decrement the counter, if-not-zero jump back to decrement). So if you start it at 800, it should take 100ms to reach zero. Remember that the ISR will stop the counter for the duration, you will need to compensate. Make sure that this loop isn't optimized out! Your ISR will be: copy the (above) counter into an array, increment your array pointer by 1 (so next time you put it in a different slot in your array). After the counter reaches zero, disable your ISR, and find the difference between each number and the next; add a constant (worked out by trial and error), round to the nearest 8 (which should be pretty close). Divide by 8. The first result should be the delay to the start of the data (first 1); the second will be the number of consecutive 1's, then the number of consecutive 0's, etc.


Can Atmel Studio 6 Simulator simulate SPI? I am trying to do PAL composite video output with Arduino Nano. I am using Atmel Studio 6, not the Arduino IDE. I am sending out the picture data via SPI. On the TV I could not see the text I tried to produce, so I tried to run my program in the Atmel Studio simulator (to use it as a logic analyzer). But in the resulting stimuli file I also do not see the MOSI pin changing.

I am using the A0 pin (PORTC bit 0) to send out the sync signal, that appears correctly in the output .stim file: PORTC changes exactly at the right time. But PORTB does not change at all.

My program can definitely be buggy, but that is another topic... the question is, can Atmel Studio Simulator simulate the SPI at all?

No Atmel Studio cannot simulate SPI.

The fact that you are using SPI makes me think that you are using the MAX7456 IC or even the SparkFun On Screen Display Breakout which uses this same IC.

You can generate composite video just by using a few resistors and an Arduino.

I have found a number of sites on Google who have used the Arduino to output PAL composite video to display the Pong game on an old TV.

http://searle.hostei.com/grant/AVRPong/index.html
http://www.makeuseof.com/tag/how-to-recreate-the-classic-pong-game-using-arduino/
http://www.instructables.com/id/2-player-Pong-using-Arduino/
http://forum.arduino.cc/index.php?topic=8708.0
http://apcmag.com/arduino-project-7-build-a-retro-gamebox.htm/
http://electronics.divinechildhighschool.org/Home/electronics-spring-2012-1/arduino-pong


How to save the SHA256 with HMAC into a variable instead of serial print? #include "sha256.h"

uint8_t hmacKey1[]={
0x65,0x63,0x73,0x74,0x61,0x63,0x79
};

void printHash(uint8_t* hash) {
int i;
 for (i=0; i<32; i++) {
   Serial.print("0123456789abcdef"[hash[i]>>4]);
   Serial.print("0123456789abcdef"[hash[i]&0xf]);
  }
 Serial.println();
}

void setup() {
   uint8_t* hash;
   uint32_t a;

 Serial.begin(9600);

 // HMAC tests
  Serial.println("Test: RFC4231 4.2");

Serial.print("Result:");
Sha256.initHmac(hmacKey1,20);
Sha256.print("Hi There");
 //My TRIAL ATTEMPT
 int i;
 for (i=0; i<32; i++) {
 hash[i] =Sha256.resultHmac();
 Serial.println(hash[i]);
 }
}

How do I save the hashed result into a variable? I disregarded the Printhash function above and tried it with my own code but it displays

 sketch_feb14a:32: error: invalid conversion from 'uint8_t*' to 'unsigned char'

I don't understand the printhash function above and found little to no documentation on the web. I'm thinking of using AES library but I guess it's more complicated over here. The above code is based on Spaniako's CryptoSuite here

Heading

My solution was making a new function that returns a String with the hash

String GetHash256(uint8_t* hash) {
    char tmp[16];
    String sHash256 = "";

    int i;
    for (i=0; i<32; i++) {
        sprintf(tmp, "%.2X",hash[i]);
        sHash256.concat(tmp);
    }

    return sHash256 ;
}


What is the smallest duration that can be measured using micros()? What is the least value of time that I could measure(count) using micros()?

What is the least value of time that I could measure(count) using micro() in Arduino board?

The answer is 64 clock cycles or 4 us @ 16 MHz. Please see the Arduino AVR core[1] for more details.

Cheers!

Ref. [1] https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/wiring.c#L25


Need function to convert bool array to int- why doesnt this work? Hey I wrote this function to convert an bool array to int:
(Math Lob included):

bool b_array[5];

int convertToInt(start_index,stop_index){
    int run=0;
    int result=0;
    for(int id=start_index;id<=stop_index;id++){
        result+=b_array[id] * pow(2.0,run);
        run++;
    }
    return result;
}

but it doesnt this work?

Thanks and kind regards
Nic

Assuming little-endian bools (least significant bool first), you should use simple bit-shifting, not floating point power calculations:

for(int id=start_index;id<=stop_index;id++){
    result |= b_array[id] ? (1 << run) : 0;
    run++;
}

The ternary operation (b_array[id] ? (1 << run) : 0) means:

If b_array[id] is true,  then

Or result with 1 left-shifted run times and store in result

otherwise

Or result with 0 and store the result (no-operation).


Real Time Clock Module Reset I just had a pretty simple question about the RTC Clock Modules, more specifically the DS3231 RTC. Once calibrated and running on my Arduino if I were to unplug it and plug it back in, will the time and everything reset and require another calibration, or will it work like a computer that, even when reset, retains the correct time and date. Thanks!

It depends if your module has a battery backup or not. A bare chip, by itself, will loose everything. That's why many breakout boards will have a small lithium cell on them to retain everything when the power is removed.


L298N Dual Motor Controller Enable Pin has power but motors not working I am trying to get the L298N to work with a simple DC motor.

For now, I have simplified the setup and the code to the basics to try to get it to work. I am using the following wiring setup with no button or pot:

Only 1 motor, I am using a 2S lipo which I measured the voltage to be 7.8V which should be enough. The DC motor works when directly powered from the battery and when power with ~5V from an Arduino so I know it is not the issue.

My code, simplified from this tutorial: https://howtomechatronics.com/tutorials/arduino/arduino-dc-motor-control-tutorial-l298n-pwm-h-bridge/

#define enA 9
#define in1 6
#define in2 7

void setup() {
  pinMode(enA, OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);
  // Set initial rotation direction
  digitalWrite(in1, LOW);
  digitalWrite(in2, HIGH);
}
void loop() {
  analogWrite(enA, 255); // Send PWM signal to L298N Enable pin
}

I can measure the voltage at the input, it is good 7.8V. No voltage on motor output pins. In1 has voltage of 3.0V and In2 has 0V which corresponds to the code. However, Enable1 has 0V which doesn't make sense. So I attached the jumper for Enable 1 to give it the 5V, measured to confirm and still the motor is not working. I also tried a 2nd L298N with the exact same setup it and does not work. So I suspect it is something in my code or setup.

I feel like I am doing something stupid but I do not know what else to check. I checked continuity on the back of the board and it seems okay.

I found this thread for a similar problem,
I realized that my scratch (taken from here) wasn't able to works..
After many and many tries, I found that:
the scratch works only using Serial Plotter, and not using Serial monitor.
In my case it was not necessary to connect 5vout of L298N with arduino,
(clearly you need to connect ground to battery supply and to arduino ground too).
I don't know why the scratch works properly (make motors turn) only by Serial Plotter and it doesn't work by Serial monitor.
I really would like to understand it!! (if someone could explain this oddity I would be very grateful).
Hope this could help.
UPDATE:
I found why it doesn't work on Serial monitor..
In the serial monitor, by using:
int inByte = Serial.read();

you must select "no line ending".
:)
it's always human error!
NOTE:
the 5V pin let to power Raspberry and this is it use.
I don't know if that solution should be risky..
In the Datasheet it's said:

A non-inductive 100nF capacitor must be connected between this pin and ground

I searched about this solution on Raspberry but, after many readings, I just don't know if this could be a safe solution to power it.
I can't suggest it as a secure way.


Connecting E-paper display (GD) to Arduino? I'm still learning how to use Arduino and electrical components, but I will try my best to understand any answers!

So I just bought an e-paper display off a website, not from the manufacturer itself (http://www.good-display.com/products_detail/productId=305.html). The product is a 1.54 inch E-paper display 200x200 partial update GDEP015OC1.

I was a bit puzzled by how to connect the display to the Arduino Uno. Turns out that to connect the display to a board, it needs a breakout board (is this the correct term?). I could buy it online from the manufacturer, however, it will take me at least a month and the shipping cost is too high.

I was wondering if it is possible for me to make my own breakout board? Is there any 'general' breakout board for an e-paper display, or does it have any special from the manufacturer? If it is possible, how difficult would it be for a beginner who has almost no knowledge on circuit building/electrical components?

The aim is just to display an image onto the e-ink display.

Thanks!

edit: I bought the mentioned display because of the size. I was afraid of not knowing how to connect the mention display (which is where I am now), so I bought this e-ink display also: https://www.smart-prototyping.com/E-ink-E-paper-Display-module-3.3V-2.04-inch-177x72.html I was thinking to take the 60mmx30mm display off the board and try connecting the 30mmx30mm display to the 'breakout board' if I am unable to build my own board. Both seemed to have the same pin number (need to confirm later).

E-ink displays require high voltages to operate them. They are electrostatic devices and the pixels need charging up to a high voltage (high compared to what an Arduino runs at) to attract the pigment powder (basically the same as laser printer toner) to create an image.

While it is possible to make your own board it's not something that is simple and straight forward. Designing boost converters requires a certain base level of knowledge and expertise to get it right. Not something I would recommend a beginner attempting.

Even though a display may have the same pin number as another it doesn't follow that the pins are in the same order on the connector. There is no standard and each display from different manufacturers (and even different displays from the same manufacturer) will have a different pin-out. You will need to compare the datasheets for the two displays to see if the pin-out is the same and if it isn't you would have to somehow map from one to the other on the driver board.

The simplest option is to just order the correct driver board for that display.

(Note: in this context it is called a driver board not a breakout board. A breakout board is typically a passive circuit board that converts from one hard-to-use connector or footprint to a simpler, say 0.1", header. A driver board contains active electronics, in this case a boost converter, to drive the device it is connected to.)


How best to power down an Arduino for ~5 minutes at a time? Reading over the datasheet it appears the longest it can shutdown for is 8s so should I just keep a counter in the loop method that checks if it's run 38 times and then execute the code I want? Would this wakeup every 8s hurt battery life much if it's doing nothing but incrementing a counter?

Yes, if you want to wake an ATMEGA (the chip in the Arduino) spontaneously (no outside trigger) from Power Down mode at periodic intervals, the you will need to rely on an interrupt generated by the watchdog timer, which has a maxim timeout of 8s.

Your goal should be to wake, increment and check the timer, and get back to sleep as quickly as possible since the amount of time you are awake will dominate your average power usage while asleep.

Some things to keep in mind...

The arduino uses a power regulator which always draws current. If you are going for long battery life, you will need to replace or eliminate this regulator. Much better to have an ATMEGA connected directly to a battery.
Turn off as much of the chip as possible before going to sleep. Take a look at the power control registers.
Make sure you are not driving any unnecessary loads with the GPIO pins when sleeping.

BTW, common wisdom has been that it is best to wake up and run at as fast a clock speed as possible to get your work done and get back to sleep as quickly as possible. However, Jack Ganssle recently published an article that makes a great case for doing the opposite. You will actually get longer battery life if you wake up to a slow clock speed, since this means you can run down the battery to lower voltage (this assumes you don'y need higher voltages for some other part of your circuit). Lots of other great info for designing long running battery-powered systems here...

http://www.ganssle.com/tem/tem275.html

Here is another relevant article about long running Arduinos...

http://www.openhomeautomation.net/arduino-battery/


Attiny85 microcontroller programming without arduino I have decided to make a simple project so thinked about arduino but that seems very worthy so i decided to use attiny85 ic for my project,but i don't have arduino or avr to program it. Is there any way to program the below ic without arduino or avr?.

Programming a bare ATtiny85 IC needs either another Arduino or an AVR programmer

Programmer $4-$7
Something like the Pololu AVR Programmer v2.1 can be bought for $7 and used with the free Arduino development software (IDE). I have used this to program an ATtiny85. This is what I would suggest, because a programmer is the most versatile solution.
 Even cheaper, a $4 USBASP

Arduino as ISP $4.50
I have used an old Arduino Duemilanove using the Arduino as ISP sketch as a programmer for an ATtiny85 but any Arduino with inbuilt USB and enough GPIO could be used. There are some low cost ATmega328P or ATmega32u4 based Arduino clones that would be suitable. A Nano v3 clone costs $4.50.

Development Board with USB $3
As others have commented, you can buy a "digispark" (just Google and click "shopping") for three or four dollars. This is essentially a breakout board with an ATtiny85, a USB connector and a soft-USB-capable bootloader pre-loaded onto the ATtiny85. You can program it with the Arduino IDE after using the IDE's board-manager to install Digistump's "core" definitions for the Digispark. It doesn't need another Arduino nor an AVR Programmer. I bought three on Amazon for $9 a month ago.

Since it is an Arduino-compatible development board, it doesn't really meet your requirement of "without Arduino" - but it might be the closest solution to what you have in mind.

Useful resources and inspiration:

ATtiny-Based Beginner's Kit
Twelve PWM outputs from an ATtiny85.

Yes, 12 LEDs individually controlled with just four resistors and four pins of an eight-pin ATtiny85 and and no other components!
I have no affiliation with the above site, I just think it is one anyone new to electronics with an ATtiny85  would find interesting.


ESP8266 fail to connect MQTT broker I am using NodeMCU dev board with ESP8266 WIFI.

Every time I try to connect to my local broker it returns this error:

failed, rc=-2 try again in 5 seconds

I am using Ubuntu 18.04, my local brokers are Mosquitto and EQMTT. I tried both of them through pubsubclient library and it doesn't connect. Using MQTT Box works connecting to my local brokers. Connecting to my WiFi also works. When I connect to a MQTT broker using pubsubclient e.g. mqtt://test.mosquitto.org:1883/ it works. It just doesn't seem to work with local broker. This is the code:

#include <ESP8266WiFi.h>
#include <PubSubClient.h>

// Update these with values suitable for your network.

const char* ssid = "mywifi";
const char* password = "password";
const char* mqtt_server = "127.0.0.1";

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;

void setup() {
  pinMode(D7, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
  Serial.begin(9600);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
}

void setup_wifi() {

  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();

  // Switch on the LED if an 1 was received as first character
  if ((char)payload[0] == '1') {
    digitalWrite(D7, LOW);   // Turn the LED on (Note that LOW is the voltage level
    // but actually the LED is on; this is because
    // it is acive low on the ESP-01)
  } else {
    digitalWrite(D7, HIGH);  // Turn the LED off by making the voltage HIGH
  }

}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("ESP8266Client")) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish("outTopic", "hello world");
      // ... and resubscribe
      client.subscribe("inTopic");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(1000);
    }
  }
}
void loop() {

  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  long now = millis();
  if (now - lastMsg > 2000) {
    lastMsg = now;
    ++value;
    snprintf (msg, 75, "hello world #%ld", value);
    Serial.print("Publish message: ");
    Serial.println(msg);
    client.publish("outTopic", msg);
  }
}

Note: The brokers are running, I can even connect it through MQTT Box (attached picture).

127.0.0.1 is not the address of your computer.  That is the address of the "loopback" interface - a virtual interface that allows a device to talk to itself.

That means that when you are using the MQTT server itself you can connect, because it's all the same computer.  However the ESP8266 is trying to connect to itself, not the MQTT server.

You need to replace 127.0.0.1 with the actual IP address of your MQTT server.

The simplest way of getting your computer's IP address is to open a terminal window and type:

hostname -I