How to purge incoming Xbee packets from the buffer? I have a need to receive a specific confirmation packet after commanding my transmitting Xbee to stop sending normal packets.

My buffer still has normal packets in it when this happens, so next time I call readPacket(), I don't want to see them. So right before I call my stop command, I try to purge the incoming buffer like this:

void burnSerial(void) {
  while (xbee.readPacket(20)) {
    xbee.getResponse().getRx16Response(rx16);
  } //read all available responses
    // only do this when not in a constant stream of responses or it may hang.

  while (Serial.available()) { Serial.read(); }
  //burn whatever may be in serial buffer
}

But this doesn't work. The next time I call xbee.readPacket(), I see tons of normal packets before I finally see my confirmation packet. Why don't these functions do anything for me at all?

It means there's a lot of latency between your issuing a command and getting a confirmation of the command's effect. When you send the command, it's best that you wait and read packets until you find the confirmation and then you return from the function or do whatever else you want to do. There is no need for a separate burnSerial() function, nor should you blindly discard data. So basically, the sequence of operations should be:

Send the command
Read packets until you find the 'confirmation' identification marker
Return or exit

This assumes that your transmitter only sends confirmation after it has halted the stream.


I have the error: expected unqualified-id before 'if' This is my Sketch or code:

const int EchoPin = 5;
const int TriggerPin = 6;
const int LedPin = 13;

void setup() {
 Serial.begin(9600);
 pinMode(LedPin, OUTPUT);
 pinMode(TriggerPin, OUTPUT);
 pinMode(EchoPin, INPUT);
 pinMode(13, OUTPUT);
}

void loop() {
 int cm = ping(TriggerPin, EchoPin);
 Serial.print("Distancia: ");
 Serial.println(cm);
 delay(1000);
}

int ping(int TriggerPin, int EchoPin) {
 long duration, distanceCm;
 digitalWrite(TriggerPin, LOW);
 delayMicroseconds(4);
 digitalWrite(TriggerPin, HIGH);
 delayMicroseconds(10);
 digitalWrite(TriggerPin, LOW);
 duration = pulseIn(EchoPin, HIGH);
 distanceCm = duration * 10 / 292/ 2;
 return distanceCm;
}

if (distanceCm <= 20) {
 digitalWrite(13, HIGH);
}

if (distanceCm >= 20) {
 digitalWrite(13, LOW);
}

The error appears in the second if.

The error is occurring because you have 2 if statements outside of a function. You could move them into the ping() function which would fix the error but there seems to be a logic error with the 2 if statements as well.

If distanceCm is 20, both if statements execute one right after another, so I doubt you'll see the LED turn on. Perhaps an if/else might work.

if(distanceCm < 21){
  digitalWrite(13, HIGH);
}
else{
  digitalWrite(13, LOW);
}


How do I communicate with the Uno using R through RStudio? I am working on a real time application which is recording sensor data continuously. I need to process the data in realtime using R. Is there a way to connect and communicate with the uno board through RStudio via serial port?

If RStudio has serial support. Yes, it can talk to a Uno. If it does not. No.

This is really a question about RStudio (and actually just pure R), not arduinos.

Furthermore, RStudio is just an IDE. Therefore, no, RStudio can not communicate with an arduino, compile a program, or do much of all aside from edit source-code files. RStudio does not run your code at all. It uses an external interpreter to run your source files.

R, on the other hand probably can talk to serial interfaces. The fact that you're using RStudio is entirely irrelevant.

I'm not familliar with R, but a little googling leads me to think that R can talk to serial interfaces without too much trouble, though I have not been able to find any information about doing so on windows. What platform are you using?


Cisco Switch not receiving serial communication from Arduino So I have an issue that I can't really think of a reason why it would be happening. I have an Arduino Mega connected on Serial3 to a RS232 breakout board with a male DB9 connector on it. I then have two female breakout boards connected. One is connected to the RS232 breakout board and the other to a Cisco DB9 to roll over cable, which is connected to my Cisco Switch, or if it is, it is being ignored.

For some reason no data sent from the Arduino is making it to the Cisco switch that I can tell. I did confirm that it is sending data using a USB to DB9 adapter and PUTTY. I can send and receive data from both the Arduino and PUTTY correctly to the other.

I can receive data from the switch perfectly. Cisco's default settings are the same as the Arduino's, 9600, 8bits, no parity, 1 stop bit etc...

I can also connect the switch to the USB to DB9 adapter directly and send and receive fine through it / PUTTY as well.

Does anyone have any suggestions why I'd be able to send data to and from Putty, but only receive data from the switch, or why the data going to the switch is failing?

void setup() {
  Serial.begin(9600, SERIAL_8N1);
  Serial3.begin(9600, SERIAL_8N1);
  Serial.println("Ready....");
  Serial.println();
}

void loop() {
  // read from Serial3, write to Serial
  if (Serial3.available()) {
    int inByte = Serial3.read();
    Serial.write(inByte);
  }
  // read from Serial, write to Serial3
  if (Serial.available()) {
    int inByte = Serial.read();
    Serial3.write(inByte);
  }
  Serial3.println(); // Added just to test if a cr could be passed
  Serial3.write(98); // Added just to test if a character could be directory passed
  Serial3.write(10); // Added just to test if a cr could be passed
}

Assuming this is a flow control problem:

  Is there such a thing as inb vs oob for a serial console connection?
  This isn't on the internal network of the switch in any way but the
  console port

It assumed this is a managed switch and the traffic on the console port has nothing to do with the traffic going through the switch. Rather this is likely a port to the computer inside the switch.  Such a port might be able to use RTS/CTS/DSR or X-on / and X-off.

If this is a flow control problem, consider first looking for thumb switches on the back of the switch to see if the method used for flow control over the console port can be selected. If that is not possible, consider simply hardwiring the out of band flow control pins to always allow for data to flow.  At 9600 baud, a dedicated Aruidno should be able to keep up.

Refer to the 9 pin connector in this chart to find the out of band flow control pins.


What is the tool to send file to SPIFSS on ESP8266/32? Is there good tools (IDE, CLI or IDE addon) to send file via USB port to SPIFSS internal espressif ESP hardware SoC ?

The mkspiffs tool creates bin from file system data (or extracts data from bin).

SPIFFS bin is uploaded with esptool over USB or with espota over WiFi. It can be uploaded with the sketch binary in one command.

Example:

esptool.py -p /dev/ttyUSB0 write_flash 0x0 sketch.bin 0x300000 spiffs.bin

The IDE plugin adds SPIFFS upload to Arduino IDE Tools menu.


Weird char on a 20X4 LCD I'm trying to make an RC controller.
I have a problem with my LCD.

I have already double-checked the wiring and the connections are great.
I made a PCB with Kicad and order it to JLCPCB. I have some mistake, you can see the soldered wire.

Before the PCB, I did my project with a breadboard and it worked fine.
const String menuElem[4] = {"Models", "Trims", "Reverse command", "Channel"};

const int rs = 3, en = 4, d4 = 5, d5 = 6, d6 = 7, d7 = 8;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void menu() {
  lcd.clear();
  //lcd.setCursor(0,0);
  //byte pos = 0;
  //int sizeOfanArray = *(&array + 1) - array;
  byte menuElemLength = *(&menuElem + 1) - menuElem;
  for (byte i = 0; i < menuElemLength; i++) {
    lcd.setCursor(2, i);
    lcd.println(menuElem[i]);
  }
  showMenuNav(currentMenuPos);
}

