Arduino Accessing a web page Folks,
I want to use my arduino with ethernet shield to access the following webpage "http://www.met.ie/forecasts/sea-area.asp" and take some information.

On the website it has a line "Small Craft Warning"- This is always either "In Operation" or "Nil".

Basically i want to hook up a RGB LED to the duino and if "Small Craft Warning" is "in Operation" i want LED to be Red, and if "Nil" LED can be green.

My issue is i cant figure out hot to go about getting the information from the webpage.- Can the arduino read this directly?

I am confident with arduino but this is my first web based project!

Any Tips or advice would be savage helpful
Thanks

As I commented on deltaray's answer, a regular expression library is
overkill for finding a fixed string. There is a standard avr-libc
function for that called strstr():

char * strstr(const char *haystack, const char *needle);

where haystack is the Web page and needle is the fixed string you
are searching for.
There is an issue with this function though: in order to use it, you
need to have the whole haystack in RAM. For a non-trivial Web page, this
may not be doable on a small Arduino.
Below is a custom solution based on a finite state machine: the
parser can be in a number of different states:

state 0 = waiting for the 'S' of "Small Craft"
state 1 = waiting for the 'm' of "Small Craft"
etc...

The state is actually an index in a character array representing the
string we are looking for. Each time the parser finds the expected
character, it moves to the next state. Otherwise it moves back to state
0. There is a small kludge though: when in the state waiting for the
'N' of "Nil", if it doesn't get an 'N', it moves to the state waiting
for the 'I' of "In Operation" and tries the match again. This way it
can look for both the possible strings at once. Also, once it got the
full preamble "Small Craft Warning: </b>", if it gets something
invalid, it moves to an extra state called INVALID instead of state 0.
Here is the code:
// Possible return values of parse_forecast().
// The last three are sticky.
enum parse_state {
    NO_PREAMBLE,        // no complete preamble seen yet
    PREAMBLE_COMPLETE,  // preamble just completed
    PARTIAL_NIL,        // received preamble and start of "Nil"
    PARTIAL_IN_OP,      // received preamble and start of "In Operation"
    COMPLETE_NIL,       // result = Nil
    COMPLETE_IN_OP,     // result = In Operation
    INVALID             // valid preamble followed by invalid data
};

parse_state parse_forecast(char c)
{
    // position:      0                        25   29            42
    const char T[] = "Small Craft Warning: </b>Nil\0In Operation\0";
    static size_t i;  // T[i] is the character we expect next

    if (T[i]) {  // non-sticky state
        if (i == 25 && c != T[i])
            i = 29;      // switch to "In Op" branch
        if (c == T[i])   // found expected char
            i++;         // wait for the next one
        else {
            if (i < 25)
                i = 0;   // reset to start of the string
            else
                i = 42;  // invalid state
        }
    }
    return i <  25 ? NO_PREAMBLE :
           i == 25 ? PREAMBLE_COMPLETE :
           i <  28 ? PARTIAL_NIL :
           i == 28 ? COMPLETE_NIL :
           i <  41 ? PARTIAL_IN_OP :
           i == 41 ? COMPLETE_IN_OP :
           INVALID;
}

With this you do not need to store the Web page in RAM. Instead, you
feed the parser one character at a time and, at the end, check the
return value. You expect it to be either COMPLETE_NIL or
COMPLETE_IN_OP.
Implementation detail: there are three NUL characters in the template
string, at positions 28, 41 and 42 (the last one is implicit). They
correspond to the three possible "sticky" states.


Max length of char arrays? I'm running the following Sketch on my Arduino Uno:

const boolean verbose = true;

void debug(const char *s){
    if(verbose){
      char buf[8 + sizeof(s)] = "[DEBUG] ";
      strcat(buf, s);
      Serial.println(buf);
   }
}

void setup() {
  Serial.begin(115200);
  char str[] = "Lorem ipsum dolor sit amet, consetetur sad";

  Serial.print("Size of String: ");
  Serial.println(sizeof(str));
  debug(str);
}

void loop() {
}

The debug() function should be used to print debugging information to Serial. The Sketch like I posted it works wuite fine and prints the following to Serial:
    Size of String: 43
    [DEBUG] Lorem ipsum dolor sit amet, consetetur sad

But when I add one more character to the string (43 chars excluding null terminator) I get the only follwoing on Serial:

Size

This problem does not appaer when defining str as a global varaible. What does cause this issue and how can it be fixed?

The main issue with your code is:

sizeof(s)

That doesn't return the string length - it returns the size of the char pointer - which is two bytes (on an 8-bit system, 4 on a 32-bit system).

Instead you need to use strlen(s) and add one to it for the NULL character at the end.

if(verbose){
  char buf[8 + strlen(s) + 1] = "[DEBUG] ";
  strcat(buf, s);
  Serial.println(buf);
}

However, what you are doing is pointless. Just print twice:

if(verbose){
  Serial.print(F("[DEBUG] "));
  Serial.println(s);
}

Note the use of the F() macro to ensure that [DEBUG] doesn't waste RAM.


Running Atmega1284P at 3.3 and 8Mhz can i run Atmega1284P at 3.3V and 8Mhz speed.? can i burn Nick Gammon Arduino bootloaders into the chip.?

Thank You

Atmega1284P 8MHz @ 3.3V?

Yes, you can. Documentation states this is permitted voltage for that frequency:  0 - 10MHz @ 2.7V - 5.5V http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-42719-ATmega1284P_Datasheet.pdf

Nick Gammon Arduino bootloaders?

On this page http://www.gammon.com.au/bootloader it states Atmega1284.
In code https://github.com/nickgammon/arduino_sketches/blob/master/Atmega_Self_Read_Signature/Atmega_Self_Read_Signature.ino
there is signature for Atmega1284P so it should work without issues.


Wrong conversion of time_t to char I have a simple sample of code that i want to convent a time_t to char array in order to concatenate it after, in an other array.
Code:

time_t unixt;
char exm [40];

unixt = RTC.get();
Serial.println(unixt);
dtostrf(unixt, 10, 0, exm);
Serial.println(exm);

The problem that i face is that, the console is printing different the second one every time like this:

1548258220
1548258200

I tried also with unsigned long with no result either. Can someone point me what's wrong or an other way of doing this?

Use ultoa() instead of dtostrf(). The former is meant to serialize
unsigned long integers, while the later is for floating point numbers.
By using dtostrf(), you are implicitly converting unixt to a
floating point number. The Arduino Mega only supports single precision
floating point, so this conversion incurs some loss of precision, hence
the result you see.


LCD not displaying text I am working with an Arduino due and currently using the Arduino liquid crystal library to display data on an LCD screen (mc42004A6wk-bnmlw) which uses the Hitachi HD44780 controller. The LCD has been update to v2 and is now using the Sitronix ST7066U controller.

From what I have read the two controllers are compatible and the liquid crystal library should work for both. I am using the same software and hardware setup as before but the screen will not display anything.

The software I use is quite complex so I moved to a simple hello world program (below) to test and I still have the same issues. Any advice would be greatly appreciated.

#include <LiquidCrystal.h>
#include <Arduino.h>

LiquidCrystal lcd(30, 31, 32, 33, 46, 47);

void setup()
{

  pinMode(36,OUTPUT);

  digitalWrite(36, LOW);

  delay(5000);

  // set up the LCD's number of columns and rows:
  lcd.begin(20, 4);

  lcd.clear();

  // Print a message to the LCD.
  lcd.print("hello, world!");
}

void loop()
{

  delay(5000);
  // set the cursor to column 0, line 1
  // (note: line 1 is the second row, since counting begins with 0):
  lcd.setCursor(0, 1);
  // print the number of seconds since reset:
  lcd.print(millis() / 1000);
}

Try using this code, I have edited some parts of your code so this should work.

#include <LiquidCrystal.h>

const int rs = 30, en = 31, d4 = 32, d5 = 33, d6 = 46, d7 = 47;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void setup()
{

  pinMode(36, OUTPUT);
  digitalWrite(36, LOW);
  delay(5000);    //Its okay to use delay here since its in the setup() function and will run only once

  // set up the LCD's number of columns and rows:
  lcd.begin(20, 4);

  // Print a message to the LCD.
  lcd.print("hello, world!");
}

void loop()
{
  // set the cursor to column 0, line 1
  // (note: line 1 is the second row, since counting begins with 0):
  lcd.setCursor(0, 1);
  // print the number of seconds since reset:
  lcd.print(millis() / 1000);
}

For this Hello World sketch, avoid using delay(); statement in the void loop() as it is not good to use when you have the millis(); used.

If the above wont work, check your LCD Wiring, many problems usually arouse from wrong wirings.
Also I may suggest you to use some cheap LCD I2C Backpacks as this will ease the coding and will use less wire and pins on your Arduino. Here is a example

If your'e going to use a I2C LCD Backpack, here is a working sample code.

#include <Wire.h>
#include <LiquidCrystal_I2C.h>

#define BACKLIGHT_PIN     13

LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); // Set the LCD I2C address

// Creat a set of new characters
const uint8_t charBitmap[][8] = {
   { 0xc, 0x12, 0x12, 0xc, 0, 0, 0, 0 },
   { 0x6, 0x9, 0x9, 0x6, 0, 0, 0, 0 },
   { 0x0, 0x6, 0x9, 0x9, 0x6, 0, 0, 0x0 },
   { 0x0, 0xc, 0x12, 0x12, 0xc, 0, 0, 0x0 },
   { 0x0, 0x0, 0xc, 0x12, 0x12, 0xc, 0, 0x0 },
   { 0x0, 0x0, 0x6, 0x9, 0x9, 0x6, 0, 0x0 },
   { 0x0, 0x0, 0x0, 0x6, 0x9, 0x9, 0x6, 0x0 },
   { 0x0, 0x0, 0x0, 0xc, 0x12, 0x12, 0xc, 0x0 }

};

void setup()
{
   int charBitmapSize = (sizeof(charBitmap ) / sizeof (charBitmap[0]));

  // Switch on the backlight
  pinMode ( BACKLIGHT_PIN, OUTPUT );
  digitalWrite ( BACKLIGHT_PIN, HIGH );

  //lcd.begin(16,2);
  lcd.begin(20,4); // initialize the lcd

   for ( int i = 0; i < charBitmapSize; i++ )
   {
      lcd.createChar ( i, (uint8_t *)charBitmap[i] );
   }

  lcd.home ();                   // go home
  lcd.print("LCD TESTER - BY:");
  lcd.setCursor ( 0, 1 );        // go to the next line
  lcd.print ("ABBAS (PRJCT.ME)");
  delay ( 3000 );
}

void loop()
{
   lcd.home ();
   // Do a little animation by writing to the same location
   //for ( int i = 0; i < 2; i++ )
    for ( int i = 0; i < 4; i++ )
   {
      //for ( int j = 0; j < 16; j++ )
      for ( int j = 0; j < 20; j++ )
      {
         lcd.print (char(random(7)));
      }
      lcd.setCursor ( 0, 1 );
       for ( int j = 0; j < 20; j++ )
      {
         lcd.print (char(random(7)));
      }
      lcd.setCursor ( 0, 2 );
       for ( int j = 0; j < 20; j++ )
      {
         lcd.print (char(random(7)));
      }
      lcd.setCursor ( 0, 3 );

   }
   delay (200);
}