Your code to calculate the length of your Strings does not make sense. The String type is an object type. The addresses of your String objects will not match the length of the charcters in those strings. You should use an array of C strings as suggested by Juraj, and then you should use strlen() to get the length of those strings (C strings have a null terminating byte, and strlen() uses that null to calculate the length. Note that C strings can't handle Unicode.)
The String type is best avoided on Arduino anyway, as String objects tend to fragment the extremely limited heap memory on Arduino devices and cause out-of-memory crashes.


SPI read while writing? I'm working on a driver for an SPI device that returns some data (device status) while the command byte is still being written.  Is there a way to read this status data using standard Arduino APIs or do I need to bit-bang to access it?
Here's what the SPI signals look like:

The 6 bits in red are the ones I'm interested in reading.

For context, the device in question is a Microchip MCP3561 ADC (MCP3X6X series).  It has a bug (erratum 2) where the new-data-ready flag (/DR_STATUS) is not always set correctly.  Part of the work-around involves reading the status bits mentioned above.

The SPI.transfer() method is designed to send a byte through
the SPI port and, at the same time receive an incoming byte.
Usage pattern:
uint8_t byte_to_send = ...;
uint8_t received_byte = SPI.transfer(byte_to_send);


Timers, PWM pins and digital outputs on Arduino Mega I'm using an Arduino Mega to control motors via PWM and Adafruit DRV8871 motor drivers.  I also use TIMER1 for a timed interrupt.  After adding the TIMER1 interrupt I discovered I had problems with motor control, which I finally tracked down to using pins 11 & 12 for PWM simultaneously with using TIMER1 for timed interrupts.
My initial thought was to change the timer used for the ISR to avoid the pin 11/12 conflict, but now I'm uncertain as to what the restrictions are for using pins associated with timers.  I now realize that pins associated with a timer interrupt can't be used for PWM using analogWrite(int val), but can they be used as general purpose digital outputs?
For instance, if I change from TIMER1 to TIMER0 for my timer interrupt, that appears to change the pin dependency from 11/12 to 4/13.  I don't use pin 13, but I do use pin 4 as a digital output.  Will using pin 4 as a digital output still work properly?
TIA,
Frank

You can use them for any purpose other than PWM.  You can even use them for PWM as long as the settings for the timer allow you to produce the waveform you want.
The reason PWM broke was that you had changed the settings for the timer.  The timer is what controls the PWM.  When you changed those settings you either turned the PWM function off or set some setting where it wouldn't work.  Then the pins associated with that timer didn't get PWM anymore.  You can do anything else you want that doesn't involve the timer including use the pin for input or output or any other special function it has not related to the timer.
If you change the timer interrupt to TIMER0, then you run the risk of delay, millis, and micros stop working right.  They depend on the TIMER0 overflow interrupt running at a set interval to count time.  It depends on how you set the timer up.
I would suggest you do some reading on how these timers work.  The Datasheet for the ATMega328P chip is a great place to start.


Problem uploading the code into an Arduino Uno I was trying to upload code for a blinking LED. It is a new Arduino Uno board. Any further help will be appreciated.I got the following error:

Info.: OS- Ubuntu 16.04
Software: Arduino IDE 1.8.5

I could not see any port.
I have tried dialout. But still it is not working.
I also have a confusion, i.e. the Programmer menu shows AVRISP mkll.

If anyone wants any information, please do comment.
Error:

An error occurred while uploading the sketch
avrdude: ser_open(): can't open device "COM1": No such file or directory`

Ubuntu and other Linux operating systems don’t name the serial ports “COM1” or similar.

They use special files like

/dev/tty.[something]

The [something] depends on the USB device driver. The IDE should list available serial ports in the Port selection menu.


How to use a common anode 7-segment, 4-digit display? Please take this question as an example to (my own) answer below.

I've got an 7 segment, 4 digit LED display, but I don't have any idea on how to wire it.

I don't understand the difference between common anode/cathode, and I don't have 2 pins per LED, which is strange.
Quite recently, a question on a "7 segment 4 digit common anode" got deleted.
At that very moment I was typing an answer.

Though, I still want to share my answer with you, or the person who asked it.
Please verify/update my answer with more information.
Specifically, could someone add working code, I can't at the moment.

Just as a complement to Paul's answer, I wrote a short program to show
how to drive the 7-segment 4-digit display of his figure:

This is actually a common cathode display, so the program assumes that,
as well as the particular wiring of the figure. The interesting part is
the refresh_display() function, which should be called periodically.
The algorithm is as follows:

drive the 7 anodes with the appropriate signals for one of the digits
we want to show
set HIGH the output that controls that digit's cathode through the
NPN transistor
wait for 2.5 ms (for a refresh rate of 100 Hz)
set LOW the cathode-controlling output
move to the next digit.

It should be noted that the waiting is done without blocking the CPU, by
using the technique described in the Blink Without
Delay Arduino
tutorial. Here is the program:

const int NB_DIGITS     = 4;  // 4-digit display
const int FIRST_ANODE   = 2;  // anodes a..g on pins 2..8
const int FIRST_CATHODE = 9;  // cathodes, right to left, on pins 9..12

// Digits to display, from right to left.
uint8_t digits[NB_DIGITS];

// Set all the used pins as outputs.
void init_display()
{
    for (int i = 0; i < 7; i++)
        pinMode(FIRST_ANODE + i, OUTPUT);
    for (int i = 0; i < NB_DIGITS; i++)
        pinMode(FIRST_CATHODE + i, OUTPUT);
}

// This should be called periodically.
void refresh_display()
{
    // Our 7-segment "font".
    static const uint8_t font[10] = {
        //abcdefg
        0b1111110, // 0
        0b0110000, // 1
        0b1101101, // 2
        0b1111001, // 3
        0b0110011, // 4
        0b1011011, // 5
        0b1011111, // 6
        0b1110000, // 7
        0b1111111, // 8
        0b1111011  // 9
    };

    // Wait for 2.5 ms before switching digits.
    static uint32_t last_switch;
    uint32_t now = micros();
    if (now - last_switch < 2500) return;
    last_switch = now;

    // Switch off the current digit.
    static uint8_t pos;
    digitalWrite(FIRST_CATHODE + pos, LOW);

    // Set the anodes for the next digit.
    pos = (pos + 1) % NB_DIGITS;
    uint8_t glyph = font[digits[pos]];
    for (int i = 0; i < 7; i++)
        digitalWrite(FIRST_ANODE + i, glyph & 1 << (6-i));

    // Switch digit on.
    digitalWrite(FIRST_CATHODE + pos, HIGH);
}

/***********************************************************************
 * Example usage.
 */

void setup()
{
    init_display();
}

void loop()
{
    uint32_t now = millis();

    // Change the number displayed every second.
    static uint32_t last_change;
    if (now - last_change >= 1000) {
        digits[3] = digits[2];
        digits[2] = digits[1];
        digits[1] = digits[0];
        digits[0] = (digits[0] + 1) % 10;
        last_change = now;
    }

    refresh_display();
}

Paul provided a link to a tutorial on
Parallax
that suggests using the
Multiplex7Seg
Arduino library. That library is more general than the example code
above, as it does not make assumptions about the pins used. But the big
difference between the library and this code is in the way the timings
are managed:

The library is driven by the Timer 2 overflow interrupt. This should
provide a very steady timing, at the cost of having one timer
dedicated to this job.
The code above relies on the user calling refresh_display() often
enough. It doesn't require dedicated hardware resources, but it
doesn't play well with programs that take too long to loop(): it
won't like you calling delay().


Using an ESP8266 with an Arduino Uno - can't get AT command to work I am trying to connect an ESP8266 to my Arduino Uno.

Connections:

RX -> RX
TX -> TX
CH_PD -> 3.3v (Arduino 5v using voltage regulator)
VCC -> 3.3v
GND -> GND

I am running the RX and TX pins through a logic converter, dropping those down to 3.3v. Also, I have read that normally RX goes to TX and vice versa, but since I am trying to communicate with the chip using my computer (not the arduino) it needs to be the other way around.

I can't get the AT command to work on any baud rate. I was paying attention mostly to 9600, 115200, and 57600...I checked some others but it seemed like from reading these are the most common.

I used a multimeter to check the voltage of the RX/TX pins and after the logic converter my meter says it is outputting 3.2 volts (is this two low for serial to work?) Is their some +/- in the reading and it is actually 3.3v?

How do I go about troubleshooting this? Is it possible the AT firmware isn't loaded onto my chip? (I purchased it new, and recently).

UPDATE:

I'm reading about my logic level converter here, and I'm wondering if I have it setup right. My converter is labeled with HV -> HV4 and LV -> LV4 (you can see in the below picture). I'm wondering about where it says:

The middle section of the board is where the reference supply for your high and low voltages should go. Supplying voltage to all four of these pins is required. If you’re converting 3.3V to 5V (and vice-versa), for example, you’d run 5V into the “HV” side, and 3.3V into the “LV” input. Make sure each is grounded too!

So I need to provide power ("reference" power)? Some diagrams I have seen do this but I wasn't sure why:

UPDATE

I provided the reference supply and it up'd my voltage reading from 3.2 to 3.27 (I can assume it has enough voltage now?). I still can't connect with AT - on one of the baud rates I was getting stuff like !? as output.

UPDATE

I changed what pins were being used by RX/TX on my logic level converter, and now when I type AT on baud 115200, it outputs AT. Below is what it looks like for this configuration:

Do the soldered connections look good on the logic level converter?

After writing such a long question, hopefully this is useful to someone else: After changing the logic converter channels (not sure why the first two weren't working) I was receiving AT as output - the only thing I needed to do after that was change No line ending to Both NL & CR and I am receiving AT OK now.


How can I control blinking of LED while in timer function? When I am in the 30-second standby function, I want to turn the LED on and off at 5-second intervals.
How can I do what I want using the read_counter() function?
The problem here is that I am already in the timer function with the read_counter() function.
void wait_function() {
  timer_init();
  while(read_counter()<30000) { //30 second wait
    // A LED blinking at 1 second intervals ???
  }
}

Note: The read_counter() function increases every 1 millisecond with ISR COMPA vector. I tried many times and couldn't find a stable solution. Example:
if (read_counter() % 1000) PORTB^=(1<<LED);
Update: My new code :
while((TIFR1 & (1 << OCF1A))==0) //4secondIf I do this cycle 8 times, it
                                 //makes 32 seconds.
            {
                if(TCNT1%15624==0) //per 15624=1 second,
                PORTA^=(1<<0);
                 //led_blink_1s
            }

But,it doesn't work.Should I use util delay function?

Your waiting loop runs much faster than once per millisecond, and even faster per second. So to get just one "event" per second, you need to detect the change of the second.
void wait_function() {
  timer_init();
  for (int second = 0; second < 30; ++second) { // 30 second wait
    // Wait for the next second
    int old_second = read_counter() / 1000;
    int new_second;
    do {
      new_second = read_counter() / 1000;
    } while (new_second == old_second);

    // A LED blinking at 1 second intervals
    PORTB ^= 1 << LED;
  }
}

However, you may think about refactoring your timer. You can put the division in the ISR, and then set a flag if a second has past. In your waiting loop you could wait for the flag, reset it, and toggle the LED.
EDIT:
If you have your (pseudo) code like this:
while (!timed_out) {
    if (timer % ticks_per_second == 0) {
        do_something();
    }
}

you will have the following erroneous behavior, presumed that the loop runs 1 million times per second and the timer increments 20000 times per second.

The timer starts at 1000, for example, and has just incremented.
The loop runs for 50 times until the timer increments to 1001.
This happens repeatedly until the timer gets 20000, which will be after (20000 - 1001) * 50 = 949950 loops.
Now the loop will run for 50 times, while the timer is still at 20000.
The condition is true on each repetition, so do_something() will be executed 50 times in a row.
Next, the timer increments to 20001, and the condition becomes false.

This is exactly what you observe: If the condition of the if becomes true, its statement will be executed repeatedly.
Because the relation between the loop's repetition frequency and the timer's frequency is not the presumed value (but similar) and even depends on the instructions executed, the state of the output is subjectively random. If the XOR instruction is executed an even number, the LED does not change, and if it is executed an odd number, the LED changes.


Help with arduino code Thank you for seeing my post.

I am trying to write a code that lets "A" displayed on row 1 and row 0 alternately on the LCD. starting from (0,1) then (1,0)  then (2,1), then (3,0) etc..
when it reaches the last point is becomes "B" and bouncing back the other way until reaching the starting point when it becomes "A" again and repeat again..

I wrote this code but I got stuck at the end, I don't know how to bounce it back:

// include the library code:
#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);   // initialize the library with the numbers of the interface pins

int x = 0;
int y = 1;

void setup()
{
    lcd.begin(16, 2);
    lcd.clear();
}

void loop()
{
    {
        {
            while (x < 15)
            {
                lcd.setCursor(x, y);
                lcd.print("A");
                delay(250);

                lcd.clear();
                x = x + 1;
                lcd.setCursor(x, y - 1);
                lcd.print("A");
                delay(250);

                lcd.clear();
                x + x++;
            }
        }
        {
            while (x = 15)
                lcd.setCursor(15, 0);
            lcd.print("B");
            delay(2000);
            x--;
        }
    }
}

To me it seems, as if you have no knowledge about C/C++. ( I might be wrong. ;-) )

If you plan to do more programming projects, I advice you to learn the basics of this programming language before proceed with the projects. It would be hard thinking about an algorithm, if you don't know the tools to implement it.

In case you just need this once for a (let's say arts project [or homework ;-)] ), I add some example code. At the moment I have no chance to test the code. So it's blind written, and there might be typos. In about 8 hours I will have access to a test setup then I'll correct it if necessary.

#include <LiquidCrystal.h>

// Here you setup your LCD display
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

// you initialize the position where the next character
// will be displayed (0,1) (x,y)
int x = 0;
int y = 1;
// setup is only done once
void setup()
{
    // initialize the lcd lib to be used with a 16x2 LCD
    lcd.begin(16, 2);
    // erase all character from the display
    lcd.clear();
}

// the loop is executed again and again and ...
void loop()
{
    // move forward
    // as long as the position is less than 15
    // you allow x = 0, 1, 2, ... ,15 because
    // you increase two times in each loop step
    while (x < 15)
    {
        lcd.clear( );

        lcd.setCursor( x, y );
        lcd.print( "A" );
        delay( 250 );

        // step to the next position
        x = x + 1;
        // toggle y
        y = toggle( y );

        lcd.clear();
        lcd.setCursor( x, y );
        lcd.print( "A" );
        delay( 250 );

        // step to the next position
        x = x + 1;
        // toggle y
        y = toggle( y );
    }

    // now move backward
    // x is still 15 and you want to go backwards until x == 0
    while ( x > 0 )
    {
        lcd.clear( );

        lcd.setCursor( x, y );
        lcd.print( "B" );
        delay( 250 );

        // step to the next position
        x = x - 1;
        // toggle y
        y = toggle( y );

        lcd.clear( );
        lcd.setCursor( x, y );
        lcd.print( "B" );
        delay( 250 );

        // step to the next position
        x = x - 1;
        // toggle y
        y = toggle( y);
    }
}

// this is a subroutine that toggles y = 0 <-> 1
int toggle( int yval )
{
   // I use a ternary operator
   // in case y == 1, I return 0 and a 1 otherwise
   return ( yval == 1) ? 0 : 1;
}


How to run functions concurrently I'm building a scale which reads a value (from a load cell) and outputs it on a LED screen.

There is a function for the scale, read which will read the value from the scale.
However this is not instantaneous - it uses the yield function to wait until the scale is ready.

The LED screen has a function, display which will display an integer on the screen with no delay. However, this lasts barely a fraction of a second, so it must be repeatedly called.

These functions as is are called one after another inside loop(), but it causes only a quick flash of the LED screen followed by a half second of reading.

How would I allow the LED screen to keep displaying a value while the scale reads? I know there's BlinkWithoutDelay - but I'm not using specific times. There is no instance of the function delay anywhere in the program. I also am not going to edit the library which reads the load cell.

There is only one execution unit in this MCU so you can not truly run multiple tasks concurrently.

However, you can achieve the appearance of concurrency by running a higher priority task through an interrupt. For example, you cannot afford to have flickering disspplay. So set up a timer that invokees the display routine periodically. If you set the timer interrupt sufficiently small (over 25hz for example), the display will not flicker.

Your other routines can be run in other isr or in the main loop so they are interrupted by the display routine periodically. In a way that's fully transparent to you.


Need help shrinking a code I'am new to Arduino and c++

i get his code from the INTERNET

void setup() {
    Serial.begin(57600);
    pinMode(13, OUTPUT);
}
int f = 0, pos;
void loop() {
    boolean has_request = false;
    String in = "";
    if (Serial.available()) {
        in = "";
        while (true) {  // should add time out here
            while (Serial.available() == false) {}
            in += (char)(Serial.read());
            if (in.endsWith("\r\n\r\n")) {
                has_request = true;  break;
            }
        }
    }
    if (has_request) {
        int i1 = in.indexOf("GET /blink?f="), i2;
        if (i1 != -1) {
            i2 = in.indexOf(" ", i1+13);
            f = in.substring(i1+13, i2).toInt();
        }
        Serial.println("HTTP/1.1 200 OK\nContent-Type: text/html\nConnection: close");
        String sr = "<!DOCTYPE HTML>\n";
        sr += "<html>\n";
        sr += "LED frequency: ";
        sr += f;
        sr += "Hz.</html>";
        Serial.print("Content-Length: ");
        Serial.print(sr.length());
        Serial.print("\r\n\r\n");
        Serial.print(sr);
        has_request = false;
    }
    if (f>0) {
        static unsigned long t = millis();
        if (millis() > t + 1000/f) {
            digitalWrite(13, 1-digitalRead(13));
            t = millis();
        }
    }
}

see this link if you cant see the code formated here in the site

this code is used for the Arduino uno wifi shield
it is working perfectly except it is too complicated for me
while loop inside a while loop

and i don't want to do frequency i only need to send turn on or off
without any complexity

anyone could help me ?

There is only one "while loop inside a while loop" and that is hardly complex:

while (Serial.available() == false) {}

All that means is "Wait for something to become available on the serial".  That is ALL it does.

There is nothing even remotely complex there.  True, it may not be very well written (as is the case with lots of code on t'interwebs).  It's time to start learning how the code works so you can write your own.


Arduino String memory allocation When a String variable is declared and modified inside a function, where does it go? To the heap(as string declaration is a part of dynamic memory allocation) or to the stack(as it is a part of function)? And is the space regained after the function goes out of the scope?
For example

void loop()
{
  Serial.println(foo("def"));
  while(1);
}

String foo(String arg1)
{
 String test = "abc";
 test = test + arg1;
 return test;
}

So, in this case, the variable "test" is declared in stack or heap? And this space is regained at the end or not?

Modified:
What if inside loop variable is declared like below?

String foo_test = F("def");
Serial.println(foo(foo_test));

In this case what will be the status of variables?

This is an excellent question to illustrate the amount of string copying and heap operations (malloc/free) going on when using the Arduino String class.

void loop()
{
  Serial.println(foo("def"));
  while(1);
}

The compiler will generate loop() something like this:

void loop()
{
  // String literal is stored in program memory. Needs to be copied
  // to temporary variable. This is done before main() is called.
  static const char temp0[4] PROGMEM = "def";
  static const char temp1[4];
  copy_from_program_memory(temp1, temp0);

  // The parameter to the call to foo() is actually a temporary String
  // variable constructed from the string literal. Storage is allocated
  // on the heap and the assigned from the value of the string literal.
  String temp2;
  temp2.constructor(temp1);

  // The return value of the call to foo() is a String that is passed
  // to Serial.println(). This is also a temporary String variable.
  String temp3;
  temp3.constructor(foo(temp2));
  Serial.println(temp3);

  // The String class destructor has to be called for the temporary
  // String variable so that the string values on heap are deallocated.
  temp2.destructor();
  temp3.destructor();
}

Note that each call to the constructor involves allocating and copying data to the heap.

String foo(String arg1)
{
 String test = "abc";
 test = test + arg1;
 return test;
}

The function foo() needs to copy strings several times to perform the string concatenation. The operator+ will require an intermediate String copy.

Cheers!

PS: For more details please see the assembly listing below with the calls to String member functions. The compiler reduces inline member functions and reuses temporary local variables. Also the call to foo() is inlined. The member function reserve() is part of the constructor.

00000198 <main>:
 1de:   60 df           rcall   .-320       ; 0xa0 <String::reserve(unsigned int)>
 1fc:   50 d2           rcall   .+1184      ; 0x69e <strcpy>
 212:   46 df           rcall   .-372       ; 0xa0 <String::reserve(unsigned int)>
 230:   36 d2           rcall   .+1132      ; 0x69e <strcpy>
 248:   62 df           rcall   .-316       ; 0x10e <String::operator=(String const&)>
 26a:   1a df           rcall   .-460       ; 0xa0 <String::reserve(unsigned int)>
 27e:   0f d2           rcall   .+1054      ; 0x69e <strcpy>
 28e:   3f df           rcall   .-386       ; 0x10e <String::operator=(String const&)>
 294:   60 df           rcall   .-320       ; 0x156 <String::~String()>
 29a:   5d df           rcall   .-326       ; 0x156 <String::~String()>
 2a0:   5a df           rcall   .-332       ; 0x156 <String::~String()>

Bottom-line is that the String class uses a lot of instruction cycles and memory, and there is a potential risk of heap fragmentation and allocation failure.


Clearing arduino serial buffer How to clear the serial buffer of arduino uno?
This is my code to on and off the LED using sms from mobile using gsm module

#include <SoftwareSerial.h>
int Led=7;

SoftwareSerial mySerial(9, 10);

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

void loop()
{
  if (mySerial.available()>0)
  {

  }
   switch(mySerial.read())
  {
    case 'a':
           digitalWrite(Led,HIGH);
           delay(10000);
           digitalWrite(Led,LOW);
           delay(100);
           break;

    case 'b' :
           digitalWrite(Led,LOW);
           break;

  }}

problem is whenever i on the module or the connection is restablished it automatically gets even without an sms.I need it to be fully in my control so i need to clear the serial buffer.

If you are receiving unsolicited message (reading junk) then you could extend the bit pattern you are expecting so that there is almost no possibility of you accidentally receiving it.

Rather than 'a' and 'b' as triggers user LED="0" and LED="1".  Doing this makes reading the data much harder, because what you are looking for may start on character 4 of the string you read.  This is what I think you will need to do.

Read each character in turn and store them in a buffer until you have 7.
Is the first character an L.
If it isn't then delete the first character, shuffle the buffer left
one place and load in the next character before returning to step 1.
If it was, check the next character matches the expected.
If it doesn't match delete all character to the left and this one and return to step one.
If you have a matching token then parse it (get the 1 or 0) and do the action.


I2C begginer with I/O expander with mega328p C code I've just started with the I2C protocol. I read about it in the datasheet, other documents, blogs and videos.

So, I started to develop my code and I think I did my first success, I succeeded to send start and check TWST for sending start signal.

I get started OK, but I can't proceed to send data. What I'm missing? I'm thinking I didn't send the correct address.

void I2C_init(void);
void I2C_start(void);
void I2C_stop(void);
void I2C_tx(uint8_t data);
void I2C_TWSR_Check(void);

void setup() {
  Serial.begin(9600);
  I2C_init();
  //  I2C_TWSR_Check();
  I2C_start();
  I2C_TWSR_Check();
  I2C_tx(0x40);           // sending the address
  I2C_TWSR_Check();       // waiting for response
}

void loop() {
  uint8_t i;
  // simple loop to blink an LED on the I/O expander pin
  for (i=0;i<5;i++) {
    I2C_tx(0xff);
    I2C_TWSR_Check();
    _delay_ms(500);
    I2C_tx(0x00);
    I2C_TWSR_Check();
    _delay_ms(500);
  }
}

void I2C_init(void) {
  //set SCL to 100kHz
  TWSR = 0x00;
  TWBR = 0x48;
  //enable TWI
  TWCR = (1<<TWEN);
}

void I2C_start(void) {
  TWCR = (1<<TWINT)|(1<<TWSTA)|(1<<TWEN);
  while (!(TWCR & (1<<TWINT)));
}

void I2C_stop(void) {
  TWCR = (1<<TWINT)|(1<<TWSTO)|(1<<TWEN);
}

void I2C_tx(uint8_t u8data) {
  TWDR = u8data;
  while (!(TWCR & (1<<TWINT)));
}

void I2C_TWSR_Check(void) {
  uint8_t Status;
  Status = TWSR & 0xF8;
  switch(Status) {
    case 0x08: // start OK
    Serial.println("Start is OK");
     break;
    case 0x10: // Re start
    Serial.println("Re start");
     break;
    case 0x18: // SLA+W OK ACK
    Serial.println("SLA+W OK ACK");
     break;
    case 0x20: // SLA+W no ACK
    Serial.println("SLA+W no ACK");
     break;
    case 0x28: // data OK ACK
    Serial.println("data OK ACK");
     break;
    case 0x30: // data OK no ACK
    Serial.println("data OK no ACK");
     break;
    case 0x38: // arbitration lost in SLA+W or data TX
    Serial.println("arbitration lost in SLA+W or data TX");
     break;
     default:
     Serial.println("Error");
    break;
  }
}

OK the answer is that I didn't send the correct address!

Because if the I2C starting command with the slave is successful, then you should get successful sending ACK according reading the value of transmission status from the status register TWSR and ANDing this value with 0xF8. Then by reading the datasheet you know the value of transmission status. I developed a function to determine the status of transmission with Arduino Serial library which is I2C_TWSR_Check();.

I did this code for Master transmitter and receiver only.

So the trick is that you have to fix the address according to the AVR's TW address command format, which is the first bit is for read/write command and the remaining 7-bits are for the address, so you have to shift the real address which I got by "I2C address scanner" I got from one of AVRfreaks members.

For example, if the address is 0x20, then after shifting it 1-bit to the left, the new address is 0x40 for write operation and 0x41 for read operation.

void I2C_init(void);
void I2C_start(uint8_t address);
void I2C_stop(void);
void I2C_tx(uint8_t data);
uint8_t I2C_rx(void);
void I2C_TWSR_Check(void);

uint8_t bitmask;

/////////// I2C modules addresses ////////////
// 8-bit I/O expander 0x20
#define IOEXP_WR  0x40    // I/O 8-bits expander address
#define IOEXP_RD  0x41

// LCD1602 adapter
#define LCD1602_WR  0x4E  // LCD1602 I2C adapter address
#define LCD1602_RD  0x4F

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

void loop() {

  I2C_start(LCD1602_WR);
  I2C_TWSR_Check();
  I2C_tx(0xff);
  I2C_TWSR_Check();
  I2C_stop();
  _delay_ms(500);

  I2C_start(LCD1602_WR);
  I2C_tx(0x00);
  I2C_stop();
  _delay_ms(500);
}

void I2C_init(void)
{
  //set SCL to 100kHz
  TWSR = 0x00;
  TWBR = 0x48;
  //enable TWI
  TWCR = (1<<TWEN);
}

void I2C_start(uint8_t address)
{
  TWCR = (1<<TWINT)|(1<<TWSTA)|(1<<TWEN);
  while (!(TWCR & (1<<TWINT)));
  //I2C_TWSR_Check();
  TWDR = address;
  TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);
  while (!(TWCR & (1<<TWINT)));
  //I2C_TWSR_Check();
}

void I2C_stop(void)
{
  TWCR = (1<<TWINT)|(1<<TWSTO)|(1<<TWEN);
}

void I2C_tx(uint8_t data)
{
  TWDR = data;
  TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);
  while (!(TWCR & (1<<TWINT)));
  //I2C_TWSR_Check();
}

uint8_t I2C_rx(void)
{
  TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);
  while (!(TWCR & (1<<TWINT)));
  return TWDR;
}

void I2C_TWSR_Check(void)
{
  uint8_t Status;
  Status = TWSR & 0xF8;
  switch(Status)
  {
    /////////////// MASTER TRANSMITTER //////////////
    case 0x08:
    Serial.println("Start is OK");
     break;
    case 0x10:
    Serial.println("Re start");
     break;
    case 0x18:
    Serial.println("SLA+W OK ACK");
     break;
    case 0x20:
    Serial.println("SLA+W no ACK");
     break;
    case 0x28:
    Serial.println("data TX OK ACK");
     break;
    case 0x30:
    Serial.println("data TX OK no ACK");
     break;
    case 0x38:        // arbitration lost in SLA+W or data TX
    Serial.println("arbitration lost in SLA+W or data TX");
     break;

    /////////////// MASTER RECEIVER //////////////
    case 0x40:
    Serial.println("SLA+R OK ACK");
     break;
    case 0x48:
    Serial.println("SLA+R OK NO ACK");
     break;
    case 0x50:
    Serial.println("data RX OK ACK");
     break;
    case 0x58:
    Serial.println("data RX OK NO ACK");
     break;

     default:
     Serial.println("Error");
    break;
  }
}


Infrared distance sensor picks up distances that are not there I have connected an Infrared sensor to my Arduino Uno and I've set this code up to blink whenever a distance of less than 50 cm is picked up. If there is an object less than 50 cm away, it does pick it up. However, with nothing in front of it it still blinks at random intervals. The sensor is new. Where do you think the problem is?