Code working well on Arduino Uno is not working with Mega 2560 Following is the code block from my script. It uses timer1. Why it is not compatible with Arduino Mega?

TCCR1A = theTCCR1A; // 0b10000010;
  /*10 clear on match, set at BOTTOM for compA.
   00 compB disconected initially, toggled later to clear on match, set at BOTTOM.
   00
   10 WGM1 1:0 for waveform 15.
   */
  TCCR1B = 0b00011001;
  /*000
   11 WGM1 3:2 for waveform 15.
   001 no prescale on the counter.
   */
  TIMSK1 = 0b00000001;
  /*0000000
   1 TOV1 Flag interrupt enable.
   */
  sei();             // Enable global interrupts.
  // Set outputs pins.
  DDRB   = 0b00000110; // Set PB1 and PB2 as outputs.
  pinMode(13, OUTPUT); // Set trigger pin to output

It's not working because code you write is code that will work only on ATmega328. Every ATmega328 chip will run this code without any problem.
If you want that Mega does same task as Uno, then you have to rewrite whole code and use Arduino functions(such as pinMode, digitalRead etc..) or read ATmega2560 datasheet and use ATmega2560 registers. Also Search for ATmega2560 pin layout, you'll need it if you want use registers.


Which voltage regulator should I use? A friend and I are working on building a smartwatch on a budget, so it’s a (very) low power project, but we are currently having a problem with the power supplying.
We already chose this board, because of its size and the BLE chip: RFduino BLE SMT
For now on, we are planning to use this battery 500 mAh LiPo battery (approx. 4V at full charge) with this voltage regulator Micrel MIC5209-3.6YS (the board supports 3.6V max.).

But the problem is that the Voltage Regulator will apparently drain by itself too much energy from the battery (by heating), reducing drastically the autonomy.

So we would like to know if you guys can help us, if you can tell us exactly what (type of) regulator would be the best or if we need to find another battery.

IGND which is mentioned on page 4 of the datasheet is apparently proportional to the output current. This accounts for about 2-5% of the total current drawn by the regulator, depending on its load. With the maximum voltage drop of 4 - 3.6 = 400mV, a switching regulator will make no real difference. I think your only option is to find another regulator that has better efficiency.


How do I even out Infared distance sensor readings? I am using a standard infared distance sensor on a small robot and i am trying to even out the readings on it so it is more accurate. The readings are very sporadic and often take huge jumps in the distance. Is there a method of programming or circuit design that might make this easier to use? I'm trying to keep my robot from running into things.

Averaging is a very good technique for improving noisy data, provided
you have a “nice” noise. “Nice” meaning that you never get “atypical”
data points, i.e. the error of any given data point is of the order of
the “typical” error amplitude. If you have for instance
additive white Gaussian
noise, then
it can be shown that averaging is in some way the “best” way to clean
your data.

However, if you have big sporadic errors, then averaging is not a good
solution. This is because you will have to average a lot of samples
in order to smoothen out a single big error... and the more samples you
average, the more chances you have to get another huge error that will
ruin your average. Of course, averaging will somewhat improve things,
and it is better than no smoothing at all, but there are better options.

The solutions to this problem lye in the realm of robust
statistics. It may look
like hairy math, but there is actually a very simple smoothing filter
that is far more robust than the average: it's called the
median. The idea is quite simple:
you sort your list of samples from smallest to largest, then you pick
the one sample that ends right in the middle of the sorted list. Unlike
the average, this filter is completely insensitive to samples carrying
huge errors, as long as the majority of samples are reasonable.

Here is an implementation of a simple moving-median filter based on the
standard libc’s qsort(). It assumes samples have int type, but you
can change it to whatever numeric type you want. You can also change the
filter length: longer lengths provide more robustness against series of
consecutive bad samples, at the cost of more filter delay, more memory,
and more processing time.

/*
 * Comparison function for qsort(): return an integer "less than, equal
 * to, or greater than zero if the first argument is considered to be
 * respectively less than, equal to, or greater than the second."
 */
int compare(const void *pa, const void *pb) {
    int a = *(int *)pa;
    int b = *(int *)pb;
    return a<b ? -1 : a>b ? +1 : 0;
}

#define FILTER_LENGTH 11  // length of the median filter, should be odd

/*
 * Input: raw sample.
 * Ouput: filtered sample.
 */
int median_filter(int data) {
    static int input_buffer[FILTER_LENGTH];
    static int input_index;
    int sorted_buffer[FILTER_LENGTH];

    // Store the current data point.
    input_buffer[input_index] = data;
    if (++input_index >= FILTER_LENGTH) input_index = 0;

    // Sort a copy of the input buffer.
    for (int i = 0; i < FILTER_LENGTH; i++)
        sorted_buffer[i] = input_buffer[i];
    qsort(sorted_buffer, FILTER_LENGTH, sizeof *sorted_buffer, compare);

    // Return median.
    return sorted_buffer[FILTER_LENGTH/2];
}

As I did not explicitly initialize the filter memory, this will output
zeros the few first times it is called. I encourage you to try this
filter and compare against an exponential moving average, and only then
decide which works best for you.


POST request not working I'm following a guide on storing sensor data to MYSQL:

Guide

I'm using different sensors but my POST request is getting any results to my server. For now, I'm only storing temperature.

Here is my code for saving data:

void sendData(double input){

String data = "sensorid=3000000&temp=" + doubleToString(input, 2) + "&hum=1.2";

if(client.connect("192.168.1.50",80)){
    client.println("POST /arduino/add.php HTTP/1.1");
    client.println("Host: 192.168.1.50");
    //client.println("User-Agent: Arduino/1.0");
    //client.println("Connection: close");
    client.println("Content-Type: application/x-www-form-urlencoded");
    client.print("Content-Length: ");
    client.print(data.length());
    client.println();
    client.print(data);

    Serial.println("Sent data: " + data);
}

if(client.connected()){
   client.stop();
}
delay(300000);
}

I've commented out two headers since it did not give any other results. My Serial.println gives: Sent data: sensorid=3000000&temp=24.00&hum=1.2
Which means that the arduino is connected to the giving IP-adress and that my Request data is as I want. They are also working perferct when I'm testing with Requestmaker. So I'm pretty sure my error comes from the way I'm doing the request here.

So do you have any idea how I can solve this? Or how I can debug it t

Answered by Edgar Bonet

There needs to be an empty line between the headers and the body of the request. Therefore you have to println() (not print()) the end of the last header.

Please accept this answer so the system knows it is the correct one.


Problem to upload code I tried to upload example code form arduino software and got error below. Two arduino attach with my computer running windows8.1. And These arduino using port 3 and port 4. The arduino using Port 3 is cordinator and arduino using port 4 is router.
I doesn't understand why error show COM1 is not available. I am not using COM1.

Arduino: 1.6.0 (Windows 8), Board: "Arduino Uno"

Sketch uses 1,030 bytes (3%) of program storage space. Maximum is 32,256 bytes.

Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.

C:\Program Files (x86)\Arduino/hardware/tools/avr/bin/avrdude -CC:\Program Files (x86)\Arduino/hardware/tools/avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM1 -b115200 -D -Uflash:w:C:\Users\Jiya\AppData\Local\Temp\build1135139715306090793.tmp/Blink.cpp.hex:i

avrdude: Version 6.0.1, compiled on Apr  3 2014 at 23:12:16
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "C:\Program Files (x86)\Arduino/hardware/tools/avr/etc/avrdude.conf"

         Using Port                    : COM1
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: ser_open(): can't open device "\\.\COM1": The system cannot find the file specified.

avrdude done.  Thank you.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

Board at COM1 is not available
Board at COM1 is not available
Board at COM1 is not available
Board at COM1 is not available
Board at COM1 is not available

  This report would have more information with
  "Show verbose output during compilation"
  enabled in File > Preferences.

(I'm assuming you're using the official Arduino IDE here.)

Before uploading a sketch, you need to select which port you want to upload to. Within the Arduino IDE, click on the Tools menu and open the Port submenu. Click on the port your Arduino is connected to, such as COM3 or COM4.

You also need to ensure the appropriate board type is selected in Tools -> Board.

You should then be able to and upload the sketch.


Serial comms failure after long time - can't open COM port I've been using an Arduino UNO to log data: it's queried by a LabView VI over a VISA connection. It'll happily sit there and log for days, but very occasionally one of the VISA functions will fail.

After this, I can't open the COM port again (in LabView or elsewhere) and the only way to restore communication is to unplug and replug the USB cable. The Arduino hasn't crashed because I can see the other results of the program it's running working fine, but Serial comms are a gonner.

Has anyone experienced this? Do you know if this is an Arduino problem, a Labview problem, a Windows problem? Or something else?

I'm writing a minimum working example to try and catch this happening in the most simple code possible, but since the error usually takes several days to show up I can't tell you the results yet!

The assumption I am making is "VISA connection" is a PC operating VISA.
I have seen ports shut down on windows several times yet the same port works fine while in DOS.  My suggestion is try a different computer, that should narrow down your problem to which side of the connector is failing.


Atmega328 PWM frequency setting not working I have an Arduino UNO with Atmega 328 SMD, and I am trying to use PWM, but by setting registers, not using analogWrite(). My code is:

DDRD |= (1 << PORTD6); //Setting pin D6 as output
OCR0A = 128; //50% duty cycle
TCCR0A |= (1 << COM0A1)|(1 << WGM01)|(1 << WGM00); //setting mode and fast pwm
TCCR0B |= (1 << CS01); //setting the prescaler to 8, which should yield PWM with frequency of 8 kHz

The problem is with the last line. No matter what I do, it results in PWM with frequency of 1 kHz. Setting different prescaler bits just yield 1 kHz PWM again. I was thinking that maybe its because I am programming this in Arduino IDE, and I kHz is Arduinos default frequency?
Or where am I making the mistake? Thanks for any answers.

Your code assumes that TCCR0n are zero. But what if they are not. What if there is some hidden initialization?

Timer0 is used by the Arduino micro/millis counter and the prescale (TCCR0B) is initiated by setting bits CS00 and CS01 in init() before setup() is called.

If you really want to use Timer0 you will need to set/clear all the prescale bits. Alternatively clear the register before setting any bit.


Installing MariaMole (Alternative IDE) on Mac I've heard about a alternative Arduino IDE called MariaMole and really liked the idea, but I just don't know how to install it on Mac OS X. The GitHub page claims that it is compatible with Mac but I just can't find a tutorial, or instructions, as to how the Git files can be compiled on Mac.

Note: I haven't tried this myself so YMMV; this is just from my general experience and reading; all information comes with citations.

To start, I would recommend opening an issue on GitHub to ask for detailed instructions. I noticed that the website says:

  Linux and Mac distributions are still experimental, but MariaMole is working fine on both systems.

so they should have a known recipe for how to do it.

In the mean time, here's how I would proceed. Given that there's a file called CMakeLists.txt in the root directory, you need to:

download and install CMake

Then, install the dependencies listed on the wiki:

Qt 5.2
QScintilla 2
QSerial

After that, I presume just cloning the repo and running cmake in the root directory should do the trick. If you have any further questions, please open an issue on GitHub with your compilation error message for further assistance.


Can I place bootloader directly onto Atmega2560 and have USB? I am working on a prototype device which I am now on my 2nd board iteration and moving away from it being a shield and wired to an arduino mega2560 board.