int sensorPin = 0;
int ledPin = 13;

void setup() {
  pinMode(ledPin, OUTPUT);
}

void loop() {
  float distance = 12343.85 * pow(analogRead(sensorPin),-1.15);
  if(distance < 50){
    digitalWrite(ledPin, HIGH);
    delay(1000);
    digitalWrite(ledPin, LOW);
  }
  delay(50);
}

I see one problem with your code and how it relates to this device.

The output from the sensor is not the monotomic function you describe; not over its entire range.  Your conversion function describes only a section of the response.  The device is only intended to be used when an object is in range 10-80 cm.

You should check that the voltage at the analog input is valid before performing the math:

int v;

v = analogRead(sensorPin);
// sensor is valid in range 0.4 to 2.5 V
if((82 < v) && (v < 512)) {
  // voltage is in usable range, can convert
  distance = 12343.85 * pow(v,-1.15);
  if(distance < 50) {
    digitalWrite(ledPin, HIGH);
    delay(1000);
    digitalWrite(ledPin, LOW);
  }
}
else {
  // no valid reading - probably just skip and try again on next loop
}

With that the false triggers may be eliminated.


Can I use the setup() function inside the loop() function In the normal case the setup() function will be run once automatically and and then the loop() function will run many times.

I want to initialize several modules in the setup() function and then in the loop() I want to read values from them periodically. But if the period between usage is long I want to power off the modules. After defined time the modules will be powered on again and need to be initialized. Can I use the already existing setup() function inside the loop() to initialize the modules or I have to write another similar function? Is there any other better way to power off/on sensors and modules during the execution of code.

It could be possible, since it is going simply to call the same function BUT it is really a very bad design*.

Usually the main purpose for a microcontroller is just sitting there and run a procedure or main function repeatedly until the end of the world. And during one loop just to check if some conditions are met.

You should never stop or influence your loop() function and never mess up the default design of the arduino.

In you case (but it depends on your code and your application), you just want to run the loop() once all sensors have been already started (in the setup() function).

In your run, you check periodically the sensor and start a timer (better if interrupted). If an amount of time has expired and the sensor should be turned off, then the timer will call another function, which has the only target to switch sensors off.

The loop() runs again and again and if the original condition is met, then you can start your sensors again.

To save up time and code typing, I suggest you write only ONE function for switching on the sensors and call this function in setup() and in your loop(), something like this:

void startSensors();
void stopSensors();

void setup() {
  startSensors();  // I start all sensors here
}

void loop() {
  if( condition?!?! )
     {
       ...
       stopSensors();
       ...
     } else {
       ...
       startSensors();  // I call the same function here
       ...
     }
}

*: for istance you define in your setup() the connection through serial port. This means that your object "serial port" is going to be recreated each time you call setup() whit undefeined behavior in case it is outputting datas or has same data in the FIFO Buffer. Simply...setup() has that name because needs to setup things once. Everything that must be done more than once, then must be called from run() too.


Check to see that String only contains .csv style numbers I'm looking to determine if an Arduino String contains any other character than those that would be in the [number],[number]'\r''\n'where [number] could be positive or negative.

I know I can run a for down the entire string and use if(isDigit([char]) || isWhitespace([char])||[char]=='-') however, I imagine there's a better way to do this.

Could I (for example) convert the String to an array of values and search the array for any value that doesn't correspond to the characters I'm looking for? Or is there a better way to check this out?

There is a better way, which is called regular expressions (or regexp). However, afaik these are not supported by Arduino by default.

However, I'm sure you can find some 'generic C++' class that can handle them.

For that, it's best to check on StackOverflow.com probably.

After a short check, on the Arduino forum there is a library available for regexp:

library

It is created by Nick Gammon, so all credits are for him.


I just want to control a 48 volt and 30 amp current with pwm singnal...i don't nkow what components is needed for this I just want to adjust voltage of a dc dc converter output with pwm signal...i used MOSFET but i get some heating effect..please tell me what model of MOSFET or ijbt or anything else which components is more reliable...

simulate this circuit – Schematic created using CircuitLab
There are not many P-Channel Mosfets with high current ratings. The circuit is an example of a buck with a high side N-Channel. If you want to use an N-Channel as the high side switch, you use and isolated DC-DC and isolated gate driver. The negative output of the DC-DC regulator gets referenced to the source of the N-Channel. Then the isolated driver's output signal is 15v referenced to the source. I would also recommend using a snubber because you're going to likely see voltage spikes across your mosfet. A 10ohm resistor and 3300pF would probably be a good start. You may need to go to a 200v or 250V mosfet if the spikes are bad enough.


Very strange power supply problem So, I've put together my Christmas tree lights - a string of WS2811s driven by my Uno board. They are 12 volt WS2811s, so I have rigged a 12 volt supply to them and just using the Uno for the data channel, powered, initially by the USB port of the PC. So far, so good.

Then I take the whole arrangement to the tree and try to power the Uno from a USB charger - but that's where it all goes wrong! The LEDS start to flash madly, nothing like the pattern that I've programmed.

I've tried various USB chargers and various USB cables to no avail, I've tried powering with 6 volts to the DC in socket - same thing. When I go back to the PC and pick up the Uno power from the USB cable, all is good! I have no idea what can be causing this, please help!

[Turning my comment and other peoples replies into an answer to make it easier to read]

You are using two different power supplies? (PC + 12V or USB Charger + 12V) Have you connected the grounds from the two power supplies?

I have a limited understanding of why, but I know that unless the two power supplies have a common ground level the values for 0V and 5V may not be the same across the two feeds and you get odd and unpredictable behaviour.

Gerban explained that the reason it works on your PC is that most PC Power supplies reference Gnd from the Earth.  If you 12V supply is an ex-PC PSU, or similar, that will be doing the same which is why that setup works, they share a common ground via the mains earth.  The 5V phone charge probably has a plastic earth pin, which means it doesn't do this and therefore the Gnds are not tied to each other.

Majenko's blog will provide a more detailed, less hand wavey explanation:
https://hackingmajenkoblog.wordpress.com/2016/12/06/the-importance-of-sharing-grounds/


Arduino Wire.h send double to lcd I'd like the double number 200.00 shown as 200.00 on my LCD screen.

For instance, when I pass just a number (int) like 40 to the LCD, it uses it as an ASCII code to show a character on the display.

Now I want to send a double to it and it should be displayed as a double.

#include <Wire.h>

void setup() {
   Wire.begin(0x63);
}

double f;
void loop() {

  f = 200.00;

  Wire.beginTransmission(0x63);
  Wire.write(byte(0x00));
  Wire.write(4); //HIDE CURSOR
  Wire.write(12); //CLEAR SCREEN
  Wire.write(13); //CURSOR 2nd LINE
  Wire.write("Frequenz: ");
  Wire.write(f); //<- How to do this?
  Wire.write("Hz");
  Wire.endTransmission();
}

Use Wire.print(), instead of Wire.write() which is intended only to output single bytes or byte arrays.


Why should I connect the l289n motor driver wires to specific arduino pins only? So, I am new with arduino and am to build a robot using motors, for that I have bought l298n H bridge motor driver. I have watched various site and videos ,to make sure not to make a mistake but, in every video and sites
I have found their connecting the motor direction controller to

IN1 -> Arduino Pin 8 (digital) and IN2 -> Arduino Pin 7 (digital)
Till then it was fine ... Now the fishy thing for me is
IN3 -> Arduino Pin 5 (PWM) and IN4 -> Arduino Pin 4 (Digital)
Why connect to a Digital and a PWM?
For E1 and E2 I am sure that the wires should be connected to the PWM (~) pins for arduino, to control speed of the motor..
But, Should not I be able to connect IN3 and IN4 both to rest of the digital pins 12, 13 or 2,4 Just Like IN1 and IN2 is connected to 7 and 8.
But the IN3 and IN4 is connected to a PWM and a Digital pin.
Conclusion,
So can I use all the unused non PWM digital pins to connect the motor direction control?
Thanks for your precious time..!

Pwm is just a digital out with extra fancy on off controls.  You can use any digital out if you do not need those extra features.
To just signal a single H bridge (1 motor of your l289n) for forward, reverse, stop, one only needs two digital outs.
I recommend you get the hang of your h bridge first - signaling it on a bread board with vcc (usually 5v but can be 3.3) and ground rather than the arduino.  Then once you understand the motor directions that result from your wiring, write the code accordingly.  This tends to result in:

fewer fried arduinos
code with functions and signals named after their intent (rather than having to mix forward and reverse)


Motor not working when connected to motor driver shield? My code is getting uploaded to arduino without problem but still my motor is not moving when i connect it to the motor driver shield. I am supplying 6V battery to the shield which is connected to dc motor at M2

What could be the problem?

Code:-

#include <AFMotor.h> //import your motor shield library

AF_DCMotor motor2(2,MOTOR12_2KHZ); // set up motors.
AF_DCMotor motor3(1, MOTOR34_1KHZ);

void setup() {
  Serial.begin(9600); // begin serial communitication
  Serial.println("Motor test!");
  motor2.setSpeed(105); //set the speed of the motors, between 0-255
  motor3.setSpeed(105);
}

void loop() {
   motor2.run(FORWARD);
   motor3.run(FORWARD);
  }

I cannot tell all of your connections from the photo, but I'm guessing you're supplying power to the Arduino through its power connector and also to the motors, both from the battery. The power connector on the Arduino is specified for 7-12v because the kind of voltage regulator it has needs that 2v difference to operate properly. You're kind of at the edge by supplying 6v, and when the motors come on, their current draw will cause the 6v battery voltage to drop somewhat. It probably drops below the regulator's ability to supply 5v from it, shutting down the Arduino.