I have used the freely available Arduino mega 2560 schematic and incorporated this into my project.

I notice that there are 2 µcontrollers on this schematic, (Atmega2560 & Atmega16U2)

I understand that the arduino bootloader resides on the 16u2 and it connect to the usb connector. the 16u2 then programs the 2560 with the code you send it.

On the searching I have done I'm getting myself terribly confused.
Someone suggested to me that I could in fact do away with the Atmega16u2 all together (this would drastically reduce my component count and free up valuable board space)

However, I was intending to flash a boot loader that would make the device appear to a computer (over usb) as a midi controller device.

I am unclear if I can indeed interface a usb port directly to the ATmega2560,  and upload my sketch code AND a midi-over-usb boot loader..
I doubt the advice because the ATmega16U2 (i think) has a built in UART to communicate via usb and that the 2560 does not...

Sorry If this all sounds vague, I'm searched out and confused...

thanks.

I understand that the arduino bootloader resides on the 16u2 and it connect to the usb connector. the 16u2 then programs the 2560 with the code you send it.

That is a misunderstanding.

The bootloader is on the 2560.  The 16U2 contains its own custom firmware which acts as a USB CDC/ACM interface to connect the USB to the 2560 as a TTL UART connection.

The same can be done using any number of other similar devices, such as the FT232R etc.

You cannot directly connect the USB to the 2560 since the 2560 has no concept of what USB is.  The 16U2 has that knowledge, but doesn't have as many IO pins as the 2560, so combining the two gives you a total system that both understands USB and has lots of IO.


Carry out two consecutive tasks when a button is pressed I'm building a project that has 2 motors. What I want to do is:
When button is pressed (hold down through RF controller) then:

Run motor A on pwm at 50 for 1 second
Run motor B on pwm at 255 for 1 second

After that first second

Run motor A on pwm at 255 until button is released
Stop motor B.

And when I hit the button again the whole thing repeats. Here is my rough code but it doesn't work that way. What it does is if I pressed the button in the first second since start up off the Arduino it does the first task. If I press it again it does the second task.

I have looked and tried through a lot of examples of blink without delay and multitasking. But I still can't get it working.

Here is my code:

#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
#include <elapsedMillis.h>

// Motor 1
int dir1PinA = 4;
int dir2PinA = 5;
int speedPinA = 3; // Needs to be a PWM pin to be able to control motor speed

// Motor 2
int dir1PinB = 7;
int dir2PinB = 8;
int speedPinB = 6; // Needs to be a PWM pin to be able to control motor speed

int msg[1];
RF24 radio(9,10);
const uint64_t pipe = 0xE8E8F0F0E1LL;

unsigned long previousMillis = 0;
long OnTime1 = 500;
long OnTime2 = 10000;

void setup(){
 Serial.begin(9600);
 radio.begin();
 radio.openReadingPipe(1,pipe);
 radio.startListening();

 pinMode(dir1PinA,OUTPUT);
 pinMode(dir2PinA,OUTPUT);
 pinMode(speedPinA,OUTPUT);

 pinMode(dir1PinB,OUTPUT);
 pinMode(dir2PinB,OUTPUT);
 pinMode(speedPinB,OUTPUT);

 }
 void CandPush()
 {
          analogWrite(speedPinA, 50);//Sets speed variable via PWM
          digitalWrite(dir1PinA, HIGH);
          digitalWrite(dir2PinA, LOW);
          analogWrite(speedPinB, 255);//Sets speed variable via PWM
          digitalWrite(dir1PinB, LOW);
          digitalWrite(dir2PinB, HIGH);

 }
 void CandStop()
 {
          analogWrite(speedPinA, 255);//Sets speed variable via PWM
          digitalWrite(dir1PinA, HIGH);
          digitalWrite(dir2PinA, LOW);
          analogWrite(speedPinB, 0);//Sets speed variable via PWM
          digitalWrite(dir1PinB, LOW);
          digitalWrite(dir2PinB, LOW);

 }
 void Home()
 {
          analogWrite(speedPinA, 0);//Sets speed variable via PWM
          digitalWrite(dir1PinA, LOW);
          digitalWrite(dir2PinA, LOW);
          analogWrite(speedPinB, 255);//Sets speed variable via PWM
          digitalWrite(dir1PinB, HIGH);
          digitalWrite(dir2PinB, LOW);

 }
 void loop(){

 if (radio.available()){
    bool done = false;
    while (!done){
    done = radio.read(msg, 1);
    Serial.println(msg[0]);
    if (msg[0] == 111)
    {
      unsigned long currentMillis = millis();
      CandPush();
      if(currentMillis - previousMillis >= OnTime1)
      {
        CandStop();
        previousMillis = currentMillis;
      }

    }
 }
 }

 else
 {
  Home();
  Serial.println("Nothing");
 }
 }

I assume pressing the button results in msg[0] == 111 every time you do the radio.read (i.e. it will continue sending that while the button is held).  If so, the first issue I see is that after 500ms has elapsed, you will call CandStop(), and then it will loop back and immediately call CandPush(), essentially cancelling the second state.

I think you should create a state variable and state machine, so for example it does a different operation when/while the button is pressed depending on whether it is in the 'home', 'push', or 'stop' state.  In the first ('home') state it is waiting for the button to be pressed, in the second ('push') state it is waiting for the time to elapse, and in the third ('stop') state it is only waiting for the button to be released.  It would also allow you to avoid repeatedly calling CandPush() and Home() when it only needs to be called once (when the button is pressed).

EDIT:
I am adding the code below.  This hasn't been tested so there may be some bugs but it should give an idea of what I mean.  It could probably also be optimized somewhat, but I tried to make it do what I think you wanted it to do based on the code you attached.

There are parts in there that I doubt work as you wanted, aside from the button handling, for example how Home() is called whenever there is no radio available and how nothing appears to happen when the button is released.

Should the Home() call really set B to full output?  I added a call to StopAll which I assumed you would use to stop A and B when the button is released.

Also radio.read doesn't return anything, so done = radio.read(...) is pointless.

// State machine states
enum {
    STATE_INIT,
    STATE_HOME,
    STATE_PUSH,
    STATE_STOP
};

unsigned long previousMillis;
bool buttonPressed = false;
bool radioAvailable = false;
int state = STATE_INIT;

void loop()
{
    //Check for new radio input every cycle
    if (radio.available()) {
        radio.read(msg, 1);
        buttonPressed = (bool) (msg[0] == 111);
        radioAvailable = true;
    } else {
        radioAvailable = false;
    }

    //State machine
    switch (state) {
    case STATE_INIT:
        //first cycle after boot-up, add any desired initialization
        //wait here until the first time the radio is available
        if (radioAvailable) {
            state = STATE_HOME;
        }
        break;

    case STATE_HOME:        //Wait for button to be pressed
        if (radioAvailable) {
            if (buttonPressed) {
                //button was pressed, reset timer and move to PUSH state
                previousMillis = millis();
                CandPush();
                Serial.println("STATE_PUSH");
                state = STATE_PUSH;
            }
        } else {
            //no radio input, go to HOME state
            Home();
            Serial.println("STATE_HOME");
            state = STATE_HOME;
        }
        break;

    case STATE_PUSH:        //Wait for timer to elapse
        if (millis() - previousMillis >= OnTime1) {
            //OnTime1 has elapsed, move to STOP state
            CandStop();
            Serial.println("STATE_STOP");
            state = STATE_STOP;
        }
        break;

    case STATE_STOP:        //Wait for button to be released
        if (radioAvailable) {
            if (!buttonPressed) {
                //button was released, stop all motors?
                StopAll();
                state = STATE_HOME;
            }   //else still waiting for button to be released
        } else {
            //no radio input, go to HOME state
            Home();
            Serial.println("STATE_HOME");
            state = STATE_HOME;
        }
        break;
    }
}


Creating formatted String (including floats) in Arduino-compatible C++ I'm using a Mega2560 and a generic SSD1306 OLED display with the Adafruit_SSD1306 (and by extension, Adafruit_gfx) library.

I need to print a bunch of float values (ranging between 30.0 and 99.9) to the display with exactly one decimal place of precision. The catch is, the Adafruit library doesn't have a printf() method, only one that takes a single ready-to-print string.

Here's an (obviously non-Arduino) Java-like example of what I'm trying to accomplish:

String foo = String.format("%.1f, %.1f\%", temp1, hum1);
// "display" is my instance of Adafruit_SSD1306
display.print(foo);

So... how can I do something similar in Arduino-compatible C(++)?

Note: for this specific program, I have (relatively speaking) RAM to burn, so I really don't care if whatever library I use to generate formatted Strings is particularly efficient (as long as it isn't leaking). If it wants to use 4k of RAM and 80k of flash to format a 20-character String, so be it.

The Adafruit_GFX class has two methods named print() and
println(). These behave exactly like Serial.print() and
Serial.println(). Specifically, when printing a float, you can provide
a second argument telling it the number of decimal places you want after
the decimal point:

display.print(temp1, 1);  // 1 digit after the decimal point
display.print(", ");
display.print(hum1, 1);  // ditto
display.print("%");

Background: the reason these methods behave like the ones of
Serial is that both Adafruit_GFX and HardwareSerial inherit them
from the Print virtual class.


Controlling an LED using a transistor (TL188) I wanted to control an LED using a transistor (my first attempt at using a transistor). I connected a transistor (TL188) to pin 13 of an Arduino Uno accidentally and noticed something.

(The resistor I used was 150 ohms, and I forgot to change the resistor value in the diagram.)

The program on the Arduino Uno was the basic Blink sketch. As per the program, the LED on the Arduino Uno was supposed to turn on for 1000 ms and turn off for 1000 ms. But when I connected the LED like the diagram below

For the first 1000 ms delay:

LED on pin 13 stayed on
LED connected using the transistor stayed off

For the next 1000 ms delay:

LED on pin 13 stayed partially on (it was dim)
LED with the transistor was on

I know that the connection that I made is completely wrong. Can someone explain me how and also why the LED on the Arduino Uno was dim?

You should have a resistor of a few hundred ohms on the base connection of the transistor - that is, between base and pin 13.

A PNP transistor is somewhat harder to get to grips with than an NPN transistor.  Much of it does things backwards.

The operation you see seems to be completely correct when you understand how a PNP works.

With and NPN transistor a high voltage on the base turns it on and a low voltage turns it off. The opposite is true with a PNP transistor.

When you have a voltage close to or above the voltage at the emitter the transistor will be off.  That means, providing a HIGH to the base will turn it off.  A voltage on the base that is below the emitter voltage minus the threshold voltage of around 0.7V will turn the transistor on.  That means providing a LOW to the base will turn it on.

So that means that when the on-board LED is on the transistor is off, and so the LED on the transistor will be off.  When the LED on the board is off the transistor will be on, so the LED on the transistor will be on.