Adding one more cell to your battery will give you 7.5v (5x1.5v) and will may be enough to run the Arduino and the motors. Two more cells would work even better. (Don't make the mistake of trying the small 9v batteries with snap-clips on top - their utterly incapable of supply the current your motors need).


Arduino UNO reset using SIM800L I'm using the SIM800L module but i've problems. I'm triying to connect it to the Elegoo UNO i've, but it restarts at all times. Also the led of signal strengh blink every second, so i dont get signal.

I also upload a video to Youtube to explain the problem, this is the link.

Thanks in advance!

When the reset pin of Uno is connected to ground, the Uno resets. That is what the reset button does.

You connected the reset pin of Uno to other device's reset pin. If the reset pin of the other device grounds the reset pin of Uno (grounds or has lower then required voltage), then Uno resets.

The reset pin of a peripheral device is intended to reinitialize the device by program running in microcontroler by setting a connected GPIO pin to required state.

If you have a library for the device, that library will take care of the GPIO pin controlling the reset of the device.

If you plan to use the device without library, then you should take care of the reset pin in your sketch. Setting the selected pin to OUTPUT and initializing it to required state.

The usual required state for reset is LOW so the output must be HIGH for the device to work.

Some tutorials and libraries require connecting the reset pin of gsm800l to a selected Uno GPIO pin with a transistor, and then reset is HIGH and LOW is for normal operation.


about receiving float on matlab from ATmega32 Avr ****i am using ATmega32 to send float and want to receive it on matlab,i send 4.85 from ATmega32 but on matlab i receive 4.260233679216239e-31...can any one help me..thanks in advance**
**

    //Atmel studio code++++code for sending float from Atmega32
    union abc{ float fo; unsigned long lo; };
 union abc data;
int main(void)
 { usart_init();
 data.fo=4.85;
 while(1) {
for(int i=0; i<=24; i+=8)
{
    uart_send(data.lo>>i); }}}

 //Matlab code for receiving float
s=serial('COM1','BaudRate',9600);
fopen(s);
out=fread(s,1,'single');
 fclose(s);

i found the solution for this problem, i set a header before sending the data from ATmega32,and on Matlab i check the frame ,if it received correctly,i receive the data

//ATmega32 code
    float x =215.5;
    unsigned char *ptrx;
    int main(void)
    {   usart_init();
        //data.fo=12.85;

        ptrx=( unsigned char *) &x;
          while(1)
       {
        uart_send(0xAA);//equals to 170
        for(int i=0;i<4;i++){
        uart_send(*(ptrx+i));}

        x++;}}
    //on Matlab
    s=serial('COM1','BaudRate',9600);
    fopen(s);
     i=1;
    while i<1000
        header =fread(s,1,'uint8');

        if header==170//equal to 0xAA

     out=fread(s,1,'float');
    data(i)=out;

     i=i+1;
        end
     end
    fclose(s);


The difference between "time_t" and "DateTime" I've run into an issue trying to combine 2 different Arduino timer projects I've found online.

For both projects I'm using a DS3231 RTC, but have been able use the DS1307 library just fine in my code.

The first set of code I picked up started with:

#include <DS1307RTC.h>

The second set of code I tried to combine did not have this 'include', but instead used

RTC_DS1307 RTC;

as found here:

https://learn.adafruit.com/ds1307-real-time-clock-breakout-board-kit/understanding-the-code

As a novice coder, I'm not really sure what the difference between the above two ways to call this library. But I do know the first way using "include", if I want to access the current time on the RTC I use

RTC.get();

as opposed to the second method which requires:

RTC.now();

And while it was easy to find documentation to sync the RTC to computer time over the USB cable using this handy bit of code:

// Notify if the RTC isn't running
    if (! RTC.isrunning()) {
    Serial.println("RTC is NOT running");
  }

   // Get time from RTC
  DateTime current = RTC.get();
  DateTime compiled = DateTime(__DATE__, __TIME__);
  if (current.unixtime() < compiled.unixtime()) { //CHECKS AGAINST COMPUTERTIME
    Serial.println("RTC is older than compile time! Updating");
    RTC.adjust(DateTime(__DATE__, __TIME__));  //UPDATES FROM COMPUTER IF OLD TIME IS OFF
  }

I can find no easy alternative using "#include DS1307RTC"

I first thought that the difference between RTC.now() and RTC.get() was just a matter of word substitution. But later on when I want to use a "time_t" call after initializing with "RTC_DS1307 RTC;"

 time_t timeNOW = RTC.now();

I get the error "cannot convert 'DateTime' to 'time_t {aka long unsigned int}' in initialization"

So I'm assuming one method uses "DateTime" and one method uses "time_t". But I'm not sure if this is the case, and if so, how to convert a "DateTime" value to a "time_t" value.

I have two goals in writing this post.

1- Can someone please explain to me the difference between "#include DS1307RTC.h" and "RTC_DS1307 RTC;" and how it impacts my code.

2- I'd like to stick with using ""RTC_DS1307 RTC;", only because it seems easy to sync my RTC to my computer. But if I do, I get the above error. So can someone please tell me how to convert a "RTC now()" call to a "time_t" value? Or is the issue more complicated than just a mere conversion between data types?

A DateTime is a full class with lots of methods to it - a time_t is just an unsigned long.

time_t is used to store the number of seconds since the epoch (normally 01/01/1970)

The Arduino Time library returns a time_t to the now() function - but RTCLib return s a DateTime object.

The DateTime object, though, has a unixtime() method which will return a time_t representation of the time stored in the DateTime object.

So you can do:

DateTime dt = RTC.now();
time_t time = dt.unixtime();


Serial.print() is slower than it should be I'm trying to use Arduino as a DAQ but the Serial.print() is not working as fast as I expected. How many bits are sent if you are using a int, because if I use a uint8_t, it's taking the same amount of time? How I could improve the speed of the Serial.print()? I'm already working at 115200 baud.

I need a sample rate of 6 kHz

OK, so that means you need to sample and send every 1/6000 seconds (167 µs).

I have a lengthy discussion about the ADC hardware. Amongst other things is a table of conversion times for the different ADC prescalers, assuming a 16 MHz clock:

Prescaler
    2    * 13 * 1/16E6  = 0.000001625 (  1.625 µs)
    4    * 13 * 1/16E6  = 0.00000325  (  3.25  µs)
    8    * 13 * 1/16E6  = 0.0000065   (  6.5   µs)
   16    * 13 * 1/16E6  = 0.000013    ( 13     µs)
   32    * 13 * 1/16E6  = 0.000026    ( 26     µs)
   64    * 13 * 1/16E6  = 0.000052    ( 52     µs)
  128    * 13 * 1/16E6  = 0.000104    (104     µs)

If you go for maximum resolution (10 bits) you need a prescaler of 128, which takes 104 µs. The number of conversions you can do a second (taking the inverse of the above) is:

Prescaler  Conversions/sec
  2           615,385
  4           307,692
  8           153,846
 16            76,923
 32            38,462
 64            19,231
128             9,615

You also need to take into account the transmission time. At 115200 baud you can transmit one byte every 1/11520 seconds (86.8 µs) so therefore two bytes (16 bits) would take 173.6 µs.

If you sample then transmit you will therefore take, per sample:

104 + 174 = 278 µs

This is too slow if you want to achieve it inside 167 µs.

You can sample asynchronously (in the background) so you transmit one sample while taking the next one, but you are still limited by the transmission speed of serial, so it would still take 174 µs per sample.

In fact, fiddling with the prescaler isn't really the issue here because the serial transmission time is the limiting factor.

Forget about the ADC and how it works for the moment. At 115200 baud you can't transmit 2 x 6000 bytes per second. That is simply because the maximum is 11520 bytes per second.


How to send multi variable information over serial? I would like to send information between my Arduino and my computer. Is there a way to send multiple variables from one Arduino? If so, how would I go about separating the variables?

You have three options for what you want to achieve (if I understand it right):

Have a fixed length for each variable: If I know each number is going to be two digits, I can send "1234" and the other side can figure out the numbers are "12" and "34".
Have a delimiter character: Have a character that signals a new variable. For example: "213|1234" would translate into "213" and "1234". You could even use the newline character to signal a new line (with Serial.println();).
Do some sort of validation to separate the data: If sending a favorite number and favorite color, I can send "12RED345BLUE" and the other side it can find that it's "12" (both numbers), then "RED" (all letters), then "345" (three numbers), and finally "BLUE" (again, all letters).


making a LCD dice for catan when I go to upload the code, I get

 Arduino: 1.8.5 (Windows Store 1.8.10.0) (Windows 10), Board: "Arduino/Genuino Uno"
C:\Users\taran\Documents\Arduino\dice in progress\dice in progress1\diceinprogress\diceinprogress.ino:1:25: fatal error: C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt\hardware\arduino\avr\cores\arduino/"DFRkeypad.h": Invalid argument
#include <"DFRkeypad.h">
                     ^
compilation terminated.
exit status 1 Error compiling for board Arduino/Genuino Uno.

and the code is

#include <"DFRkeypad.h">
#include <LiquidCrystal.h>
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
const char* DFRkeypad::sKEY[]=                          { "---",       "Right",   "Up", "Down", "Left", "Select", "???" };
const int DFRkeypad::iARV_VALUES[DFRkeypad::eNUM_KEYS]= { 1023,        0,         143,  328,    504,     740,      -1   };
int btnSELECT;

void setup() {
  lcd.begin(16, 2);
  lcd.setCursor(1, 0);
  lcd.print("Roll the dice!");
}

void loop() {
while (btnSELECT == 0){

  delay (50);
  buttonState = analogRead(btnSELECT);
}

 case btnSELECT:
     {
     lcd.print("Rolling dice");
       diceOne = random(1, 7);
       diceTwo = random(1, 7);
     break;
    }
}

In C/C++ you either use the #include pre-processor statement in the form of

#include "someFile.h"

or

#include <someFile.h>

The form

#include <"someFile.h">

is not legal. You must correct it to one of the two forms above.

The difference between those forms is explained in https://stackoverflow.com/a/77092/5296568.


How to power Arduino externally for long term? For a robotic project, I need to keep an Arduino powered up for a long time in an outdoor environment. What can I use to power the board?
If battery is the only solution, can the device tell me remotely that battery is getting low?

It needs to be powered for at least few days ( at least). The unit monitors an outdoor sensor that is shaded from sun but still exposed to wind and moisture. The unit does not move.

There are several options for Arduino power in an external environment.

Wall wart: Connects to a wall socket, provides a great long-term source of power
Rechargeable battery: Doesn't last long, but they can be recharged and monitored with a low cost board
Alkaline Battery: Last longer, there are some monitoring systems available.
Solar: Only works when the sun is out, unless you combine it with a rechargable battery (example)
Nuclear power: NOT RECOMMENDED!!!


Is ATmega 328 on Arduino UNO already bootloaded? I've seen many tutorials on programming a ATmega 328 via Arduino. If i'm right, the atmega need to be bootloaded. I thought to remove the atmega present on the arduino board. But to bootloading atmega we need another atmega on the arduino board. I can't buy a new one. After bootloading we need only one IC. So, can I remove the atmega which  is present on the arduino and directly program it? Can I consider it as a bootloaded one?

In Arduino board, arduino controller means ATMEGA328P-PU already bootloaded. So, you can use directly. But if you buy only ATMEGA328P-PU chip or any other ATMEGA chip then you have to do bootloading for that.


Serial Communication - strtok() issue I'm working on UART communication between an ESP32 (sender) and ESP8266 NodeMCU board(receiver).

The host is sending out the following character string:

Serial.println("2753192144$1&");

The 2753192144 is the payload. The $1& is the trailer of the packet - $1 signifies a particular option for the receiver and & is the termination character to signify that the packet is complete.

On the receiver end - this is what I have:

#define MAX_REC_STR_SIZE 10
#define REC_TRAILER_SIZE 4 // $1& and string terminator
#define TRUE_TRAILER_SIZE 2 // option size really

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

void loop() {
    if(Serial.available()){
    char data [MAX_REC_STR_SIZE + TRUE_TRAILER_SIZE + 1];
    Serial.readBytesUntil('&', data, MAX_REC_STR_SIZE + REC_TRAILER_SIZE); // data does not contain termination &
    data[MAX_REC_STR_SIZE + TRUE_TRAILER_SIZE + 1] = 0; // adding null terminator

    // Tokenizing
    char *payload = strtok(data, "$"); // getting payload
    char opt = strtok(NULL, "$")[0]; // getting option - 1 in our sample

    // Print
    Serial.println(payload);
    Serial.println(opt);
  }
}

This code results in a stack exception error in the serial monitor. If I remove the last line which prints opt, the payload print works fine and I get 2753192144in the serial output.

I tested this exact code out in a standard C compiler, except instead of the serial read part - I defined a character array with 2753192144$1& and used printf instead of Serial.println. See the code below

#include <stdio.h>
#include <string.h>

int main()
{
    char data[] = "2753192144$1";

    char *payload = strtok(data, "$");
    char opt = strtok(NULL, "$")[0];
    printf("Payload is %s and opt is %c", payload, opt);

    return 0;
}

This code outputs

Payload is 2753192144 and opt is 1

This works fine. Any ideas why the Arduino sketch isn't working?

data[MAX_REC_STR_SIZE + TRUE_TRAILER_SIZE + 1] = 0; // adding null terminator

That line places a 0 in the byte following the array.

If you define an array of size [x] you have slices [0] to [x-1] available. If you try accessing [x] you will be altering other items on the stack after the array.

That's called a buffer overrun and is one of the most common causes of programs crashing.

If you want to put a 0 at the end of the array, you should use

data[MAX_REC_STR_SIZE + TRUE_TRAILER_SIZE] = 0; // adding null terminator

You should also check that the strtok() calls actually return a valid pointer. If the incoming string is not in the right format and strtok() can't split the string up, it will return NULL. If you then try and access that NULL pointer as if it were a valid array you will have a nasty crash.


Will Arduino Mega support stepper motor NEMA 24, NEMA 34 Will two stepper motor NEMA 24, 10 kg cm, 2. 8 amp, 24 vdc work at same time on Arduino Mega and when they stop stepper motor NEMA 34, 34 kg cm, 4amp, 24 VDC will work or not? This is my first project please help me to choose the controller.

I'm using 4x Nema 24s for a CNC project of mine.  They only need a couple of signals/pins each from the Arduino to work, the rest is up to the stepper controller board.

For my steppers, I'm using TB6600s, since I need ~3.5 amps per motor/channel.  There are others out there that'll work, but it's what I saw other people at my maker space using.

Nema34s would probably need higher rated amps, so that would determine what controller you need to use.

In fact, every motor is rated for different amps and voltages, so that will always determine what motor controller you use.  Since you need a higher voltage to run the motor controllers than the Arduino, using a separate stepping power supply is a requirement.

The Arduino gets hooked to the step/pulse and direction pins of the motor controller and the other pins on the motor controller go elsewhere.  The CNC motor controller shields you normally see are for lower amp controllers and do most of the pin connections for you.  With the higher amperage motors, you'll have to do this yourself.

When you determine what motor controller you are going to use, find a wiring diagram for it (and maybe a friend) to figure out how it should be wired.


Arduino GPS Simulator: SoftwareSerial Issues For my project, i need my Arduino Uno to simulate a GPS. To do this, I need to:

Generate a 5V Pulse once a second (no problem)
Send a $GPRMC NMEA sentence with the current time over RS-232 (i've got an RS-232 shield)

The GPRMC message i need to send is the following:

$GPRMC,075832.293,A,4042.695,N,07400.796,W,,,080120,000.0,W*63

Where the first part is the time, and needs to change.
I basically implemented it as:

// Setup
String prefix = "$GPRMC,";
String gprmc  = "075832.293";
String suffix = ",A,4042.695,N,07400.796,W,,,080120,000.0,W*63";
String all = prefix + gprmc + suffix;
char* buff = (char*) malloc(sizeof(char)*all.length()+1);

Then, in the loop-code i update the time and want to send the message:

//...inside the condition that gets executed once a second
gprmc = String(gprmc.toFloat()+1);
all = prefix+gprmc+suffix;
all.toCharArray(buff, all.length()+1);
mySerial.write(buff);

I'm using an RS-232 shield, which shows me when a message is being sent by blinking an LED.
However, is only seems to work, if i shorten the all string, i.e.:
Works:

all = prefix+gprmc;

Does not work:

all = prefix+gprmc+suffix;

Is it possible that the message is just too long to send? Is there a way I can fix this? Because it's crucial to send the whole message.

Note: I'm currently working on an Arduino Uno, but I'm switching to an arduino Leonardo today. I currently have low memory available (77% used). could this add to the problem?

Thank you so much for your help!! :)

First off, some comments about your code:

Never use String unless it is absolutely unavoidable
Unless you have a free() to balance your malloc() you will run out of memory almost immediately
There is never any need to concatenate strings to send through serial like that.

Instead of what you are currently doing, just scrap the String usage and your buf variable completely.  There is no need to concatenate things together - serial sends data one character at a time, so you're gaining nothing by concatenating and only causing yourself more problems.

How you should be doing it:

// The changing value as a float
float gprmc=75832.293;
// Print the prefix
mySerial.print(F("$GPRMC,"));
// Pad the value with zeroes
if (gprmc < 10) mySerial.print(F("0"));
if (gprmc < 100) mySerial.print(F("0"));
if (gprmc < 1000) mySerial.print(F("0"));
if (gprmc < 10000) mySerial.print(F("0"));
if (gprmc < 100000) mySerial.print(F("0"));
// Print the value with 3 decimal places
mySerial.print(gprmc, 3);
// Finally print the suffix
mySerial.println(F(",A,4042.695,N,07400.796,W,,,080120,000.0,W*63"));

Note the use of the F() macro to further reduce RAM usage by keeping the string constants in flash memory.


Will a .ino Arduino Sketch compile directly on GCC-AVR? Okay, we all have seen those questions all over the web such as Arduino v.s. C++, or other similar questions. And a vast majority of the answers do not even touch compilation differences other than through abstracted information.

My question aims to solve the actual differences (not preferences) in how a .ino file renamed to a .cpp file or other similar file extension for c++ would compile using GCC-AVR. I know that at a minimum you have to include the Arduino header file, but beyond that, what would cause a compilation error if compiling said .ino to .cpp file using, say, for instance GCC-AVR. For simplicity's sake, lets use the classic blink example to explain what the differences are. Or if you have a better code snippet to use, please by all means, include the snippet in your answer and explain the differences thoroughly.

Please no opinions as to which is a better way or tool to use.

FYI. I use Platformio for development and I notice a conversion process happening behind the scenes during compilation. I am tryng to understand what is actually happening there, so when I code in Arduino, I understand the "pure" C++ version as well.

Thanks for your thoughtful answers to my question in advance.

See my answer here: Classes and objects: how many and which file types do I actually need to use them? - specifically: How the IDE organizes things.

  I know that at a minimum you have to include the Arduino header file

Yes you would need to do that.

  but beyond that, what would cause a compilation error if compiling said .ino to .cpp file using, say, for instance GCC-AVR.

The IDE generates function prototypes for you. Code in a .ino file may or may not need this (it probably will unless the author is disciplined enough to code in the usual C++ way and do them themselves).

If the "sketch" contains other files (eg. other .ino, .c or .cpp files) then these would need to be incorporated in the compile process as I describe in my answer mentioned above.

Also you would need to (compile and) link in any libraries used by the sketch.

You haven't asked about the linking side of things, but naturally the various files, as compiled, need to be linked together, and then turned into a .elf and .hex file for uploading purposes. See below.

Example makefile

Based on the IDE output I made a simple makefile a while back:

#
# Simple Arduino Makefile
#
# Author: Nick Gammon
# Date: 18th March 2015

# where you installed the Arduino app
ARDUINO_DIR = C:/Documents and Settings/Nick/Desktop/arduino-1.0.6/

# various programs
CC = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-gcc"
CPP = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-g++"
AR = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-ar"
OBJ_COPY = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-objcopy"

MAIN_SKETCH = Blink.cpp

# compile flags for g++ and gcc

# may need to change these
F_CPU = 16000000
MCU = atmega328p

# compile flags
GENERAL_FLAGS = -c -g -Os -Wall -ffunction-sections -fdata-sections -mmcu=$(MCU) -DF_CPU=$(F_CPU)L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=106
CPP_FLAGS = $(GENERAL_FLAGS) -fno-exceptions
CC_FLAGS  = $(GENERAL_FLAGS)

# location of include files
INCLUDE_FILES = "-I$(ARDUINO_DIR)hardware/arduino/cores/arduino" "-I$(ARDUINO_DIR)hardware/arduino/variants/standard"

# library sources
LIBRARY_DIR = "$(ARDUINO_DIR)hardware/arduino/cores/arduino/"

build:

    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(MAIN_SKETCH) -o $(MAIN_SKETCH).o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/malloc.c -o malloc.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/realloc.c -o realloc.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WInterrupts.c -o WInterrupts.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring.c -o wiring.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_analog.c -o wiring_analog.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_digital.c -o wiring_digital.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_pulse.c -o wiring_pulse.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_shift.c -o wiring_shift.c.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)CDC.cpp -o CDC.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HardwareSerial.cpp -o HardwareSerial.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HID.cpp -o HID.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)IPAddress.cpp -o IPAddress.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)main.cpp -o main.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)new.cpp -o new.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Print.cpp -o Print.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Stream.cpp -o Stream.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Tone.cpp -o Tone.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)USBCore.cpp -o USBCore.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WMath.cpp -o WMath.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WString.cpp -o WString.cpp.o
    rm core.a
    $(AR) rcs core.a malloc.c.o
    $(AR) rcs core.a realloc.c.o
    $(AR) rcs core.a WInterrupts.c.o
    $(AR) rcs core.a wiring.c.o
    $(AR) rcs core.a wiring_analog.c.o
    $(AR) rcs core.a wiring_digital.c.o
    $(AR) rcs core.a wiring_pulse.c.o
    $(AR) rcs core.a wiring_shift.c.o
    $(AR) rcs core.a CDC.cpp.o
    $(AR) rcs core.a HardwareSerial.cpp.o
    $(AR) rcs core.a HID.cpp.o
    $(AR) rcs core.a IPAddress.cpp.o
    $(AR) rcs core.a main.cpp.o
    $(AR) rcs core.a new.cpp.o
    $(AR) rcs core.a Print.cpp.o
    $(AR) rcs core.a Stream.cpp.o
    $(AR) rcs core.a Tone.cpp.o
    $(AR) rcs core.a USBCore.cpp.o
    $(AR) rcs core.a WMath.cpp.o
    $(AR) rcs core.a WString.cpp.o
    $(CC) -Os -Wl,--gc-sections -mmcu=$(MCU) -o $(MAIN_SKETCH).elf $(MAIN_SKETCH).o core.a -lm
    $(OBJ_COPY) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $(MAIN_SKETCH).elf $(MAIN_SKETCH).eep
    $(OBJ_COPY) -O ihex -R .eeprom $(MAIN_SKETCH).elf $(MAIN_SKETCH).hex

In that particular case, the .ino file compiled without any problems after renaming it to Blink.cpp and adding this line:

#include <Arduino.h>


How would I go about powering addressable RGB LED light strip? [Arduino Nano] The addressable RGB LED I have is WS2812B. I plan on controlling the LEDs via an Arduino nano. I have a total of 188 LEDs to supply power to.

Would I require anything between the addressable RGB LED strip and the 12v power supply?

Would I require a 1000uF capacitor?

Would I require anything between the addressable RGB LED strip and the 12v power supply?

A suitable 5V regulator (assuming 5V LED strip)

  Would I require a 1000uF capacitor?

For what? A suitable 5V regulator won't need one. An unsuitable one would be improved by it, but still be unsuitable.


Why is my potentiometer giving strange reading? I have a 10kOhm linear Potentiometer. I connected it to analog 0, as in https://www.arduino.cc/en/Tutorial/Potentiometer.

The analogRead() gives a value between 0 and 1023, so I was expecting 0 if the potentiometer is at the lowest position, 1023 if it is at the highest position and 500 somewhere in the middle.

In fact I get ~40 at the lowest position, I get 1021 at the highest position (that's okay, I guess), and I also get 1021 at the middle. 500 is at a 1/4 position, I expected to have ~255 there.

I measured the resistance of the potentiometer. It reads ~200 Ohm at the lowest postion, 10kOhm (as expected) at the highest position and ~5kOhm in the middle, so, exactly as I expected.

So, what did I get wrong?

Unfortunately I cannot comment. I can't really think of a reason why your readings are the way they are. Though you did not present to us an image of what potentiometer you are using and how you are really wring it up.

It is possible that your potentiometer is a center tapped type with 4 pins. You could have possibly connected the positive rail to the center tap pin, ground to the side pin and the wiper pin to the Arduino pin so that you would have the result you are getting.

Or potentially, you wired it correctly except for the fact the positive rail you connected to was 10V, but that is really dangerous.

Have you tried measuring the resistance of the potentiometer from one side pin to the other side pin?


for loop running infinitely void writereg() {
  digitalWrite(latchPin, LOW);
  for (int i = 7; i >= 0; i--) {
    digitalWrite(clockPin, LOW);
    Serial.print("wswitch&&&&&&");
    Serial.print(i);
    Serial.print("----------------------");
    digitalWrite(dataPin, switches[i].stat);
    Serial.println(switches[i].stat);
    digitalWrite(clockPin, HIGH);
  }
  digitalWrite(latchPin, HIGH);
  touched = false;
}

I don't understand what's wrong with what I'm doing here, but this for loop runs into an almost infinite loop and prints crazily. I'm a newbie to electronics and Arduino and I don't understand what's wrong here. Please help.

This is my switch class:

struct Swtch
{
  int num;
  bool stat;
  bool touched;
};

Swtch switches[8] = {{1, 0, 0}, {2, 0, 0}, {3, 0, 0}, {4, 0, 0}, {5, 0, 0}, {6, 0, 0}, {7, 0, 0}, {8, 0, 0}};

After a chat with OP, it turned out this was a more complex issue, probably a memory overrun.

This cannot be seen in this small snippet, but the whole program is using memory extensively (global variables and dynamic memory heap allocation).

Heavy use of String variables is a likely explanation for the observed behavior.
Also a lot of string literals are putting more pressure on memory in the OP program.

Here are my suggestions:

Replace all "..." string literals with flash-stored strings with F("..."). That will reduce the initial SRAM size used.
Replace all String variables with pure C-string (char* and char arrays) and use standard C string functions such as strcpy, strcat, strlen, strcmp, strchr... This forces to pre-allocate string to their maximum size, but this can be controlled at compile-time (for string variables defined as global). For this point, I also suggest to read a good tutorial on strings in C language.
Use const whenever possible (instead of variables that waste memory)
Use the smallest type needed for each variable, e.g. avoid int (2 bytes) when you need to store a boolean value, prefer bool type (only one byte) or even use 1 byte to store 8 boolean values and use boolean logic to manipulate each value.


Convert UNIX Timestamp I have an UNIX Timestamp in my Arduino Sketch and would like to get the day of the week of this timestamp (1-7).

How can I convert the timestamp to get the day of the week?

The simplest solution to that problem is to download the Time library and use the weekday() function:

int weekday(time_t t); // the weekday for the given time

Cheers!


Is there any way that the values here be converted to another variable and not string? int val1 =(mfrc522.uid.uidByte[0]);
int val2 =(mfrc522.uid.uidByte[1]);
int val3 =(mfrc522.uid.uidByte[2]);
int val4 =(mfrc522.uid.uidByte[3]);

String valA=String(val1);
String valB=String(val2);
String valC=String(val3);
String valD=String(val4);
uID=valA+valB+valC+valD;

The function above with mfrc522.uid.uidByte[x] is from the MFRC522.h Library by Miguel Balboa and it is initialized as byte there. But when I initialize the val1 to val4 as byte, the desired number doesn't appear. I don't intend to print the uID to serial (as someone may suggest that to readily print to serial as it converts it automatically to some ASCII strings), but instead in the client.print() of the Ethernet library along with other codes. I want to save it into another "greater" variable in terms of speed and memory allocation. The Arduino community warns about the use of String as it uses additional decoding which is not needed as well as may crash Arduino and make Arduino run out of memory. And somehow, I experience some lagging or hanging in the serial, which I thought maybe due to the use of Strings variable. Please help me. I've read some sprintf() concatenations and free() but not well documented, I'm quite confused on their explanations. :)

sprintf() is a nicer way to do that (imo), however, there's nothing wrong with what you've done-- if you don't have a ton more code, I'd continue to use it.

It's simple and that's a lot more important that speed most of the time. Also, the likely memory usage isn't enough to worry about.

In my experience, once I got past 1500 bytes SRAM (dynamic) memory usage, I ran into trouble. But my projects have a ton of code. I've read through the String class code and it's totally reasonable-- you're not likely to experience lag there.

My bet is that the lag is due to the timeout period, try making it smaller.


Power 5v from l298n to 5v pin arduino im using the l298n module, and 3x 18650 batterys (near 12v total), and supplying 12v to the 12v pin of the l298 module. Can i use the 5v pin of the module to power the 5v pin of arduino? Or i need a second power supply just for the arduino? Any tips?

The L298N is a chip, and the link you provided in the comments is to the chip, not to a full H-bridge module with voltage regulator and other components. We don't have any way to answer your question about your particular set-up without more info.

If the module you have uses a voltage regulator to provide clean 5V to its solid state chips, but does not use it to drive the motors, and it provides enough extra current to drive your Arduino then you might be able to get away with using it to feed your Arduino. If the H-bridge module uses the output of it's 5V regulator to drive the motors then I would not recommend using it to power your Arduino, since as the motor is switched on and off it will cause the voltage from the regulator to bobble. At the very least you would need a reservoir capacitor across the 5V rails near the Arduino to smooth out the 5V supply.