"But", you say, "the on-board LED doesn't turn off".  That is correct. It just gets dimmer.  That is, again, because of how the PNP transistor works.  Current (seen from the conventional sense - i.e., flowing from + to -) enters the emitter and is then split between the collector and base. The amount of current allowed to flow out of the base defines how much is allowed to flow out of the collector (in an NPN it's current into the base and collector that combine to flow out of the emitter, and the amount that is allowed to flow into the base defines how much is allowed to flow into the collector). So there will be some current flowing out of the base - which makes its way to ground both through the microcontroller's IO pin and also through the LED on board, making it glow slightly*.

*That is a little crudely put, but kind of illustrates what is going on.


Sim800l and arduino pro mini3.3 volt I want to connect sim800l module with arduino pro mini, I don't find any circuit diagram or tutorial for this. I want a circuit diagram for this.

Here is a schematic;

You may also find those links useful;

Link#1

Link#2

P.S. Please do little bit a google search. There are many samples and schematics all over the place.


No programmers available for this board - Programming ESP32 Cam with Ardunio IDE This is my first time working with ESP32 Cam boards.
I have followed the instructions as given in this site https://technoreview85.com/how-to-program-esp-32-cam-using-arduino-uno-board/
However my IDE doesn't display any programmers for this board.

Couldn't find any details about this in google. I just want to know how I could fix this problem(i.e. get the programmers listed).
Thanks in advance.

There are no programmers for ESP32. It only accepts Serial upload over bootloader.
Versions of IDE before 1.8.13 displayed programmers for all board support packages, that is why a programmer could be selected. Now only programmers for package of the selected board are available. But programmers are used only with the "Burn bootloader" or "Upload with programmer" commands, not with standard Serial upload over bootloader.


Arduino trim: does it remove the \n as well? According to the manual:

https://www.arduino.cc/en/Reference/StringTrim

Trim strips one or more whitespaces from the beginning and the end. Does it also removes tabulators and \n ?

I have the following code which works:

 while (Serial.available()) {   // something came across the serial
      char c = (char)Serial.read();
      Command += c;
      Command.trim();
      if (c=='\n')
         {
           Complete =true;
         }
   if (Command.length() >0 && Complete) {

        if (Command == "LED_ON") {
               // Do stuff
        }

Although I'm not sure that it is working because of the last if statement which says: if (Command == "LED_ON") ignores the ending \n and say ok it matched OR Command.trim() really takes off that \n.

Thank you

The source for the trim() function is in WString.cpp.

void String::trim(void)
{
    if (!buffer || len == 0) return;
    char *begin = buffer;
    while (isspace(*begin)) begin++;
    char *end = buffer + len - 1;
    while (isspace(*end) && end >= begin) end--;
    len = end + 1 - begin;
    if (begin > buffer) memcpy(buffer, begin, len);
    buffer[len] = 0;
}

We can see it uses the isspace() function, but where's that function defined? WString.cpp only #includes WString.h, so we go there.

In WString.h, we can see it includes ctype.h. Time to go to the C++ Reference, which tells us that yes, \n is a "space" according to isspace(), so it is trimmed.

(note that isspace() is affected by localization settings. I'm not sure what the localization settings are when compiling for Arduino)


RDM6300 library not working on ESP8266 I have a RDM6300 RFID module which I am trying to connect to an ESP8266 by using rdm6300.h library.
I had it all up an running all along with other components but we had connected to the ESP8266 but we had to move from the breadboard to an actual wired setup. Everything kept on working except for the RFID reader. The way I used to do it was by making a reference to this approach (more or less):
#include <rdm6300.h>

#define RDM6300_RX_PIN 4
#define READ_LED_PIN 13

Rdm6300 rdm6300;

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

    pinMode(READ_LED_PIN, OUTPUT);
    digitalWrite(READ_LED_PIN, LOW);

    rdm6300.begin(RDM6300_RX_PIN);

    Serial.println("\nPlace RFID tag near the rdm6300...");
}

void loop()
{
    /* if non-zero tag_id, update() returns true- a new tag is near! */
    if (rdm6300.update())
        Serial.println(rdm6300.get_tag_id(), HEX);

    digitalWrite(READ_LED_PIN, rdm6300.is_tag_near());

    delay(10);
}

but now, after the re-arrangement it just stopped reading tags. What I did was to disconnect everything from the ESP and leave only the RDM6300 connected to it with the sample code. Unfortunately, it doesn't seem to detect any tags.
In order to test if the components are failing for some reason, I decided to test it by using SoftwareSerial.h library on it like this:
#include <SoftwareSerial.h>
SoftwareSerial RFID(2, 3); // RX and TX

int i;

void setup()
{
  RFID.begin(9600);    // start serial to RFID reader
  Serial.begin(9600);  // start serial to PC
}

void loop()
{
  if (RFID.available() > 0)
  {
     i = RFID.read();
     Serial.print(i, DEC);
     Serial.print(" ");
  }
}

and it worked perfectly fine. I was able to read the payload coming from the chip:

2 30 31 30 46 33 46 38 44 39 31 32 44 3

But, since I don't want to implement everything related to decoding this serial stream I decided to ask for your opinion what could be wrong here. It used to work without any problem but now it doesn't.
There is something interesting which I also noticed. When I run the first code snipped and change the ESP8266 pin used from 4 to 16(D0) and I upload it, once I move the tag close to the antenna the hardware light related to this pin starts flashing and when I bring the tag back (away from the antenna) it stops flashing.
This makes me thing that on a hardware level everything is fine but some software issues are happening.

What fixed the issue for me was to go to Boards manager on Arduino IDE and update to latest version:

Then I got the following error when compiling:

Board generic (platform esp8266, package esp8266) is unknown

In order to fix that, I followed these instructions.
And, I also removed rdm6300 library from C:\Program Files\Arduino\libraries and moved it in C:\Users\myusername\Documents\Arduino\libraries


State machinese for serial input I am trying to control a servo using keyboard.

void loop() {
if (Serial.available() > 0) {
  x = Serial.parseInt();
  while(pos < 180){
  pos = x + pos;
  Serial.println(pos);
  myservo.write(pos);
  delay(100);
 }
  }
else if(Serial.available() > 0){
if(pos>=180){
  pos = 0;
  delay(500);
  myservo.write(0);

  }
  }
 }

Right now the servo takes the input correctly. The only thing is that it wont change positions immediately. It will wait until it hits 180 resets to 0 and then use the input I put in. This isnt the behaviour I want. I want it to change immediately. How Do I set this up?

I don't understand why you use 2 Serial.available condition.
I try to rewrote your program based on my imagination, so do not hate me if its wrong.
Why don't you try this and tell the results:

int pos = 0,x=0;
void loop()
{
  while (Serial.available() > 0) x = Serial.parseInt();

  pos+=x;
  if (pos>180) pos = 0;
  myservo.write(pos);
  Serial.println (pos);
  delay(100);
}


The fastest way to read out a digital pin state in an Arduino Due What is the fastest way to read a digital pin status in an Arduino Due? Is it possible to achieve speed in the Nanosecond area?

With which type of code I can achieve this?

Edit: This question is not a duplicate please see my comment.

If the pin is declared as input, let's say pin 13:

uint32_t pin_status;
pin_status = PIOB->PIO_PDSR & PIO_PDSR_P27;

If the pin is declared as output, let's say pin 13:

uint32_t pin_status;
pin_status = PIOB->PIO_ODSR & PIO_ODSR_P27;


ledkeypad shield not responsive I recently purchased several of the DFRobot ledkeypad shields: https://www.dfrobot.com/product-1407.html

I have Arduino Leonardo (which also had some problems in the beginning, being recognized as modems).
My OS is Linux Mint, and I'm using the last Arduino IDE.

The library I use is the one recommended on the website of the vendor, LedKeypad.h, and works fine with the other shields of the same model from the same batch.

Some shields worked fine but I am now having trouble with one of them, which seems unresponsive. I can load for instance the blink program in the arduino, and it works, but the shield does not work. When it is plugged in, the fours dots are slightly red, and I cannot turn them off.

I tried displaying something on the serial monitor when the buttons are pushed, and only one of the 5 buttons works (the KEY_DOWN one).

Is there anything I can attempt to fix the problem ? Or should I just give up on this shield ?

... and works fine with the other shields of the same model from the same batch.

So had you considered that the shield might be faulty? Have you contacted the manufacturer or vendor for support?


How do i wire a switch to control Leds on a arduino nano I am wiring some LED's with buttons to trigger them but i don't know if i have the wiring right?

Code

    /* switch
 *
 * Each time the input pin goes from LOW to HIGH (e.g. because of a push-button
 * press), the output pin is toggled from LOW to HIGH or HIGH to LOW.  There's
 * a minimum delay between toggles to debounce the circuit (i.e. to ignore
 * noise).
 *
 * David A. Mellis
 * 21 November 2006
 */

int inPin = 2;         // the number of the input pin
int outPin = 13;       // the number of the output pin

int state = HIGH;      // the current state of the output pin
int reading;           // the current reading from the input pin
int previous = LOW;    // the previous reading from the input pin

// the follow variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long time = 0;         // the last time the output pin was toggled
long debounce = 200;   // the debounce time, increase if the output flickers

void setup()
{
  pinMode(inPin, INPUT);
  pinMode(outPin, OUTPUT);
}

void loop()
{
  reading = digitalRead(inPin);

  // if the input just went from LOW and HIGH and we've waited long enough
  // to ignore any noise on the circuit, toggle the output pin and remember
  // the time
  if (reading == HIGH && previous == LOW && millis() - time > debounce) {
    if (state == HIGH)
      state = LOW;
    else
      state = HIGH;

    time = millis();
  }

  digitalWrite(outPin, state);

  previous = reading;
}

  note
  The code is not set to the pins yet.

The wiring is correct, but inPin in your code is set to 2, which is D4 on the Nano, while you have your signal wires going to D7 and D6 in your schematic.

Similarly, outPin is set to 13 in your code, which is D9 on the Nano, but your schematic shows the LEDs connected to D5 and D4.

I would also put the resistor going from the other pin on the switch to 5V, having the digital input connected directly to GND, but I'm not sure if that will affect power consumption, so it's probably more just a matter of personal preference.


Sending arduino sensor data via WiFi to a MySQL server I'm aware this question has probably been asked many times but I'm pulling my hair out.
I'm trying to get sensor data from an arduino to a MySQL server. I've checked the apache access log and the request is there. But it just isn't being inserted into the database. Manually adding the data using the browser works so the php code seems fine. I've allowed apache through the firewall and updated the permissions all to no avail. Code below:
Arduino Main Code:
#include "thingProperties.h"
#include <Arduino_MKRENV.h>
#include <WiFi.h>

WiFiClient client;

void setup() {
  // Initialize serial and wait for port to open:
  Serial.begin(9600);
  // This delay gives the chance to wait for a Serial Monitor without blocking if none is found
  delay(1500);

  //Connect to WiFi network
  int status = WL_IDLE_STATUS;
  while (status != WL_CONNECTED){
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(SSID);
    status = WiFi.begin(SSID, PASS);
    delay(10000);
  }
  Serial.println("This is connected.");

  if (!ENV.begin()) {
  Serial.println("Failed to initialize MKR ENV shield!");
  while(1);
  }
  pinMode(2, INPUT);
}

void loop() {
 relativeHumidity = int(ENV.readHumidity());
 lightIntensity = (ENV.readIlluminance());
 airPressure = int(ENV.readPressure(MILLIBAR));
 temperature = int(ENV.readTemperature());
 if(digitalRead(2) == LOW){
   rain = 1;
 }else if(digitalRead(2) == HIGH){
   rain = 0;
 }
 Serial.println("httpRequest");
 httpRequest();
 delay(10000);
}

void httpRequest(){
  // if there's a successful connection:
  if (client.connect(SERVER, 80)) {
    Serial.println("Connecting to server...");
    // send the HTTP PUT request:
    client.print("GET /weather_data.php?temp=");
    Serial.println("GET /weather_data.php?);
    client.print(temperature);
    client.print("&pressure=");
    client.print(airPressure);
    client.print("&humidity=");
    client.print(relativeHumidity);
    client.print("&illumination=");
    client.print(lightIntensity);
    client.print("&rain=");
    client.print(rain);
    client.print(" ");
    client.println("HTTP/1.1");
    client.print(" Host: ");
    client.println(SERVER);
    client.println();
    Serial.println("Added.");
  } else {
    Serial.println("Not connected.");
  }
  if (client.connected()){
    client.stop();
  }
}

thingProperties.h:
#include <WiFi.h>
#include <SPI.h>

const char THING_ID[] = "c942a18f-7696-4431-952c-76eaea3214ea";

const char SSID[]     = SECRET_SSID;    // Network SSID (name)
const char PASS[]     = SECRET_PASS;    // Network password (use for WPA, or use as key for WEP)
const char SERVER[]   = SECRET_IP;      // Server IP Address

int airPressure;
float lightIntensity;
float relativeHumidity;
bool rain;
float temperature;

So I don't quite know why, but I started from scratch and it works now. I've put the new code below in case it helps someone in my situation.
// Arduino Low Power - Version: Latest
//#include <ArduinoLowPower.h>
//#include <ArduinoIoTCloud.h>
#include "thingProperties.h"
#include <Arduino_MKRENV.h>
/*
  Repeating Wifi Web Client

  This sketch connects to a a web server and makes a request
  using a WiFi equipped Arduino board.

  created 23 April 2012
  modified 31 May 2012
  by Tom Igoe
  modified 13 Jan 2014
  by Federico Vanzati

  http://www.arduino.cc/en/Tutorial/WifiWebClientRepeating
  This code is in the public domain.
*/

#include <SPI.h>
#include <WiFiNINA.h>

int status = WL_IDLE_STATUS;

// Initialize the Wifi client library
WiFiClient client;

void setup() {
  //Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // check for the WiFi module:
  if (WiFi.status() == WL_NO_MODULE) {
    Serial.println("Communication with WiFi module failed!");
    // don't continue
    while (true);
  }

  String fv = WiFi.firmwareVersion();
  if (fv < WIFI_FIRMWARE_LATEST_VERSION) {
    Serial.println("Please upgrade the firmware");
  }

  // attempt to connect to Wifi network:
  while (status != WL_CONNECTED) {
    //Serial.print("Attempting to connect to SSID: ");
    //Serial.println(SSID);
    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
    status = WiFi.begin(SSID, PASS);

    // wait 10 seconds for connection:
    delay(10000);
  }
  // you're connected now, so print out the status:
  //printWifiStatus();
  //Start arduino cloud.
  //ArduinoCloud.begin(ArduinoIoTPreferredConnection);
  //Begin ENV shield.
  if (!ENV.begin()) {
    Serial.println("Failed to initialize MKR ENV shield!");
    while (1);
  }
}

void loop() {
  //ArduinoCloud.update();
  // if there's incoming data from the net connection.
  // send it out the serial port.  This is for debugging
  // purposes only:
  while (client.available()) {
    char c = client.read();
    Serial.write(c);
  }
    //Serial.println("Start reading sensors.");
    relativeHumidity = int(ENV.readHumidity());
    //Serial.println(relativeHumidity);
    lightIntensity = int(ENV.readIlluminance());
    //Serial.println(lightIntensity);
    airPressure = int(ENV.readPressure(MILLIBAR));
    //Serial.println(airPressure);
    temperature = int(ENV.readTemperature());
    //Serial.println(temperature);
    UV_Index = int(ENV.readUVIndex());
    //Serial.println(UV_Index);
    if (digitalRead(2) == LOW) {
      rain = 1;
    } else if (digitalRead(2) == HIGH) {
      rain = 0;
    }
    //Serial.println(rain);
    //Serial.println("Sensor data read.");
    //Serial.println("Start http request.");
    httpRequest();
    //Serial.println("Stop http request");
    delay(60000);
}

// this method makes a HTTP connection to the server:
void httpRequest() {
  // close any connection before send a new request.
  // This will free the socket on the Nina module
  client.stop();

  // if there's a successful connection:
  if (client.connect(server, 80)) {
    //Serial.println("connecting...");
    // send the HTTP PUT request:
    client.print("GET /weather_data.php?temp=");
    client.print(temperature);
    client.print("&pressure=");
    client.print(airPressure);
    client.print("&humidity=");
    client.print(relativeHumidity);
    client.print("&illumination=");
    client.print(lightIntensity);
    client.print("&UV_Index=");
    client.print(UV_Index);
    client.print("&rain=");
    client.print(rain);
    client.print(" ");
    client.println("HTTP/1.1");
    client.println("Host: 192.168.0.29");
    client.println("User-Agent: ArduinoWiFi/1.1");
    client.println("Connection: close");
    client.println();
  } else {
    // if you couldn't make a connection:
    //Serial.println("connection failed");
  }
}

void printWifiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your board's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}


ESP8266 as ISP program for ATMega16 I have used below program for ESP8266 as ISP to upload a program to an ATmega16.

ISP program uploaded in ESP8266

#include <SPI.h>
#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <ESP8266AVRISP.h>

const uint8_t reset_pin = 5;
const uint16_t port = 328;

ESP8266AVRISP avrprog(port, reset_pin);

void setup() {
    Serial.begin(9600);//115200
    Serial.println("");
    Serial.println("Arduino AVR-ISP over TCP");
    avrprog.setReset(false); // let the AVR run

    // listen for avrdudes
    avrprog.begin();
}

void loop() {
    static AVRISPState_t last_state = AVRISP_STATE_IDLE;
    AVRISPState_t new_state = avrprog.update();
    if (last_state != new_state) {
        switch (new_state) {
            case AVRISP_STATE_IDLE: {
                Serial.printf("[AVRISP] now idle\r\n");
                Serial.println("idle...");
                // Use the SPI bus for other purposes
                break;
            }
            case AVRISP_STATE_PENDING: {
                Serial.printf("[AVRISP] connection pending\r\n");
                Serial.println("pending...");
                // Clean up your other purposes and prepare for programming mode
                break;
            }
            case AVRISP_STATE_ACTIVE: {
                Serial.printf("[AVRISP] programming mode\r\n");
                Serial.println("Active...");
                // Stand by for completion
                break;
            }
        }
        last_state = new_state;
    }else{
      Serial.println("newstate not equal to old");
    }
    // Serve the client
    if (last_state != AVRISP_STATE_IDLE) {
        avrprog.serve();
        Serial.println("serve..");
    }
}

Then I have changed the board to ATmega16 and used programmer as AVR ISP and fetched/written below simple blink program to upload in ATmega16.

void setup() {
  // initialize digital pin 13 as an output.
  pinMode(1, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(1, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);              // wait for a second
  Serial.println("light on");
  digitalWrite(1, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);              // wait for a second
  Serial.println("light off...");
}

Tried uploading blink program to ATmega16 using ESP8266 as ISP by Sketch =>Upload Using Programmer. This resulted to compilation followed by uploading status in Arduino IDE for longer period. I didn't get any response after 10 mins of time. Then i have tried opening Serial Monitor which shows newstate not equal to old.

I am not sure what went wrong in my coding? How can I debug this issue ?

1. Uploading the sketch to your ESP8266

Tools > Board > select the appropriate ESP8266 board
File > Examples > ESP8266AVRISP > Arduino_Wifi_AVRISP
Change lines 7 and 8 to match the SSID and password of your WiFi router
Sketch > Upload
After the upload completes unplug the ESP8266 from your computer.

2. Generating the .hex file and the upload command

Open the sketch you want to upload to your ATmega16
Tools > Board > ATmega16
File > Preferences > Show verbose output during: > upload (check)
Sketch > Upload
The sketch will compile and then the upload will fail. This is the expected behavior. The goal of this process is to generate the .hex file that will be uploaded and the correct upload command.
Scroll the black console window at the bottom of the Arduino IDE window up until you see a line that looks something like:

>

E:\Arduino\hardware\tools\avr/bin/avrdude -CE:\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM54 -b115200 -D -Uflash:w:C:\Users\per\AppData\Local\Temp\arduino_build_288143/Blink.ino.hex:i

3. Connecting the ESP8266 to the ATmega16

Connect the ESP8266 to your ATmega16 board as follows:

+----------+-----------+
| ESP8266  | ATmega16  |
+----------+-----------+
| GPIO12   | MISO      |
| GPIO13   | MOSI      |
| GPIO14   | SCK       |
| GPIO5    | RESET     |
+----------+-----------+

You also need to power the ATmega16. It is recommended to use 3.3 V since this is what the ESP8266 is running at. Make sure the ground of the ESP8266 is connected to the ground of the ATmega16.

4. Starting the ESP8266AVRISP

Plug the ESP8266's USB cable back in to your computer
Tools > Serial Monitor
Select 115200 from the baud rate menu in the bottom right corner of Serial Monitor
You should see something like

  IP address: 192.168.0.100
  Use your avrdude: avrdude -c arduino -p  -P net:192.168.0.100:3000 -t # or -U ...

5. Uploading via ESP8266AVRISP

The second line you saw in the Serial Monitor in step 4 is the sketch's attempt to give you the AVRDUDE command you need to run to upload to your ATmega16 via the ESP8266AVRISP. Unfortunately they got a bit vague at the end. Apparently they are trying to steer you towards using AVRDUDE in terminal mode via the -t option but also mentioning that -U might be preferred. I recommend the latter since the Arduino IDE has helpfully generated the -U command for you already.
Since you need to run a custom AVRDUDE command to upload to your ATmega16 over the network you will not be able to do the upload via the Arduino IDE. Start the command line on your computer.
Now you need to merge the upload command you generated when you did the intentionally failed upload to the ATmega16 in step 2 with the command that was printed to Serial Monitor in step 4. In my examples, this merged command would be:

>

E:\Arduino\hardware\tools\avr/bin/avrdude -CE:\Arduino\hardware\tools\avr/etc/avrdude.conf -v -c arduino -p atmega16 -P net:192.168.0.100:3000 -Uflash:w:C:\Users\per\AppData\Local\Temp\arduino_build_288143/Blink.ino.hex:i

Your command will be similar to mine but the path to avrdude, avrdude.conf, the IP address, port, and path to the .hex file will be different. Enter your merged AVRDUDE command at the command line.
The upload should now proceed successfully.

Comments

The above is quite a complex process. Although it will be significantly easier with subsequent uploads, it will likely still not be as easy as an upload via the Arduino IDE. I would not recommend regularly using the ESP8266 as an AVR ISP simply because it's what you have on hand. Instead I would strongly recommend you to just buy a cheap (~$3 USD with free shipping from China) 6 pin USBasp from eBay.

The primary benefit of using the ESP8266 for this application is that it can be done over the WiFi network rather than the traditional USB connection but it's questionable how often that will truly be useful.


Reset Button not working + Can't Upload code , What is wrong? I was testing and debugging a code I wrote for a robot with 3 stepper motors on  (Arduino Uno + CNCShield V3 + a4988 stepper drivers). I want to disable drivers at will. so I bypassed EN pin on 2 of a4988s to pin12 and pin13 of Arduino. (by defalut all EN pins of drivers are are connected to pin8 ) everything was ok but suddenly the Reset button is not working and I can't upload new codes to Arduino! I get this error:

avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x83
.
.
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x83
Problem uploading to board.

but Arduino still is working with the last code that was uploaded to it!!! have I fried my Arduino? and Why is this happening?

Try manually resetting the board:

Before uploading, run Verify.
Hold the reset button and click Upload.
Release the reset button.

If that worked, your board's reset isn't fried, it just isn't receiving a reset via the serial cable. If it failed, either part of the board or MCU may be damaged; something attached to the board may be inhibiting the reset signal; or the software may have disabled the board's reset pin. In the latter case, see the Arduino StackExchange article, How do I repurpose Arduino's reset button, for how this can happen and how to undo it if it has.

  Is here anything wrong with using pins 12 and 13?

I'm not familiar with stepper driver, but at a quick glance at its data sheet, and it's logic being 3.3v & 5 v compatible, I don't see any problem with connecting any of its logic to any of Arduino's logic pins (almost all of them). Since the driver also has a motor drive-voltage input for driving your motors, accidentally connecting an Arduino pin to a driver pin (or anything else) carrying the drive-voltage could - probably would - damage at least the connected pin driver in the MCU, and possibly other parts of it as well.

If your Arduino has a socketed Atmega chip, and since you already know another Arduino works as you expect it to, replacing the Atmega chip will be the quickest, cheapest & easiest fix. Just go over your wiring and make sure no motor drive voltages are connected to the Arduino board.


Arduino + SIM808: How to get only the JSON object response without the header? I have been successfully getting the response from my web server. The problem is I get the whole package with header and content/body:

Recv: 325 bytes: HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
X-Powered-By-Plesk: PleskWin
Date: Wed, 02 Aug 2017 03:26:37 GMT
Connection: close
Content-Length: 18

1501644397698.2585

I want to only assign this 1501644397698.2585 to my double variable. How can I do this?

This is the code which sends and prints the response:

Serial.println("waiting to fetch...");
sim808.send(http_cmd, sizeof(http_cmd)-1);
while (true) {
  int ret = sim808.recv(buffer, sizeof(buffer)-1);
  if (ret <= 0) {
    Serial.println("fetch over...");
    break;
  }
  buffer[ret] = '\0';
  Serial.print("Recv: ");
  Serial.print(ret);
  Serial.print(" bytes: ");
  Serial.println(buffer);
  break;
}

You need to receive the whole header and them trim what you don't want. The easiest way of doing this is scanning the header string for a new line (\n) character. From the start of the string to the new line gives you a line of the header. If the length of this substring is < 1 then look for the next line. Now scan between the start and the new line and see if you see a colon (:), if you do then this line is part of the header, look for the next new line. Otherwise use strtod() to convert the data to a double.

It should be something like this (not compiled, not tested):

char* response = ".........";
char* pStartOfLine = response;
char* pEndOfLine = response;
bool bFoundData = false;
while (!bFoundData && pEndOfLine)
{
  while (pEndOfLine != NULL && *pEndOfLine != '\n')
    pEndOfLine++;
  if (pEndOfLine && pEndOFLine != pStartOfLine)
  {
    char* pStartOfData = pStartOfLine;
    while (pStartOfLine != pEndOfLine && *pStartOfLine != ':')
      pStartOfLine++;
    if (*pStartOfLine != ':')
    {
      theData = strtod (pStartOfData, NULL);
      bFoundData = true;
    }
  }
}

If it's in a separate function then you could just return rather than use the Boolean.

The order of the lines in the header are not guaranteed, but will always be in the same order from the same device with the same software, so as a cheat you could look for 'Content-Length: 18\r\n' and then just take the next non-blank line after that, but this is a more hacky way of doing it.


Using Arduino command line on windows I have an nmake file;

  srcpath = ..\pilot
  cmdline =  "C:\Program Files (x86)\Arduino\arduino.exe"
  cmdflags = --verify  --board arduino:avr:uno --port com4 -v --preserve-temp-files
  prefs = --pref sketchbook.path=$(srcpath) --pref build.path=build
  deps = $(srcpath)\pilot.ino $(srcpath)\commands.h $(srcpath)\publish.h $(srcpath)\motor.h

  pilot.hex :$(deps)
    type $(srcpath)\pilot.ino
    $(cmdline) $(cmdflags) $(prefs) $(srcpath)\pilot.ino

The file types out fine, but Arduino returns an error;

"failed to open sketch ..\pilot\pilot.ino"

I am setting --pref sketchbook.path=$(srcpath), but I have tried with and without (and many variations of both) and get the same error.

This is the command that is currently being invoked, and looks correct to me;

"C:\Program Files (x86)\Arduino\arduino.exe" --verify  --board arduino:avr:uno --port com4 -v --preserve-temp-files --pref sketchbook.path=..\pilot --pref build.path=build ..\pilot\pilot.ino

Any ideas?

srcPath = C:\Users\mikep\Documents\MWPRobotics\Pilot\Pilot
bldPath = $(srcPath)\build
arduinoCmd = "C:\Program Files (x86)\Arduino\arduino.exe"
arduinoFlags = --verify --board arduino:avr:uno --port com4 -v --preserve-temp-files --preferences-file $(bldPath)\pilotPrefs.txt
prefs = --pref sketchbook.path=$(srcPath) --pref build.path=$(bldPath)

deps = $(srcPath)\Pilot.ino $(srcPath)\commands.h $(srcPath)\publish.h  $(srcPath)\motor.h

pilot.hex : $(deps)
#   type $(srcPath)\Pilot.ino
    $(arduinoCmd) $(arduinoFlags) $(prefs) $(srcPath)\Pilot.ino

Apparently it is really picky about absolute full paths (contrary to the comments that say it is relative)


Arduino Micro interference between analog inputs I'm building a MIDI controller with the Arduino Micro, hooking a bunch of knobs up to the analog inputs. Currently, I'm getting analog in 9 being influenced by analog in 10: analogRead(9) returns a number close to analogRead(10) and doesn't give the voltage that I'm reading with a multimeter.

What could be causing this interference?

I looked around for a while and eventually thought to put the multimeter probe on the top pin instead of on the soldered header, and got no voltage across it.

If you're experiencing a strange interference between two analog inputs, double-check your solder joints again, one of your inputs might be floating (not connected to high or ground).


how to use Nano instead of Uno3 to operate DC motors OK I have the Logitech G29 Wheel and Pedal setup that I use for my Racing Sim. On YouTube there is a gentleman (amstudio) who has used motors on the Gas and Brake pedals to give some realism to the Sim. To achieve this he used a Uno 3 and a motor shield. The motors used are those that you'd find in the XBox/PS4 controllers. It's my understanding that the Uno 3, Nano and Micro are the same in its basic form, meaning that the sketch he uses can be used on all 3. If this is true then I want to use the smallest footprint to achieve the Rumble effect.
Question is how do I wire up the Nano to do this and with the motors as small as they are is it really necessary to have a motor shield or H bridges?
I have taken a picture of his Uno setup.  My aim here is to make it the smallest as it can be and still do the function of this mod' as this will be its only function. Any ideas on how best to go about this, The XBox Controller is rated at 5v @ 450mA. have included a picture showing his setup.thanks in advance

It's my understanding that the Uno 3, Nano and Micro are the same in its basic form

Not exactly. The Uno and Nano use the same chip (the Atmega328p) and have the same pins broken out. The Arduino Pro Mini also uses that chip, but I think the pinout is a bit different. But mostly a code can be reused between these boards. The Arduino Micro uses an ATmega32U4, which is a different chip. Depending on the actual code, you might not be able to just reuse the code. Then you might have to change to code to use the Micros hardware.

with the motors as small as they are is it really necessary to have a motor shield or H bridges?

I would say yes. A digital output pin of an Arduino can only supply 20mA of current over longer time (absolute maximum 40mA). Even very small motors can easily exceed that. As long as you don't know the exact needed current in worst case (like stalling the motor), you should assume, that it is more than 20mA. Also a running motor generates a lot of electrical noise and the coils can induce backcurrents, that might destroy the output hardware of the Arduino pin (for that you need a flyback diode). And lastly, if you want to change the direction of the motor, you absolutely need an H-bridge. Otherwise it is only on or off.

Question is how do I wire up the Nano to do this

With H-bridges you normally need 3 pins to control the motor:

The enable pin (often marked as EN) enables or disables the motor (run or stop). You normally use analogWrite(en_pin, speed) to control the speed of the motor. It will send a PWM signal with the given duty cycle to the enable pin.
And you have 2 input pins (often marked as IN). They give you control over the direction.

IN1 to HIGH and IN2 to LOW will give you the first direction. Reversing to IN1 LOW and IN2 HIGH will give you the other direction. This will cause the H-bridge to lead the current through the motor in different directions.
Setting them to the same value will cause the motor to break (because that will short circuit the motors coil).

So you would wire 3 output pins of the Arduino to the mentioned pins on the H-bridge. It is up to you, what you want to use here. You can use a shield (which is normally the size of the Uno), you can use other ready to use motor driver boards (there are many) or you could build your own driver with a H-bridge chip and flyback diode.


Arduino Mega's auxiliary serial ports If I am correct, the first two pins (RX/TX) are connected to the USB, and I cannot use the serial monitor and the first RX/TX serial ports at the same time.

But, what about the other 3 auxiliary serial ports? Are they separated? Do each one of them has it's own buffer?

For example: Is it possible to add, let's say, four Bluetooth modules(Let's say HC-05) and use each of them for a different purpose?

You can indeed use a serial monitor on your PC on the Mega's first serial port, in fact you will have to if you are connecting to one on the PC via USB port.. And just as with the Uno, you can connect a TTL serial device (like RS-232 serial, but using logic levels of 0 and +5v instead of [-3v - -25v] and [+3v - +25v] (which most PCs implemented as -12v and +12v).

If you need to connect to a true RS-232 device, you'll need to convert the TTL logic levels to something within the RS-232 spec; -5v and +5v would probably be the easiest.


Memory chip for arduino I know that you can't expand your ram because it is intern. But I want a extern memory chip (1024KBytes) that is very fast. I know that I need a library to access information on this chip. And functions to read and write data. A shield or breakout board it doesn't matter, and I want that it is compatible with Arduino mega. If the arduino lost power it doesn't matter if I lost the data. It must hold the data when the arduino is powerd.

You can quite easily connect multiple 128kB SPI ram chips to an Arduino. 4 of them together would give you 512kB of extra SPI-connected SRAM.

Access isn't super fast.

Another option is to use a parallel 8-bit SRAM chip. These take a lot more wiring since you need 8 wires for the data, log2(n) wires for the address, plus a couple of control wires (OE, WE, etc). But if you wire it making use of entire IO ports you can get much faster access times.  Also, these come in larger capacities than the SPI SRAM chips.

There is also PSRAM available in even bigger capacities. The same interface as SRAM but it's actually DRAM. The "P" stands for "Pseudo". You can get these in megabyte capacities, although they are usually in a BGA footprint, so you'd need to find one on a breakout board.


Arduino uno unexpected void loop stop I have a trouble with following, few lines code.
For some reason after few seconds Arduino uno stops responding into void loop section of code.
I tried to remove serial communication, all print and println without any success. Is the problem comming from MMA_7455.h?

#include <MMA_7455.h>
#include <Servo.h>

int servoPin = 9;
int servoAngle = 0;

Servo servo;

MMA_7455 accel = MMA_7455();
char yVal;
char yVal_bkp;

void setup() {
    servo.attach(servoPin);
    accel.initSensitivity(2);
    accel.calibrateOffset(1.0, 26.0, -69.0);
}

void loop() {
    yVal = accel.readAxis('y'); //Read out the 'y' Axis

    if(yVal_bkp != yVal + 2 || yVal_bkp != yVal -2)
    {
        servo.write(90 + yVal);
        yVal_bkp = yVal;
    }
}

P.S. Servo is normal G90

Have you checked that MMA_7455 can handle this many reads?
I had sensors that stop working because I asked to often for feedback.
As the servo needs a 20ms to adjust its location I would add a delay(20) to the loop.


Uploading Arduino bootloader to ATmega32U4 with another Arduino? I am in a situation where it is useful if I can upload a bootloader into an ATmega32U4 using another Arduino like this, for ex:https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard. I have a different circuit though.

Is there a reason to believe that this can't be adapted to ATmega32U4?

Are there any important differences between the ATmega328P and ATmega32U4, that I have to take into account for this to work?

The only difference you have to take into account is that if you're using an ATmega32U4 board such as Leonardo the SPI pins are not broken out to the pin headers along the edge of the board as is the case with the Uno shown in the tutorial you linked. Instead you should connect the programmer board to the ICSP header pins on your ATmega32U4 board, where the SPI pins are broken out:

MISO: ICSP-1
MOSI: ICSP-4
SCK: ICSP-3

So this means you can't follow the wiring shown on the tutorial exactly but it should be very easy to adapt that tutorial to your needs.


Deep Sleep NodeMCU with Door Sensor I have a very simple code of door sensor (magnetic) which gives results in 1 & 0 format. But I want to run the NodeMCU only when a door is open or close. Rest of time I want to keep it in deep sleep mode. Here is my code looks like :

int doorClosed = 1;

#define REED_SWITCH D5

void setup() {
  // put your setup code here, to run once:

  Serial.begin(115200);
  pinMode(BUILTIN_LED, OUTPUT);
  digitalWrite(BUILTIN_LED, HIGH);

  pinMode(REED_SWITCH, INPUT_PULLUP);
}

void loop() {
  // put your main code here, to run repeatedly

   Serial.println(digitalRead(REED_SWITCH));

    if ((digitalRead(REED_SWITCH) == HIGH) && (doorClosed == 1))
    {
      Serial.println("DOOR OPEN!!");
      doorClosed = 0;
      digitalWrite(BUILTIN_LED, LOW);
      ESP.deepSleep(0);
    }
    else if ((digitalRead(REED_SWITCH) == LOW) && (doorClosed == 0))
    {
      Serial.println("DOOR CLOSED!!");
      doorClosed = 1;
      digitalWrite(BUILTIN_LED, HIGH);
      ESP.deepSleep(0);
    }
    delay(500);
}

Here I am able to put the NodeMCU in deep sleep. But it never wakes up. How can I wake up my chip. After attaching the D0 with RST, I don't event get Serial Logs. I am not sure what kind of behaviour is this. If someone can help me to fix this code will be great!

Thank you!

According to this guide:

  The RST pin of the ESP8266 is always HIGH while the ESP8266 is
  running. However, when the RST pin receives a LOW signal, it restarts
  the microcontroller.

  If you set a Deep Sleep timer with the ESP8266, once the timer ends,
  GPIO 16 sends a LOW signal. That means that GPIO 16 when connected to
  RST pin can wake up the ESP8266 every time the timer ends.

The only way to wakes up ESP8266 from deep sleep mode without timer is set a LOW signal on RST pin.

Example without timer:

ESP.deepSleep(0);

Connect D0 (GPIO 16) to RST is available only when ESP8266 is in sleep mode with timer.

Example with 30sec timer:

ESP.deepSleep(30e6);

In your case, you can use deep sleep with timer and connect Door sensor to D0 and will act as switch between the RST and D0.


Converting (char*)variable to int I have the following code:

      uint8_t buf[1];
      uint8_t buflen = 1;
      if (driver.recv(buf, &buflen)) // Non-blocking
         {
            int i;
            // Message with a good checksum received, dump it.
            Serial.print("Message: ");
            Serial.println((char*)buf);//this prints out okay
            highPins[(char*)buf] = 1;
         }

The problem is in highPins[(char*)buf]. highPins is array, and in (char*)buf I get index number. When I display it with Serial.println, it shows the number, but here it does not. I am guessing its because (char*)buf is not a number. I have tried to convert it to int with few functions I have found online, but it was unsuccessful. Any help is appreciated :)

I would suggest improving your code slightly as follows:

  uint8_t buf;
  uint8_t buflen = 1;
  if (driver.recv(&buf, &buflen)) // Non-blocking
     {
        int i;
        // Message with a good checksum received, dump it.
        Serial.print("Message: ");
        Serial.println(buf);//this prints out okay
        highPins[buf] = 1;
     }

The important point is that you do not need to declare buf as an array of just one element, but just declare the element itself (as uint8_t) and pass its address (&buf) to driver.recv(...).

As @Majenko suggested, you should alos check buf before using it as an index to highPins array, in order to avoid using an index bigger than teh array size.


EPS8266 ESP-01: LED manipulation seems to interfere with serial communication I'm playing around with this udp-example. Both this and the blink-example work perfectly. Now I would like to use the LED to indicate what the ESP is currently doing, as well as reading some data over Serial. My code looks like this:

void setup(){
  Serial.begin(115200);
  Serial.setTimeout(500);
  while(Serial.available()==0){
  }
  String password = Serial.readStringUntil('.');
  Serial.println(password);
  WiFi.begin(ssid.c_str(), password.c_str());
  //pinMode(LED_BUILTIN, OUTPUT);
  while (WiFi.status() != WL_CONNECTED){
    //digitalWrite(LED_BUILTIN, LOW);
    delay(250);
    //digitalWrite(LED_BUILTIN, HIGH);
    delay (250);
  }
  Serial.println("connected");
  Udp.begin(localUdpPort);
}

It works fine, but if I uncomment the led-lines the serial communication doesn't seem to work anymore. All the stuff that is printed on the Serial Monitor is now messed up (missing characters, ...). Is there a problem with my code or what else could be possible going wrong here?

EDIT: I recently tried the same code again, but used an additional power supply (3.3V, 500mA) for the chip. However, this didn't resolve the problem.

I would bet that the built-in LED pin is also the TX pin for the serial interface.

Check here, LED Pin section: http://www.esp8266.com/wiki/doku.php?id=esp8266_gpio_pin_allocations

  LED Pin

  GPIO1, which is also TX, is wired to the blue LED on many devices.
  Note that the LED is active low (connected to Vcc and sinks through
  the chip to ground) so setting a logical value of 0 will light it up.
  Since GPIO1 is also the TX pin, you won't be able to blink the LED and
  perform Serial communications at thew same time unless you switch
  TX/RX pins.

This would be confirmed if the LED blinks when serial communication is active.

If this is the case you would have to add your own LED on a different pin, or switch the RX/TX pins.


Control LED strip via serial monitor I've been struggling with writing a code for Arduino UNO so that I could use my phone and change the colour of the LED strip via terminal.

#include <FastLED.h>
#include <SoftwareSerial.h>

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

#define NUM_LEDS 22
#define DATA_PIN 6
CRGB leds[NUM_LEDS];

void setup() {

  btSerial.begin(9600);
  btSerial.println("Connected to Arduino");
  FastLED.addLeds<WS2812, DATA_PIN>(leds, NUM_LEDS);
}

char a;

void loop()
{
    if (btSerial.available())
    {
      a= (char)btSerial.read();

      if(a=="b")
      {
        btSerial.println("Turning LED blue");
        leds[0] = CRGB::Blue; // Turns 1 LED to blue
        FastLED.show();
      }
    }
}

So basically I'd like to be able to change LED colours with my phone. If you enter "r", the LEDS turn red, if you enter "b", leds turn blue etc. Maybe even add some patterns. Brightness controller would be nice too to save some battery.

EDITED. Serial works.

#include <FastLED.h>
#include <SoftwareSerial.h>

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

#define NUM_LEDS 22
#define DATA_PIN 6
CRGB leds[NUM_LEDS];

void setup() {
  Serial.begin(9600);
  btSerial.begin(9600);
  btSerial.println("Connected to Arduino");
  FastLED.addLeds<WS2812, DATA_PIN>(leds, NUM_LEDS);}

char a;

void loop(){
    if (btSerial.available())
    Serial.write(btSerial.read());
    if (Serial.available())
    btSerial.write(Serial.read());}

3.

#include <FastLED.h>
#include <SoftwareSerial.h>

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

#define NUM_LEDS 22
#define DATA_PIN 6
CRGB leds[NUM_LEDS];

void setup() {
  Serial.begin(9600);
  btSerial.begin(9600);
  btSerial.println("Connected to Arduino");
  FastLED.addLeds<WS2812, DATA_PIN>(leds, NUM_LEDS);}

char a;

void loop(){
    if (btSerial.available())
    Serial.write(btSerial.read());
    if (Serial.available())
    btSerial.write(Serial.read());}

    if (a=='b'){
      btSerial.println("Turning LED blue");
      leds[0] = CRGB::Blue;
      FastLED.show();}

RECENT:

#include <FastLED.h>
#include <SoftwareSerial.h>

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

#define NUM_LEDS 28
#define DATA_PIN 6
CRGB leds[NUM_LEDS];

void setup()
{
  Serial.begin(9600);
  btSerial.begin(9600);
  btSerial.println("Connected to Arduino");
  FastLED.addLeds<WS2812, DATA_PIN>(leds, NUM_LEDS);
}

char a;

void loop()
{
  if (btSerial.available())
  {
    a= (char)btSerial.read();

    if( a == 'b' )
    {
      btSerial.println("Sinine"); //All LEDs are blue
      fill_solid( leds, NUM_LEDS, CRGB::Blue);
      FastLED.show();
    }

    if( a == 'r' )
    {
      btSerial.println("Punane"); //All LEDs are red
      fill_solid( leds, NUM_LEDS, CRGB::Green);
      FastLED.show();
    }

    if( a == 'g' )
    {
      btSerial.println("Roheline"); //All LEDs are green
      fill_solid( leds, NUM_LEDS, CRGB::Red);
      FastLED.show();
    }

    if( a == 'y' )
    {
      btSerial.println("Sinine"); //All LEDs are yellow
      fill_solid( leds, NUM_LEDS, CRGB::Yellow);
      FastLED.show();
    }

    if( a == 'w' )
    {
      btSerial.println("Sinine"); //All LEDs are white
      fill_solid( leds, NUM_LEDS, CRGB::White);
      FastLED.show();
    }

    if( a == 'o' )
    {
      btSerial.println("Väljas"); //All LEDs are turned off
      fill_solid( leds, NUM_LEDS, CRGB::Black);
      FastLED.show();}

    if ( a == 'z' ) //1 blue LED from start to finish
    {
      int i= 2;
      while (i > 0)
      {
        for (int dot = 0; dot < NUM_LEDS; dot++)
        {
            leds[dot] = CRGB::Blue;
            FastLED.show();
            leds[dot] = CRGB::Black;
            delay(100);
        }
      }
    }

     if ( a == 'x' ) //1 red LED from start to finish
     {
      int i= 2;
      while (i > 0)
      {
        for (int dot = 0; dot < NUM_LEDS; dot++)
        {
            leds[dot] = CRGB::Green;
            FastLED.show();
            leds[dot] = CRGB::Black;
            delay(100);
        }
      }
     }
  }
}

You seem to lack the basic understanding, how Serial (UART) communication works. So I will explain the basic principles. From there you should be able to implement, what you want.

Serial (aka UART) transmits the data serially, byte after byte (thus it's name). When you type in a text in the Serial Monitor of the Arduino IDE and send it, you have no influence, when exactly each byte will be transmitted. As the UART interface doesn't know messages or "chunks of data", only bytes, it will transmit each byte, when it is ready. There might be a short pause inbetween the bytes. This is an important fact to know, if you want to implement commands longer than 1 byte.

The normal Serial interface is mostly implemented in the Uno's hardware, thus it doesn't depend on the running software that much. SoftwareSerial does all the hard communication work in software, thus it comes with some caveats (blocking write operations, more limited baudrate, only possible to receive on one SoftwareSerial interface at once, ...). But both mostly share the same code interface.

Serial.available() returns the number of received bytes, that are still in the internal buffer. You are already using this to only read from the buffer, when there is actually data to read in it (with the if statement). Then you read one byte from the buffer by Serial.read(). Currently you are giving the return value (the read data) directly to the other serial interface for sending. Thus the value is not saved anywhere in your sketch. Doing a Serial.read() will remove the read byte from the buffer and return it. Thus the read byte will no longer be in the buffer.

The code with the 2 if statements and serial functions is mostly used to forward the data between the two serial interfaces. For your use case you don't need this. Instead you should read the data into a local variable like you did in your first sketch:

if (btSerial.available())
{
  a= (char)btSerial.read();

  if(a=="b")
  {
    btSerial.println("Turning LED blue");
    leds[0] = CRGB::Blue; // Turns 1 LED to blue
    FastLED.show();
  }
}

Here you are first checking, if there is data to read in the btSerial buffer. If yes, you read it into the variable a. This variable now holds a single character. If you also want to forward this character to Serial, you can now use Serial.write(a); to do so. Then you want to check the value of the received character. Here we are doing a little excourse:

In C/C++ 2 different kinds of quotes are used: The double quotes " and the single quotes '. Double quotes mark string literals, which consists of a series of characters. Single quotes mark single character values - only one character. In your if statement you check for equality. If you think about it, you see, that checking if 2 single characters are equals is a lot easier, than checking if two strings are equal (checking 1 character on each side versus checking multiple characters on each side). Thus it is a difference, if you compare string literals or single characters. Comparing a single character variable with a string literal doesn't work - they are two completely different things. Instead you should compare the character variable to a single character:

if( a == 'b' )

As you are adding more commands for your project, you will see, that if statements don't order the code very good. In this case a switch statement is better:

switch(a){
    case 'b':
        // Doing what you want to do with the LEDs here
        break;
    case 'c':
        ...
        break;
}

This will execute the corresponding code part depending on the value of a. You can read more about this construct on the web (google something like "C switch").

Now you should be able to implement simple 1 byte/character commands in your code. Also review and understand the examples from the Arduino IDE about Serial.

If you need more complex commands (maybe with some payload data in addition to the command), you have to introduce a communication protocol onto the Serial interface. The simplest way is to define whole messages by using a delimiter character at the end of every message. Mostly the newline '\n' character is used for this purpose. You basically read the data from Serial and save it on a char-array/string until you received the newline character. Then you know, that you have received a complete message, and you can start to process it as a whole. When finished, you clear your message buffer and again wait for a new message. For this to work, you of course have to ensure, that the delimiter character is never part of your send data (as the code would think, that it marks the end of the message).

You can see this in the SerialEvent example in the Arduino IDE. Try to understand, what happens there. There are also many tutorials on the web.

I hope, I could enlighten you a bit. Good luck with your project.


What's Happened with my Arduino? I am in a First Year Design class, and we are supposed to be making an autonomous robot. After hooking up some wind speed and temperature sensors to calibrate, I plugged in to my laptop (we have 2 arduino nanos) and ran a temperature code. I got the reading, but smelled something burning. Nothing was smoking, but I've found that when I plug my arduinos into my laptop, the light and the code indicate that they are not connected. This is odd because when I plug in the batteries, they show that the proper voltage is coming through, but they will still not connect to the laptop. Is it a problem with the micro-usb port?

I've included the code I'm using just in case that is cause for suspicion. It is notable that our instructors have written an API that allows us to code in Java for the arduinos.

public static void main (String[] args)
{
    robot = new ArduinoNano();
    robot2 = new ArduinoNano();
    robot.setPort("COM5");
    robot2.setPort("COM6");
    robot.connect();

    int reading = getThermistorReading();

    System.out.println("The probe read the value " + reading);
    System.out.println("In volts: " + (reading * (5.0/1023.0)));
    System.out.println();

    double temperature = (reading - 855.02) / -7.563;

    System.out.println("Temperature: " + temperature);

}

public static int getThermistorReading()
{
    int sum = 0;
    int readingCount = 10;

    for (int i = 0; i < readingCount; i++)
    {
        robot.refreshAnalogPins();
        int reading = robot.getAnalogPin(3).getValue();
        sum += reading;
    }

    return sum / readingCount;
}

}

First, did the Arduino continue to respond and operate after you smelled the burning?

Just because there isn't smoke doesn't mean you didn't kill something on the board.

If your Arduino is not responding, there are two possibilites I can think of:

Your port is not working so simply switch to a different USB port
Somehow your laptop must have sent a large amount of amps/volts to the circuit and burned it out. If you have a multimeter you can use the sound setting to test whether or not wires are burned out, and if your nifty with an iron/heat gun, you can replace the part. Or you could buy a new one.

If the connection is good, you will hear a small beep. Oh, and these things don't work if there's a resistor in the way.


Arduino potentiometer example: what limits the current? I have a question regarding potentiometer example:

https://www.arduino.cc/en/Tutorial/AnalogReadSerial

If I turn the potentiometer to the marginal position and have 5V at A0 (and almost zero resistance at the pot), what limits the current flowing through the circuit?

A0 input is high impedance, so very little current is flowing into A0. The value is so small that you can simplify that it flows only from +5V through the potentiometer to GND.

For some applications, when you are measuring high-impedance sources (a source that can deliver very little current) this simplification may not be correct.

You can find more detailed explaination in Atmel application note:

http://www.atmel.com/images/atmel-8456-8-and-32-bit-avr-microcontrollers-avr127-understanding-adc-parameters_application-note.pdf


What is the smallest microcontroller capable of running Arduino? I'd like to know which is the most powerful, lightest, and perhaps least expensive micro controller capable of running Arduino.

Well, your questions is quite vague and perhaps overly broad.  I'll answer your main question "what is the smallest," assuming you meant dimensionally, while keeping in mind that you also want the most powerful one in that size. The pricing of different chips like this will be fairly similar so I'll ignore that.

Next, I'm not sure what you meant by saying "capable of running Arduino" which may mean capable of having the Arduino bootloader installed or could mean being capable of running code written with Arduino libraries.  I'll assume the latter since it's the most practical requirement. I'll also assume you want an Atmel chip since it will be the most directly compatible with the Arduino libraries.

So what is the most powerful of the smallest Atmel microcontrollers capable of running Arduino code?

The answer is probably the Attiny 10 which comes in a 2 x 2mm 8-UFDFN Exposed Pad package, or a 2.9 x 1.6mm SOT-23-6 package for about one dollar in small quantities.

Also see this Hackaday article on how to use the Attiny10 with Arduino.

Edit: After more research, I was unable to find an Arduino core for the Tiny10. So while you can program it with an Arduino using assembly or something, writing Arduino code for it won't work.  The smallest Attiny with an Arduino core I could easily find is the Attiny13 in a 3 x 3mm 10-VFDFN package.  The upside is that while not being that much bigger or more expensive, it's a way more capable chip for your project.


How fast is an Arduino? Can an Arduino Uno calculate the time that an assembly instruction will take in nanoseconds, not microseconds? I don't want to use a PC, because the calculation will be more accurate using an Arduino, as the processor won't be running other tasks.

If the Arduino can't, is there any way to improve it, or any other open source hardware that can do?

How fast is an Arduino?

Arduino Uno is based on AVR MCU and run at 16 MHz. Due to the processor architecture it can execute almost 1 instruction per clock cycles (62.5 ns). It uses a simple two step pipeline which may require restart if a branch is taken. There are some instructions such as memory access that take more than one clock cycle.

  Can an Arduino Uno calculate the time that an assembly instruction will take in nanoseconds, not microseconds?

It is possible to measure the execution time with a resolution of 4 us with micros(). Please describe what you want to calculate/measure.

For more details on ATmega328p please see the data-sheet, chap. 6.6 Instruction Execution Timing.


detecting signal coming from another motion sensor that triggers camera's shutter I have a motion sensor (used for camera trapping) that sends a signal to the camera to trigger the shutter. I am trying to use Arduino to turn on lights for 10 seconds by getting the signal from the motion sensor. I know there are ways to use motion sensor that can be used with Arduino. However, I need to know how I can detect a signal coming from the sensor to feed it to Arduino. I have tried connecting the cable from the sensor to A0, wrote a simple code to print the value of A0 but the serial monitor of Arduino shows nothing.

Sorry I am typing this here coz I don't have enough rep to comment. Anywho, most of the motion sensors involve PIR tech, so the best way is to connect your PIR Signal pin from your sensor to any analog pin of your arduino and test the kind of signal you're getting when the environment is idle and when movement is detected, Keep in mind of the region that the sensor covers too (ROI). That will tell you some things,

If the sensor works or not.
If the sensor value is analog or digital
If the sensor is active high or low
Trial and error on the actual ROI

After all that you can write your code around it.


Write to file in SD card in wave shield V3 I just started tinkering with Arduino. I'm curious to know though, is it possible to read and write to a file stored in the SD card in the Wave shield v3 by Elechouse? I'm able to play files stored in said SD card, but I don't know how I'd go about writing some logs. I'm using an Arduino Mega.

Thanks in advance.

No, you cannot.  The shield is basically a cheap WAV or AD4 (whatever THAT is) playing chip which loads the audio data direct from an (old, small) SD card.  The only control you have is IO pins that emulate pressing the buttons on an MP3 player.


Are there any constants for default SPI port pins defined? I'm writing a library which controls a device using SPI bus. For the communication I need to manually toggle the chip select pin. On most Arduinos SS pin is on D10, but there are also other models where it's different like D53 on Mega. Is there a way to know where it is? Like a global #define? I would like to avoid any pin configuration parameters in my library. At least for default configuration...

Yes there are. They are defined in pins_arduino.h Below the pins for the yun.

// Map SPI port to 'new' pins D14..D17
static const uint8_t SS   = 17;
static const uint8_t MOSI = 16;
static const uint8_t MISO = 14;
static const uint8_t SCK  = 15;

Use SS MOSI MISO and SCK in your code