IDE support for Arduino micro I have an Arduino micro http://arduino.cc/en/Main/arduinoBoardMicro I was looking to know which is the lowest version of the IDE that support it. Actually on the IDE 0023 is not present in Tools > Board.

According to the Arduino Software Release Notes, support for the Arduino Micro was added in 1.0.2.


Controlling a servo motor with two arduinos? I have two Arduinos, two buttons and one servo motor.

I want to control a servo motor with two Arduino's when I pressed the buttons. I linked Arduino PWM pins (first Arduino PWM pin is 9, and second one is 3) to the servo motor signal input.

When I pressed button 1 servo motor moving a few, or pressed button 2. but the signal isn't clear, and servo motor doesn't move correctly that I assigned degree.

What can I do for the solution?

My first Arduino code is here:

#include<Servo.h>

#define Buton 8

Servo myServo;

void setup() {
  pinMode(Buton, INPUT);
  myServo.attach(3);
}

void loop()
{
  if (digitalRead(Buton) == 1)
  {
    myServo.write(90);
  }
  else
  {
    myServo.write(180);
  }

}

and second arduino code is:

#include<Servo.h>

#define Buton 8

Servo myServo;

void setup() {
  pinMode(Buton, INPUT);
  myServo.attach(9);
}

void loop()
{
  if (digitalRead(Buton) == 1)
  {
    myServo.write(90);
  }
  else
  {
    myServo.write(180);
  }

}

You can't just connect random pins together like that. Connecting two output pins together is a recipe for disaster. Best case scenario: nothing works. Worst case scenario: you break one or both Arduinos.

Only one Arduino can control a servo. If you want a second Arduino to make something happen to the servo you have to make it tell the Arduino that is controlling the servo that something should happen.

That could be a simple output of the second Arduino connected to an input of the first Arduino, in which case it kind of acts like a button. Or you could create some kind of communication channel between them - maybe using a Serial connection, or a Wire (I2C) connection. There's many ways, and which is best depends on how much control one Arduino needs to exert over the other.


"No more addresses" when using multiple DS18B20 sensors I want to build a scheme to get data from several DS18B20 sensors and write their temperature to serial. Before I connected them using parasite mode and using 2,7k resistor (because I didn't have 4,7k at home). Back then, it worked for 1 device, if I plug in another, it won't detect any of them (it writes "No more addresses"). Now I replaced 2,7k resistor with 4,7k and it doesn't detect any device connected. But if I do one little thing, which is replacing 4,7k resistor back with 2,7k, it will detect one device.

How to fix it?

Here is exactly how it is all connected now:

and here is the default sketch I am using:

#include <OneWire.h>

// OneWire DS18S20, DS18B20, DS1822 Temperature Example
//
// http://www.pjrc.com/teensy/td_libs_OneWire.html
//
// The DallasTemperature library can do all this work for you!
// http://milesburton.com/Dallas_Temperature_Control_Library

OneWire  ds(10);  // on pin 2 (a 4.7K resistor is necessary)

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

void loop(void) {
  byte i;
  byte present = 0;
  byte type_s;
  byte data[12];
  byte addr[8];
  float celsius, fahrenheit;

  if ( !ds.search(addr)) {
    Serial.println("No more addresses.");
    Serial.println();
    ds.reset_search();
    delay(250);
    return;
  }

  Serial.print("ROM =");
  for ( i = 0; i < 8; i++) {
    Serial.write(' ');
    Serial.print(addr[i], HEX);
  }

  if (OneWire::crc8(addr, 7) != addr[7]) {
    Serial.println("CRC is not valid!");
    return;
  }
  Serial.println();

  // the first ROM byte indicates which chip
  switch (addr[0]) {
    case 0x10:
      Serial.println("  Chip = DS18S20");  // or old DS1820
      type_s = 1;
      break;
    case 0x28:
      Serial.println("  Chip = DS18B20");
      type_s = 0;
      break;
    case 0x22:
      Serial.println("  Chip = DS1822");
      type_s = 0;
      break;
    default:
      Serial.println("Device is not a DS18x20 family device.");
      return;
  }

  ds.reset();
  ds.select(addr);
  ds.write(0x44);        // start conversion, use ds.write(0x44,1) with parasite power on at the end

  delay(1000);     // maybe 750ms is enough, maybe not
  // we might do a ds.depower() here, but the reset will take care of it.

  present = ds.reset();
  ds.select(addr);
  ds.write(0xBE);         // Read Scratchpad

  Serial.print("  Data = ");
  Serial.print(present, HEX);
  Serial.print(" ");
  for ( i = 0; i < 9; i++) {           // we need 9 bytes
    data[i] = ds.read();
    Serial.print(data[i], HEX);
    Serial.print(" ");
  }
  Serial.print(" CRC=");
  Serial.print(OneWire::crc8(data, 8), HEX);
  Serial.println();

  // Convert the data to actual temperature
  // because the result is a 16 bit signed integer, it should
  // be stored to an "int16_t" type, which is always 16 bits
  // even when compiled on a 32 bit processor.
  int16_t raw = (data[1] << 8) | data[0];
  if (type_s) {
    raw = raw << 3; // 9 bit resolution default
    if (data[7] == 0x10) {
      // "count remain" gives full 12 bit resolution
      raw = (raw & 0xFFF0) + 12 - data[6];
    }
  } else {
    byte cfg = (data[4] & 0x60);
    // at lower res, the low bits are undefined, so let's zero them
    if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
    else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
    else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
    //// default is 12 bit resolution, 750 ms conversion time
  }
  celsius = (float)raw / 16.0;
  fahrenheit = celsius * 1.8 + 32.0;
  Serial.print("  Temperature = ");
  Serial.print(celsius);
  Serial.print(" Celsius, ");
  Serial.print(fahrenheit);
  Serial.println(" Fahrenheit");
}

Is there anything I am doing wrong? Because I somehow managed to get it working some time ago.

A problem with what you are doing on the breadboard is that you show no bypass capacitors.

What makes the pull up "strong" is the ability to provide current to move the data line from zero back to one.  The load on the data line is its capacitance.  To move the data line from 0 to 1, you have to charge that capacitor.  Working on a bread board, you are correct that you have a larger capacitive load.  So you require more current to move the data line from zero to one quickly.

You are correct that the lower 620 ohm resistor will provide more current.  The large current will move the capacitance load of the data line more quickly.  But you are not paying attention to the other side of the resistor, the 5V rail.

The layout you have has inductance in the wires from the Arduino power supply out to the bread board.  An inductor has a voltage drop across it proportional to the rate of change of the current through it:

V = L  di/dt

The analogy is that inductance is a flywheel: if it is not spinning, it will take force to get is moving.  Similar, once it is spinning, it will take force to stop it.

So when the resistor starts conducting to pull up the data line, the inductance in the wires and breadboard cause a voltage drop.  The +5 side of the resistor voltage drops.  This inductance in the wires leading to the resistor prevents it from rapidly charging the data line back to 1.

That is the role of bypass capacitors.  You place 1 or 2 right at the resistor between the +5 and GND strips on the bread board.  Now when the resistor draws current, it initially pulls from the energy stored in the capacitors.  After a short time, the current will start pulling from the +5 wire.  Thereby, you have bypassed the inductance of the +5 supply, hence the name.

Add a 0.1 microFarad ceramic capacitor on your breadboard where the wires connect to the contact strips.  You will see this on schematics for anything that has a DC supply off board.  Right next to the power connector will be 2 or 3 capacitors, usually one big 2-10 uF tantalum and one smaller 0.1 uF or so.  Similar across circuit boards you see bypass caps placed at the supply voltage pin of every chip, commonly two: a 0.1 uF and a smaller 10 nF.

It might seem pointless to place a small capacitor in parallel with a larger capacitor.  The values just add, yes?  But again, the time response is different.  Capacitors are not perfect and have internal series resistance.  A big 10 uF electrolytic capacitor may store a lot of energy, but it is not fast in terms of how quickly it can start providing current.  A little 100 nF ceramic monolithic capacitor is very fast, but doesn't have much energy.

So with two bypass caps in parallel, you have the small one for the initial burst of current, the larger cap for the heavy lifting, and last and slowest the 5V wires and traces to supply to steady current.


Ethernet shield programming This is first time programming with Ethernet shield . I want to test the web server application with my Arduino. I have an Arduino Uno, Ethernet shield, and a potentiometer. Below code being uploaded.

Question are:

Currently I am using LAN connection to configure. How to configure it? Is internet required for below application?
How do I check the output?
Is there any software where i can make customized tags?
I have values coming from the serial port to be monitored on webserver. Can someone share how to monitor it?

Ethernet shield

#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192,168,1,177);

// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);

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

  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip);
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());
}

void loop() {
  // listen for incoming clients
  EthernetClient client = server.available();
  if (client) {
    Serial.println("new client");
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        Serial.write(c);
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank) {
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println("Connection: close");  // the connection will be closed after completion of the response
      client.println("Refresh: 5");  // refresh the page automatically every 5 sec
          client.println();
          client.println("<!DOCTYPE HTML>");
          client.println("");
          // output the value of each analog input pin
          for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
            int sensorReading = analogRead(analogChannel);
            client.print("analog input ");
            client.print(analogChannel);
            client.print(" is ");
            client.print(sensorReading);
            client.println("
");
          }
          client.println("");
          break;
        }
        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
        }
        else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    // give the web browser time to receive the data
    delay(1);
    // close the connection:
    client.stop();
    Serial.println("client disconnected");
  }
}

You need to determine what the network address is of the LAN you have connected the arduino to. A router can often give you this information. Alternatively you can connect a computer to the same network and look at the computers network settings (this varies depending on what OS you use). Then you have determine what IP address is available on that network. You will enter this in the ip variable in your example.

The internet is not required for your application, however you do need the arduino to be connected to a LAN and another device (probably a standard computer) to invoke the arduinos server behaviour.

To test that it works, you can open an internet browser on the second device and type in the IP address that you have configured for the arduino into the address bar.


How do I upload an Arduino STM32 binary from the Mac command line? I've compiled an Arduino program via a Makefile and have the resulting hex file.

From the Mac command line, how do I upload this hex file to my STM32 Cortex M3 board?  For an ATMEL processor I would use avrdude.

There are several different tools for uploading binaries to a Cortex M3.  Depending on the board (not chip) configuration, they include (ht: Majenko):

dfu-util through an FT232 adapter
stm32flash through serial
micronucleus through the Micronucleus bootloader
stlink through an STLink programmer

Many Arduino flavors use a board with some kind of USB or FT232 adapter.  In this case:

the STM32 line of processors include a DFU (device firmware update) bootloader in ROM.

The dfu-util project supports a Mac version of dfu-util, their command line DFU tool.

Note that this answer is identical for any binaries which run on the processor, be they Arduino sketches or programs developed with other frameworks.