Serial receiver (Arduino Micro ATmega32U4) in bad state I have configured two Arduino Micros as a pair of multiplexer/demultiplexers communicating via Tx and Rx.

Everything works great except for one little thing. If I reset the sender (multiplexer) the receiver (demultiplexer) goes into a bad state resulting in random low and high outputs.

Resetting the receiver brings it back to a normal state but I am hoping someone might have a better solution. Using the serial monitor I noticed that during the reset process on the sender there are some seemingly random bits being transmitted toward the end. Not sure if this has anything to do with it.

The code for the sender is:

byte PINBold;
byte PINDold;
byte PINFold;

byte PBmask = B11111110;
byte PDmask = B11010011;
byte PFmask = B11110011;

void setup() {
  Serial1.begin(3704400); // Speed
  DDRB = DDRB & B00000001; // Sets pins to digital input: 11,10,9,8,MI,MO,SCK
  DDRD = DDRD & B00101100; // Sets pins to digital input: 2,3,4,6,12
  DDRF = DDRF & B00001100; // Sets pins to digital input: A0,A1,A2,A3,A4,A5
}

void loop() {
  if (((PINB & PBmask) != PINBold) |((PIND & PDmask) != PINDold) | ((PINF & PFmask) != PINFold)) {
    Serial1.write(PINB);
    Serial1.write(PIND);
    Serial1.write(PINF);

    PINBold = PINB & PBmask;
    PINDold = PIND & PDmask;
    PINFold = PINF & PFmask;
  }
}

The code fore the receiver is:

void setup() {
Serial1.begin(3704400); // Speed
DDRB = DDRB | B11111110; // Sets pins to digital output: 8,9,10,11,MI,MO,SCK
DDRD = DDRD | B11010011; // Sets pins to digital output: 2,3,4,6,12
DDRF = DDRF | B11110011; // Sets pins to digital output: A0,A1,A2,A3,A4,A5

PORTB = PORTB | B11111110;
PORTD = PORTD | B11010011;
PORTF = PORTF | B11110011;
}

void loop() {
if (Serial1.available() > 2) {
PORTB = Serial1.read();
PORTD = Serial1.read();
PORTF = Serial1.read();
}
}

Ok, there are some issues in your code. First of all, are you sure that a baudrate  of 3.7Mbps is what you need? Can't you go a bit slower?

If you are dealing with mechanical parts (e.g. buttons), then a refresh rate of 100Hz cannot be noticed; to send 3 bytes you need 30 bits, and at 9600 bit/s this means 320 Hz of frequency. Reducing the speed increases the rejection to noise too, so I'd go with a lower speed (even a 38.4kbps is fine).

Then you are reading the PINx registers too many times, which can lead to inconsistency. What happens if the value changes after the if but before the updating of the value? It's better to store it in a variable.

These, however, are not the root cause of your problem. The main issue, as anticipated by Jot, is that you are not using a protocol to synchronize the two elements. This means that at the bootup the receiver does not know if it is at the beginning of the "frame" or in the middle. Moreover start conditions when the sender is not online are not ignored.

So a "protocol" must be agreed between the two. The simplest one I can think of revolves around the fact that you can reserve a bit for the flow control.

Looking at your port masks, I can see that if we split the PINB values in the two nibbles and then move the lowest one one bit to the left, we get that bit 3 is never used for transmitting a pin data:

PINB 76543210 -> 7654x321 (pin 0 was not used)

consequently we use this as a control bit. It has value 1 for the first bit in the frame, and 0 otherwise. On the receiver side, you look for a byte with this bit set, then record also the other two, then check if the other two have a 0 in this position and, if confirmed, you have your frame.

This solution has the highest throughput, but may be a bit fragile when some noise is present (false start of frames, possibly).

For this reason I suggest you to add another byte to the packet, thus having to transmit four bytes. Again, the first one has the bit set in position 3, and the other have zero. But in this case the first byte has a predefined value, and consequently the receiver has just to look for this specific value (and the robustness is increased.

Ok people, I can hear your question. Where is the code? Well, here it is. For the sender, you have to perform a bit of manipulation on the bytes to be sent. I chose the hex value 0x5A because it has a lot of transitions (difficult to replicate from a noise) and it has a 1 bit in position 3. I also changed the things said at the beginning (baud rate and reading PINx only once); feel free to revert the changes if you have different needs. Moreover I initialized the old variables, and I set the direction of the pins based on the mask rather than having it done manually (easier to maintain).

EDIT: I added the possibility to get the current status by sending a char on the serial interface (useful when the receiver boots up)

byte PINBold;
byte PINDold;
byte PINFold;

const byte PBmask = B11111110;
const byte PDmask = B11010011;
const byte PFmask = B11110011;

const byte StartOfFrame = 0x5A; // bit 3 is always '1'

void setup()
{
    Serial1.begin(38400); // Speed
    DDRB = DDRB & (~PBmask); // Sets pins to digital input: 11,10,9,8,MI,MO,SCK
    DDRD = DDRD & (~PDmask); // Sets pins to digital input: 2,3,4,6,12
    DDRF = DDRF & (~PFmask); // Sets pins to digital input: A0,A1,A2,A3,A4,A5

    PINBold = ~PBmask; // Force a 1 in a forbidden position -> force a sending at first round
    PINDold = ~PDmask;
    PINFold = ~PFmask;
}

void loop() {
    byte currPINB = PINB & PBmask;
    byte currPIND = PIND & PDmask;
    byte currPINF = PINF & PFmask;

    bool shouldSendData = false;

    if ((currPINB != PINBold) || (currPIND != PINDold) || (currPINF != PINFold))
    {
        PINBold = currPINB;
        PINDold = currPIND;
        PINFold = currPINF;
        shouldSendData = true;
    }

    while (Serial1.available())
    {
        Serial1.read();
        shouldSendData = true;
    }

    if (shouldSendData)
    {
        Serial1.write(StartOfFrame);
        Serial1.write((currPINB & 0xF0) | ((currPINB >> 1) & 0x07)); // send currPINB 7654_321, where _ is a '0'
        Serial1.write(currPIND); // bit 3 is always '0'
        Serial1.write(currPINF); // bit 3 is always '0'
    }
}

On the receiver side, what you need is to wait for the start of frame, then you have your data. I prefer to implement it as a very small state machine. I also added a bonus timeout feature to exit from the payload state after 10ms of inactivity.

EDIT: Added the sending of a char at the beginning, to trigger a resending of the status from the master (if available). Included also the functional code from the question, since the OP added the receiver

const byte StartOfFrame = 0x5A; // bit 3 is always '1'

const byte PBmask = B11111110;
const byte PDmask = B11010011;
const byte PFmask = B11110011;

// State machine states
const byte SM_WaitingForSOF = 1;
const byte SM_WaitingForPayload = 2;

byte SM_CurrentState;

bool receivedData;
byte receivedPortB;
byte receivedPortD;
byte receivedPortF;

uint8_t startOfTransmissionMillis;
const byte transmissionTimeout_ms = 10;

void setup()
{
    Serial1.begin(38400); // Speed

    DDRB = DDRB | PBmask; // Sets pins to digital output: 8,9,10,11,MI,MO,SCK
    DDRD = DDRD | PDmask; // Sets pins to digital output: 2,3,4,6,12
    DDRF = DDRF | PFmask; // Sets pins to digital output: A0,A1,A2,A3,A4,A5

    SM_CurrentState = SM_WaitingForSOF;
    receivedData = false;
    receivedPortB = 0;
    receivedPortD = 0;
    receivedPortF = 0;

    Serial1.write('H'); // Any byte is ok; it is used to trigger a sending of the status
}

void loop() {
    receivedData = false;

    switch (SM_CurrentState)
    {
        case SM_WaitingForSOF:
            while (Serial1.available() > 0) // can also be a "if"
            {
                if (Serial1.read() == StartOfFrame)
                {
                    SM_CurrentState = SM_WaitingForPayload;
                    startOfTransmissionMillis = (uint8_t)millis();
                    break;
                }
            }
            break;
        case SM_WaitingForPayload:
            if (Serial1.available() >= 3)
            {
                receivedPortB = Serial1.read();
                receivedPortD = Serial1.read();
                receivedPortF = Serial1.read();

                if (((receivedPortB & 0x08) | (receivedPortD & 0x08) | (receivedPortF & 0x08)) == 0)
                { // All the payload bits have '0' as bit 3, so communication was ok
                    receivedData = true;
                }

                SM_CurrentState = SM_WaitingForSOF;
            }
            else if ((((uint8_t)millis()) - startOfTransmissionMillis) > transmissionTimeout_ms)
            {
                SM_CurrentState = SM_WaitingForSOF;
            }
            break;
        default:
            SM_CurrentState = SM_WaitingForSOF;
            break;
    }

    if (receivedData)
    {
        PORTB = (PORTB & (~PBmask)) | (receivedPortB & 0xF0) | ((receivedPortB & 0x07) << 1);
        PORTD = (PORTD & (~PDmask)) | receivedPortD;
        PORTF = (PORTF & (~PFmask)) | receivedPortF;
    }
  }
}

Beware: untested code. I'm confident that no major bugs are present, but some tweaking may be necessary


Digispark / Digikeyboard code doesn't execute inside setup{} Here's sample code to demonstrate my problem:

#include <DigiKeyboard.h>

void setup() {
  // put your setup code here, to run once:
  delay(5000);
  DigiKeyboard.print("TESTING TESTING");
  pinMode(1,OUTPUT);
  digitalWrite(1,HIGH);
}

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

My problem is that I can't get Digikeyboard.print() or other Digikeyboard commands (e.g. sendKeyStroke()) to do anything while they are located inside the setup function. The led command after the print command executes properly.

The print command will work if I place it inside the loop function. However, I want to only execute this code once.

Any assistance would be appreciated, and I would be happy to provide more information if necessary.

EDIT: I worked around this by using a if-expression inside the loop function to only run the code once. However, I am still interested in learning why my original code doesn't work.

The (hard to find) documentation on the DigiKeyboard example:
http://digistump.com/wiki/digispark/tutorials/digikeyboard

States:

  It is essential that DigiKeyboard.update() is called regularly (the
  beginning of the loop is good) to maintain USB communication. Using
  DigiKeyboard.delay() will automatically spam DigiKeyboard.update()
  calls during the delay period. If your loop code is fast just using
  DigiKeyboard.delay() will be sufficient.

Without looking deeper into it, I suspect that your initial call to DigiKeyboard.print() fills a buffer and DigiKeyboard needs subsequent repeated calls in order to empty the buffer.

Does the problem still exist if you put DigiKeyboard.update() as the only statement in the loop() function?


Trying to Serial.write RAW code properly I have a SIM800L Module connected to my arduino Nano. I want to open a TCP connection from the sim800l module to my own server and send a text string. The connection is working however I am not able to send text, because there is an issue with the arduino write() function I think... Below is the code I am trying to execute. Right after the message is sent, I need to send the stop value 0x1A (byte 26) to tell the sim800l module that the message end is reached and to send out the message.
My problem is, that it is not working in the arduino IDE and I don't know why.

My arduino code:

#include <SoftwareSerial.h>

#define SIM800_TX_PIN 8
#define SIM800_RX_PIN 7

SoftwareSerial serialSIM800(SIM800_TX_PIN, SIM800_RX_PIN);

void setup() {

serialSIM800.println("AT");
delay(500);

serialSIM800.println("AT+CIPSTART=\"TCP\",\"IP-ADRESS-HERE\",\"9999\""); //connection works
delay(500);

serialSIM800.println("AT+CIPSEND");
delay(500);

serialSIM800.print("TEXT MESSAGE HERE");
delay(500);

serialSIM800.write(26);
delay(500);

serialSIM800.println("AT+CIPCLOSE");
delay(500);
}

void loop() {
  //Empty
}

On my server I am running this python script that opens a socket:

import socket
import sys

HOST = ''   # all available interfaces
PORT = 9999 # Arbitrary non-privileged port

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'

#Bind socket to local host and port
try:
  s.bind((HOST, PORT))
except socket.error as msg:
  print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
  sys.exit()

print 'Socket bind complete'

#Start listening on socket
s.listen(10)
print 'Socket now listening'

#now keep talking with the client
while 1:
  #wait to accept a connection - blocking call
  conn, addr = s.accept()
  print 'Connected with ' + addr[0] + ':' + str(addr[1])
  data = conn.recv(1024)
  print len(data)
  print data
s.close()

Once I execute this, I see the connection is working because "Connected with IP:PORT" is printed on my console. However right after that "len(data)" is printed (0) and "data" is an empty string. I even upped the delay from 500 to 5000, still same result.

However, if I leave the arduino IDE and send the message using the program "HTerm", it is working! In HTerm I typed in the text message and hit enter. After that I switched from ascii to hex mode (there is a checkbox) and I just typed 1A and sent it. That way it worked. Anybody can help me? Why is it not working @arduino?

Replace serialSIM800.write(26); with serialSIM800.write(0x1A);, also  change serialSIM800.print("TEXT MESSAGE HERE"); with a println or add a carriage return \n.


Read pc volume percentage? is there a way to read the current pc volume? This is going to be a part of a project that I have in mind that is essentially reading curent pc volume value and giving it an RGB value (green=>30, yellow=<30>60, red=<60) and lighting up an RGB led accordingly.

There is no way for any hardware device, Arduino or otherwise, to request information like that from a computer.

HID is a protocol which (when used as a keyboard) allows you to send keypresses, including "media keys", which tell the computer to change the volume (amongst other things). There is no provision, other than three status LEDs, for getting any data back from the computer.

You will have to write software for your computer to query that information using whatever API may be available for your operating system, and pass that information through whatever communication channel you choose to the Arduino (such as through serial).

Some pointers:

C# get master volume level/precent
Windows 7 Master Volume
Arduino: Sending and Receiving Multi-Digit Integers


Adafruit RGB LCD w/ Shield kit connection to arduino uno? I have a adafruit rbg 16x2 lcd with shield kit and am trying to connect it to an arduino uno. The only thing is the assembly instructions have the lcd basically using every pin on the arduino, even tho it says its not for connections. Since we are using many of the pins already on the board, can I wire it to the board without soldering it to every pin, essentially only wiring to the few necessary pins?

Sorry, I am very new at this. Thank you for the help.

EDIT: Was essentially looking for the follwing diagram. Thanks to all!

The idea of shields is that they (in theory) can be stackable.
(In practice they are usually not)
This means that technically you can do this:

That's why by design every shield connects to every Arduino pin but uses only some of them. That way shield is mechanically well attached to the Arduino, and can pass "unused" pins to the shield above it.

Your shield is designed to be always "on top" so I think it only connects to some pins just for mechanical support. Technically the LDC screen needs only 6 pins and 1 pin per button.

EDIT:
I read now that the shield you got uses only 2 pins and communicates using I2C bus (which is perfect) so I'm 100% sure that it's designed to be on top of the stack and work together with other shields and uses extra pins for mechanical support.


Simple Arduino - 74hc595 shift register construction [tmli5] I'm quite new to Arduino world and I'm trying to understand how shift registers work.
I built this construction :

In fact, it is an Arduino Duemilanove with AtMega on it, but afaik it doesn't matter.

The tutorial I try to follow use SPI library so I try to do it too. I kind of understood that data input, latch and clock had to be pins 7, 4 and 11.

Basically, all I try to do is sending a byte to light the LEDs. As for me now, the sequence should light all LED, then no one, then one after another.
I know there is one more input ont the right side of the SR but I didn't plan this model so I ran out of LEDs...

This is the code I use :

#include <SPI.h>
#include <StandardCplusplus.h>
#include <vector>
#include <iterator>
#include <size_type>

using namespace std;

//pin du shift register
#define DATA_PIN 13
#define LATCH_PIN 4
#define CLOCK_PIN 11
//à utiliser plus tard
#define INPUT_PIN 2

void setup() {
  pinMode(DATA_PIN, OUTPUT);
  pinMode(LATCH_PIN, OUTPUT);
  pinMode(CLOCK_PIN, OUTPUT);
  //pinMode(INPUT_PIN, INPUT);

  SPI.setBitOrder(MSBFIRST);
  SPI.setDataMode(SPI_MODE0);
  SPI.setClockDivider(SPI_CLOCK_DIV2);
  SPI.begin();

  //SPI.transfer(getBit(3));
  //digitalWrite(LATCH_PIN, HIGH);
  //digitalWrite(LATCH_PIN, LOW);

  Serial.begin(9600);
  Serial.println("start !");
}

void loop() {
  shift(B11111111);
  shift(B00000000);
  shift(B10000000);
  shift(B01000000);
  shift(B00100000);
  shift(B00010000);
  shift(B00001000);
  shift(B00000100);
  shift(B00000010);
  shift(B00000001);
}

void shift(int n){
  SPI.transfer(n);
  digitalWrite(LATCH_PIN, HIGH);
  digitalWrite(LATCH_PIN, LOW);
  Serial.print("shift : ");
  Serial.println(n);
  delay(1000);
}

When I upload this code, LEDs sequence has no sense, but serial output was totally OK.

What I see (without the output 0 of course) is :
1111111, 0111111, 1011111, 1110111, 1111101 and then 1111111 without further changes, whereas serial output is 255, 0, 128, 64, 32, 16, 8, 4, 2, 1, 255, 0, 128 and so on.

I assume I didn't understand something important, and it prevent me from finding answers in google.

Thanks for helping, it's really disturbing for me.

EDITS :

changed the title, it is a 74HC595.

Strangest behavior too (not gonna create another topic for that now), I dont have to connect both the gnd and VCC from my arduino for this to light LEDs. It changes a little the brighness of LEDs, but surprisingly VCC< GND< both

This is the tutorial I use to understand shift registers : https://youtu.be/6fVbJbNPrEU?t=195, and the one that uses SPI is nXl4fb_LbcI

I am now aware that I should get one resistor for each LED but I don't have that much resistors and as far as I can see this don't harm my LEDs nor underpower them.

You have a number of problems here. The first is the wiring.

My wiring diagram above is for the Uno / Duemilanove. Since that is what you have, you should follow that.

The pins are fixed in hardware, except for the slave select pin. Thus D13 on the Duemilanove should go to pin 11 on the 595. D11 on the Duemilanove should go to pin 14 on the 595. And your slave select (which may as well be pin 10 on the Duemilanove) should go to pin 12 on the 595.

Your code looks more complex than it needs to be. This code will exercise the 8 LEDs:

#include <SPI.h>

const byte LATCH = 10;

void setup ()
{
  SPI.begin ();
}  // end of setup

byte c;
void loop ()
{
  c++;
  digitalWrite (LATCH, LOW);
  SPI.transfer (c);
  digitalWrite (LATCH, HIGH);
  delay (20);
}  // end of loop

As other responders have said, you should have a current-limiting resistor for each LED. You can't share it like that.

Also the 595 ground (pin 8) should be wired to the Duemilanove ground, not via a resistor.

Reference

Using a 74HC595 output shift register as a port-expander


How to continuously monitor range finder and immediately interrupt code to run a different code in pedestrian traffic lights setup? I am currently doing part 2: Pedestrian Mode of my project below:

Regular Mode: This is the regular mode of operation. In this mode the
three lights (Red, Yellow and Green LEDs) should operate in the following
order. The Red LED lights for 2 seconds, followed by the Yellow LED for 1
second, the Green LED for 2 seconds and then the Yellow LED again for 1
second. The cycle should repeat until the mode changes.
Pedestrian Mode: This mode uses the SRF05 Ultrasonic Range Finder to
detect the proximity of any object. The lights should operate as defined in
the regular mode UNTIL an object is detected less than 10 cm from the
TLC. The buzzer should then beep and the Yellow LED must blink ON/OFF
(flashing intervals of 0.1 sec) repeatedly 10 times. The buzzer should then
stop beeping and the operation of the lights (not the system) must behave
as it would in the regular mode. The operation stays the same until the
mode changes

My code works, however it waits for the entire regular cycle to finish before sensing a pulse with the ultrasonic range sensor to determine if an object is near or not. Therefore, when I put my hand near the sensor, it has to finish running the regular mode before it detects my hand and switches to pedestrian mode. What I would like is for the range finder to continuously fire the pulse and immediately switch to pedestrian mode when it detects an object less than 10 cm away.

Code below:

int red_light = 12;
int yellow_light = 10;
int green_light = 8;
int ECHOPIN = 3;
int TRIGPIN = 5;
int buzzer = 7;
float distance;

void setup() {
  Serial.begin(9600);
  pinMode(red_light, OUTPUT);
  pinMode(yellow_light, OUTPUT);
  pinMode(green_light, OUTPUT);
  pinMode(ECHOPIN, INPUT);
  pinMode(TRIGPIN, OUTPUT);
  pinMode(buzzer, OUTPUT);
}

void loop() {
  range_finder();
  if (distance < 10) {
    pedestrian_mode();
  } else {
    regular_mode();
  }
}

void regular_mode() {
  digitalWrite(red_light, HIGH);
  delay(2000);
  digitalWrite(red_light, LOW);
  digitalWrite(yellow_light, HIGH);
  delay(1000);
  digitalWrite(yellow_light, LOW);
  digitalWrite(green_light, HIGH);
  delay(2000);
  digitalWrite(green_light, LOW);
  digitalWrite(yellow_light, HIGH);
  delay(1000);
  digitalWrite(yellow_light, LOW);
}

void range_finder() {
  digitalWrite(TRIGPIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIGPIN,HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIGPIN,LOW);
  distance = pulseIn(ECHOPIN, HIGH);
  // return 0 if no high pulse in 1 sec
  distance = distance/58;
  Serial.print(distance);
  Serial.println("cm");
  delay(200);
}

void pedestrian_mode() {
  digitalWrite(buzzer, HIGH);
  digitalWrite(yellow_light, HIGH);
  delay(100);
  digitalWrite(yellow_light, LOW);
  delay(100);
  digitalWrite(yellow_light, HIGH);
  delay(100);
  digitalWrite(yellow_light, LOW);
  delay(100);
  digitalWrite(yellow_light, HIGH);
  delay(100);
  digitalWrite(yellow_light, LOW);
  delay(100);
  digitalWrite(yellow_light, HIGH);
  delay(100);
  digitalWrite(yellow_light, LOW);
  delay(100);
  digitalWrite(yellow_light, HIGH);
  delay(100);
  digitalWrite(yellow_light, LOW);
  delay(100);
  digitalWrite(yellow_light, HIGH);
  delay(100);
  digitalWrite(yellow_light, LOW);
  delay(100);
  digitalWrite(yellow_light, HIGH);
  delay(100);
  digitalWrite(yellow_light, LOW);
  delay(100);
  digitalWrite(yellow_light, HIGH);
  delay(100);
  digitalWrite(yellow_light, LOW);
  delay(100);
  digitalWrite(yellow_light, HIGH);
  delay(100);
  digitalWrite(yellow_light, LOW);
  delay(100);
  digitalWrite(yellow_light, HIGH);
  delay(100);
  digitalWrite(yellow_light, LOW);
  delay(100);
  digitalWrite(yellow_light, HIGH);
  delay(100);
  digitalWrite(yellow_light, LOW);
  delay(100);
  digitalWrite(yellow_light, HIGH);
  delay(100);
  digitalWrite(yellow_light, LOW);
  delay(100);
}

Also I have a feeling some parts of my code may be unnecessarily long and could be shortened. If so, I would appreciate any advice and how to do that. Thank you.

digitalWrite(yellow_light, HIGH);
   delay(100);
   digitalWrite(yellow_light, LOW);
   delay(100);

   digitalWrite(yellow_light, HIGH);
   delay(100);
   digitalWrite(yellow_light, LOW);
   delay(100);

...

You really need to read up on "for" loops. Make a loop that does it 10 times, don't copy and paste 10 times.

As for your other issue, at the very least you could test the proximity sensor after each delay. Read up on millis. Just imagine how you might do it in real life. Would you really delay for two seconds? Or would you check the clock to see if two seconds had elapsed and also check if a pedestrian had arrived?

And better still, replace delay with a loop which tests elapsed time, and also tests the distance sensor.

I'm not writing more specific code because clearly the exercise is for you to learn how to do this. I already know how to do it, and if I just posted the exact answer you wouldn't have learned how to do it.


Distance Measurement - between 6 points, individually moving in (almost) any direction within 1m I'm trying to find a solution for a given task in a problem I want to solve.
Assume I have 6 individual Points in a 3D environment of about 1m³. Each point will be able to change position (almost) freely.
Is there a way I can get the information of which distance each point is to any of the remaining 5 points?
Background Idea for understanding: Say its 2 wooden triangles (one of those points on each angle) and I need to calculate how far and in which direction one is moving from or towards the other.
By comparing all those distances, direction and step-width may be easily calculated.
Are there like "coded" distance-sensors so they don't mix their signals?
Any thoughts highly appreciated.

You may try to implement some kind of ultrasonic transponders. The
emitter sends a code addressing a specific receiver. Upon recognizing
its address, the receiver replies after a short, fixed delay. The
emitter measures the time it took the response to reach it, and from
there computes the distance.

You may need some kind of omnidirectional transducers (e.g. this
models) if you want the measurement to work in any
direction. And also a protocol to avoid several emitters talking at the
same time.

This seems to me like a very complex project though.


Max double value or NAN as a sentinel value? I am in need of a sentinel value to use to assign to a double variable initially.
0 or -1 won't work because these values are valid values in my computation and I need a value that will stand out.

Possible choices are:

Maximum double value
Minimum double value
NAN (I would also need a method to check is_nan as well)

How can I accomplish this in the Arduino language?

This is a matter of personal preference. I like NAN because it is almost
always obvious it cannot be a valid value.

You can test for the value being NAN with
isnan().


Can not receive data from UART with stepper motor I am using an Arduino Mega2560
While my motor is moving I can not receive anything from the UARTs. When the motor ends movement, I receive data from UART.

How can I make my motor move without stopping the reception of data from UART?

If you look at AccelStepper.cpp code of the library you're using, you'll notice that runToNewPosition() is:

void AccelStepper::runToNewPosition(long position)
{
    moveTo(position);
    runToPosition();
}

which, in turns calls:

// Blocks until the target position is reached
void AccelStepper::runToPosition()
{
    while (run())
    ;
}

In turn, run() returns false only when the position is reached, as shown here:

boolean AccelStepper::run()
{
    if (_targetPos == _currentPos)
    return false;

    if (runSpeed())
    computeNewSpeed();
    return true;
}

As you can see, your program is blocked until the position is not reached.

Data can be still received by the serial port (until buffer is exceed), but you won't be able to read it until that while ends.

To make the motor running without blocking the program, you should implement the AccelStepper functions in the loop function, in a non-blocking way.

In particular, (I only help you to set the position to 1100. You'll make the effort to bring it back to 0, with small modifications), in rotate_motor() call only:

stepper1.moveTo(1100);

Then in the loop, write somewhere:

stepper1.run();

EDIT:
Hint for having the motor moving forward and then backward as in your original code:
Add a state variable (say you call it "m"), where you store if you need to move forward (e.g. 2), backward (e.g. 1) or stop (0). Then, before calling stepper1.run(), check if you actually must move (if (m != 0)). When you call the stepper1.run() method, check if it returns false. In this case it means it reached the position, then you must change the value of m accordingly.


Can you output to D+ and D- so that Arduino Uno can be used as a USB device? My project is basically a set of 5 audio signals (analog) that get altered slightly by Arduino Uno. I convert to MIDI and would then output it to USB, so that it can be used in a program of my choice on the computer. I found a vaguely similar project online with a guide. In that project they write a serial to a MIDI out, and then plug that into a computer. I'm fairly sure I can't just use the TX and run that into the USB, that wouldn't work. So I'm looking for an alternative method.

Not with an Uno, no. You can only use USB Serial (CDC/ACM) through the on-board USB chip[1].

Your best bet is probably with a Teensy 3 (or 3.1 or whatever they are up to now) which has built-in support for USB MIDI emulation.

1: I believe there is MIDI firmware for the USB chip on the Uno, but installing that requires a hardware programmer and then breaks the normal sketch upload.


RGB LEd and a push button in TinkerCAD I'm working on TinkerCAD, I want to design and simulate a circuit in which there are following components. 1. 1 RGB LED 2. 1 Push button 3. 3 Photo-resistors. 4. 1 Arduino board. So the light should be off at the starting. When the push button is pressed for the first ever time, the LED should light up as red, and then the brightness of the red color should be able to controlled by one of the three photo-resistors used, the second time when the push-button is pressed the LED should light up as green and green color this time should be controlled by another photo-resistor..when the button is pressed for the third time , the LED should now change to blue color and the third photo-resistor should be able to control the brightness of the blue color. And this cycle should go on, upon pressing the Push button.

please tell me what's wrong.

Code looks like this

int button_state = 0;//declaring a variable
int counter;//declaring another variable,will keep count of which color to be lighted
const int pRed = A2; //assigning pin A2 as pRed
const int pBlue = A1; //.............A1....pBlue
const int pGreen = A0; //............A0.....pGreen
int inputRed;//adjusted value of led brightness will be stored
int inputGreen;
int inputBlue;
const int ledRed = 9;
const int ledGreen = 11;
const int ledBlue = 10;

void setup()
{
  pinMode(2,INPUT);
  pinMode(ledRed,OUTPUT);
  pinMode(ledGreen,OUTPUT);
  pinMode(ledBlue,OUTPUT);
  pinMode(pRed,INPUT);
  pinMode(pGreen,INPUT);
  pinMode(pBlue,INPUT);
}

void loop()
{
  button_state = digitalRead(2);// reading the button state
  inputRed = analogRead(pRed);// Reading the value from A2 pin
  inputRed = map(inputRed,0,1023,0,255);//value from A2 pin adjusted for led's brightness
  if (button_state == HIGH) {
    counter = 0; // Declaring counter as 0 again
    analogWrite(ledRed,inputRed);
    analogWrite(ledGreen, 0);
    analogWrite(ledBlue, 0);
    delay(10);// Wait for 10 millisecond(s)
    green();// Jumping to green
  }
}
void green()
{
  while (counter == 0){//counter was declared 0 in loop function,so the code won't go ahead till it's 0 only
  button_state = digitalRead(2);//for reading the button state once again
  inputGreen = analogRead(pGreen);//reading the signal from A0 as it is the inputpin for photoresistor for green light
  inputGreen = map(inputGreen,0,1023,0,255);  //value from A0 pin mapped
  if (button_state == HIGH) {
    counter++; // Increasing counter by 1 so that it becomes 1 now.
    analogWrite(ledRed,0);
    analogWrite(ledGreen,inputGreen);
    analogWrite(ledBlue,0);
    delay(10);//wait for 10 millisecond(s)
    blue(); //jumping to function for blue led now
  }
}
}
void blue()
{
  while (counter == 1)//using while, so that the code won't go ahead if counter=1,as made in function for green light
  {
  button_state = digitalRead(2);
  inputBlue = analogRead(pBlue);//reading value from A1 pin
  inputBlue = map(inputBlue,0,1023,0,255);//value from A1 pin mapped
  if (button_state == HIGH) {//
    counter++;
    analogWrite(ledRed,0);
    analogWrite(ledGreen,0);
    analogWrite(ledBlue,inputBlue);
    delay(10);//wait for 10 millisecond(s)
  }
  }
}

please tell me what's wrong.

I'm sorry to say, but pretty much everything. You need to rethink your program flow from the ground up.

Separate out the button from the LED actions. The button should only control the counter. The counter then makes the decision what to do with the LEDs.

Also you have to learn about the concept of change with the button. You don't want to be doing something if the button is high, since that will be being done all the time the button is pressed. Instead you need to learn how to do something only at the moment the button changes from low to high.

As a rough outline to how your program could look, here's a pseudo-listing:

Set the counter to 0
If the button changes from LOW to HIGH

Increment the counter

If the counter is greater than 3

Set the counter to 1

That would give you a sequence of 0-1-2-3-1-2-3-1-2-3 for the counter as you press the button.

Next you have a separate section in your loop to deal with what the counter is.

If the counter is 0

Turn off all LEDs

If the counter is 1

Control the red LED and turn off the others

If the counter is 2

Control the green LED and turn off the others

If the counter is 3

Control the blue LED and turn off the others

If you implement that properly you will have created a finite state machine.


How important is the INT pin of the MPU6050 (GY-521)? I want to wire multiple MPU6050 (at least 16 of them) to an arduino UNO for development (then nano for production). So I first started wiring one MPU6050 to an arduino like shown on the diyhacking website or in the picture below:

as you can see in the picture above the INT pin is used.
I then wearched for a way to wire multiple MPU6050 to an arduino using a multiplexer and I found a way on horizonlab's website or see the picture below:

As you can see in the second picture the INT isn't used at all. I'd like to know how important it is and what I'm missing out by not using it.

The INT is the interrupt signal, usually open-drain output and you can connect many of them to the single MCU interrupt line (but you have to check all devices which ones are ready). The LOW level from MPU device signalize that data are ready (conversion was finished). So you don't have to periodically read status register to find it out (no polling is necessary).

In short, using INT is optional.


16x2LCD Display serial read extra character I get extra character (frowning face) when sending a text over the serial monitor(see attached image)

When empty string is sent over the serial monitor, the LCD display still shows the extra character of frowning face.
How do I get rid of the extra character?
I use the tutorial code below and change nothing in the code.
https://www.arduino.cc/en/Tutorial/LibraryExamples/LiquidCrystalSerialDisplay/
#include <LiquidCrystal.h>

    // initialize the library by associating any needed LCD interface pin
    // with the arduino pin number it is connected to
    const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
    LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

    void setup() {
      // set up the LCD's number of columns and rows:
      lcd.begin(16, 2);
      // initialize the serial communications:
      Serial.begin(9600);
    }

    void loop() {
      // when characters arrive over the serial port...
      if (Serial.available()) {
        // wait a bit for the entire message to arrive
        delay(100);
        // clear the screen
        lcd.clear();
        // read all the available characters
        while (Serial.available() > 0) {
          // display each character to the LCD
          lcd.write(Serial.read());
        }
      }
    }

The LCD display acts a bit different to a normal console. For instance, it does not recognize the newline character and uses the corresponding ASCII code (10) like a normal letter. Depending on the letter map of your display (for which there are several variants on the market) this will print a more or less random character. To avoid this, you have to strip the last letter from the input string before sending it to the display.
For the same reason, sending an empty string does nothing, since an empty string sends no letters. To clear individual characters in the display, you have to overwrite them with a space.


16*2 LCD display doesn't display my result I am working on a project to calculate line frequency meter by reciprocal counting with Arduino. I am trying to print the the result on a 16*2 LCD but it is not displaying anything. It just gets on and stuck there. I got the project details from this website Line Frequency Meter Based On Reciprocal Counting

I modified the stock program to interface the LCD but it's not working. Here is the code I am using:

//To read and display the Line frequency
//using Reciprocal counting method
//clk for 'Time Counter'  is generated with 'Tone' function
//'Time counter' is the physical counter T1
// 'EVENT Counter' is a software counter
#define Fin 6      // input pin for Line freq sig
#define clk 7      // input to ' Time ' counter
#include<LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
boolean FState;   // status of the 50 Hz Signal
int countS;       // Signal count
int countC=0;     //  Clock count
int LineFreq;     // Result

void setup() {
  tone(8, 5000); // generates ref freq of 5000 Hz at Pin 8
  pinMode(Fin, INPUT); // set the Fin pin as INPUT
  pinMode(clk, INPUT); // set the clk pin as INPUT
  lcd.begin(16, 2);
}

void loop() {
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("Frequency of signal");
  // to avoid partial cycles, first detect the rising edge
  while(digitalRead(Fin)) {
    //wait for '0' state of the Signal
    delayMicroseconds(10);
  }
  //here '0' state
  while(!digitalRead(Fin)) {
    //wait for '1' state
    delayMicroseconds(10);
  }
  //this is the rising edge of the Fin
  //counting can start from here
  // clear the TIME Counter T1
  counterStart1();
  //count 50 of the Line freq signals
  while(countS<50) {
    while(digitalRead(Fin)) {
      //wait for '0' state
      delayMicroseconds(1);
    }
    //here '0' state
    while(!digitalRead(Fin)) {
      //wait for '1' state
      delayMicroseconds(1);
    }
    // here '1' state
    // here one cycle is just over
    //increment the event counter
    countS=countS+1;
  }
  //here 50 Signal cycles over
  // read the contents of T1 & compute frequency
  countC = getCount1();
  LineFreq = 25000000/countC;

  //send to display
  lcd.setCursor(0,1);
  lcd.print(LineFreq);
  lcd.print(" Hz");
  delay(500);
  delay(100);
  // clear counter
  countS=0;
  // repeat
}

//The following code is obtained from on-line articles in the public domain
void counterStart1() {
 // hardware counter setup,  for  the 16-bit Timer1 Timer/Counter
 TCCR1A=0; // reset timer/countern control register A
 TCCR1B=0; // reset timer/countern control register B
 TCNT1=0; // initialize the counter value to 0; this register holds the current count
  // set timer/counter1 hardware as a counter; it counts events on pin Tn (Arduino pin 5)
 TCCR1B = TCCR1B | 7; // Counter Clock source = pin Tn (Arduino pin 5) , start counting now
 // 7 in binary is 0111; OR-ing will set CS10,11,12 to 1's
return;
}

// the following code is obtained from on-line articles in the public domain
// Sub routine  to get the current count
unsigned int getCount1() {
 unsigned int count; // this variable returns the current count from the counting register
 TCCR1B = TCCR1B & ~7; // Gate Off  / Counter T1 stopped,
 // this operation clears the bits (CS10,11,12)
 count = TCNT1; // read the counting register
 TCCR1B = TCCR1B | 7; // re-start counting by resetting the bits (CS10,11,12)
 return count; // return the retrieved count to the calling function
}

I am getting a blank screen but the line at very first of the code "Frequency of signal" is printing accurately.

What is wrong with the code and what changes do I need?

Thanks in advance!

Your variables are int, which on an Arduino is a 2-byte signed type by default, and has a range of -32768 to 32767.

When you execute:

LineFreq = 25000000/countC;

is the result of the math a 2-byte int, or a 4-byte long? Regardless, you are possibly assigning a 4-byte value to an int.

You can declare LineFreq to be type long, and also append an L to the end of the constant value 25000000 to force long math, so that you have:

long LineFreq;
[...]
LineFreq = 25000000L/countC;


What is this temperature sensor module? (LM358, 103) I got this sensor some time ago because I wanted to play with measuring the temperature. I don't remember how I got it or if it has a name.

I've Googled around, and obviously is has the following

LM358 op amp
"103" thermistor

When googling for help I mostly find stuff about how to use the LM358 which is way above my skill level.

What is this and how do use it? :)

"103" is standard resistor (and other component) numbering - the first two digits specify a value and the third is a power-of-ten multiplier:

1 0 3 = 10 * 10^3 = 10K

4 7 2 = 47 * 10^2 = 4.7K

For devices that are typically measured in thousandths, millionths or smaller (like a capacitor) then the third digit is a minus power-of-ten:

1 0 6 = 10 * 10^-6 = 1u

That black disc labelled '103' is a thermistor - a temperature-controlled resistor. It is most likely NTC, or negative-temperature coeffiecient, thus the resistance decreases as the temperature increases. This is contrary to typical physics where an increase in the temperature of a generic conductive material results in an increase in its electrical resistance.

The LM358 is included to buffer the thermistor from the Arduino/microcontroller. In simple terms, this means that the effective resistance of the analogue input pin does not have to be taken into consideration when converting the voltage measured to into a value for the temperature.

Without a better picture of both sides of the board, or better yet a circuit diagram, it is not possible to determine what the voltage on pin S will be for a given temperature. However, it seems that the thermistor is in series with another 10K resistor (R3, marked '103' of course) such that an increase in temperature results in an increase in voltage. At roughly 20 degrees Celsius (it depends on the manufacturer and their specifications) the resistance of the thermistor will be 10K, thus the voltage at S will be Vcc/2. Calculating the voltage for different temperatures requires you to know the temperature coefficient, which can be found from the datasheet or by measuring the resistance at various known temperatures and plugging those values into an equation.


How do powering arduino both barrel jack and lipo battery together? I have arduino mega and Lipo batterry such this and Lipo battery charger 5V USB Boost. I am powering arduino normally from barrel Jack with an 9 Volt adaptor. But if there is power cut occur, I dont want to stop, I want powering arduino with Lipo battery. After power come back, arduino contunie to powering from barrel jack again at the same time battery start to charge. How can I succes this. Do you have any sample circuit?
After Majenko♦ comment, I've tried circuit but there is heating problem occur. More then 70 celsius. Is that normal?
Circuit

Termal Circuit

As is described in this post from the arduino forum, There is a MOSFET switch in series with the USB connector +5V input line.  If the battery booster 5V output is connected to the USB input jack, then it will automatically power the UNO whenever power is disconnected from the barrel jack, and will be automatically disconnected whenever at least 7.0V is available at the barrel jack.
If you are experiencing over-heating problems, then you are probably overheating the linear regulator that steps down the barrel jack voltage to 5V.  You need about 7-7.5V at the barrel jack to overcome the 2-2.5V loss through the linear regulator, but anything higher than about 7.5V will just cause the linear regulator to get hotter.


Can Serial be safely used in an SPI interrupt routine I have anecdotal experience that using Serial.print inside a slave's SPI interrupt routine (ISR) causes issues with transmission. It also seems that interrupts may be called more than once before the main loop can react, so it is difficult to print info from all interrupts. Is this because Serial is inherently unsafe, or too slow? Can Serial be used safely inside the ISR routine?

Serial should be avoided in ISRs because interrupts are disabled inside ISRs, and Serial transmission uses interrupts to operate. Better to have the ISR set a flag that is read in the next iteration of loop() to print the desired info.


Can i use arduino code, without using arduino board but just using MCU included I am developing a product, and to ease my job i am planning to use MCU inside the arduino with the library of Arduino.

Since all the registers are already defined inside the library, and all required things to registers of corresponding MCU are done to "make a pin input/output , enable interrupt , enable UART , enable I2C". I think that i can directly use the arduino coding enviroment even if i use MCU seperately.

Is it possible and how?  (can i use it in commertial product, i have already prototyped it with arduino)

Yes, you can. Once you have a .hex file for a specific MCU and environment you can use a programmer to upload it to a discrete MCU.


How to I press a button once to display text and again to remove it? My code is displaying voltage and I want to have a button that when pressed it displays a text and when I pressed it again it would turn off the text. I put the word "YES" just for a test

float vPow = 4.7;
float r1 = 1000000;
float r2 = 100000;
const int buttonPin = 8;
int buttonState = 0;
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
  lcd.begin(16, 2);
  pinMode(buttonPin, INPUT);
  Serial.begin(100);
}

void loop() {
  float v = (analogRead(0) * vPow) / 1024.0;
  float v2 = (v / (r2 / (r1 + r2)))/.48;
  lcd.setCursor(0,0);
  lcd.print("V:");Serial.println(v2); lcd.print(v2); lcd.print("%");delay(100);
  buttonState = digitalRead(buttonPin);
  if (buttonState == HIGH) {
    lcd.setCursor(0,1); lcd.print("YES");
  } else {
    lcd.setCursor(0,1); lcd.print("");
  }
}

You need to somehow debounce the button. Using a long delay in the loop
(your delay(100)) can do the trick, but it's probably not the best
way, as it will slow down anything that you may later add to your
program.

Better would be to write your own debounce function, or to use one of
the libraries that already implement that. For example, with
Bounce2, you would write
something like:

#include <Bounce2.h>

const int buttonPin = 8;
Bounce button;       // debounced button
bool textDisplayed;  // whether the text is displayed or not

void setup()
{
    button.attach(buttonPin, INPUT);

    // etc...
}

void loop()
{
    // Read and display the analog value, then...

    // Update the state of the debounced button.
    button.update();

    // Toggle display on rising edges of the button.
    if (button.rose()) {
        lcd.setCursor(0,1);
        if (textDisplayed) {
            lcd.print("   ");
            textDisplayed = false;
        } else {
            lcd.print("YES");
            textDisplayed = true;
        }
    }
}


How do I connect 4 or more Arduinos to a single shared GSM Module? Is it possible to connect 4 or more Arduinos to a single GSM Module.?
All the Arduinos need to send SMS at a specific time daily.
How do I make sure thet don't time collide with each other, other than sending sms at different times for each Arduino?.
I want the SMS to be queued up, and be sent one by one.

You should consider connecting one Arduino to the GSM module, and connect the 4 Arduinos together using SPI, I2C, or any other inter-hardware comms protocol. Before I knew these options existed, I once wrote a bit of code to send data between Arduinos by having one pin represent the data being sent and another pin changing every time a new bit was available. You could do something similar with an extra line per pairing, so an Arduino could tell the primary that it had new data to send.
Anyway, check out the "Wire Library" - it's basically for this kind of work. I think you'll be happier trying to have one Arduino "in charge" and connected to the CSM while the rest vie for its attention.


C++ Namespace/scope problem when trying to attach arduino interrupt I have defined a c++ class (RpmDriver) and want to use attachInterrupt in the constructor to link an Arduino pin to its ISR (RpmInt) in the class. When I try this, I get:

error: cannot convert 'RpmDriver::RPMInt' from type 'void (RpmDriver::)()' to type 'void (*)()'

This is the cpp file:

#include "RpmDriver.h"
#include <Arduino.h>
int currentRpm;
long lastMillis;
int pin;

RpmDriver::RpmDriver(int Pins[])
{
    pin=Pins[0];
    currentRpm=0;
    pinMode(pin,INPUT);
    lastMillis = millis();
    attachInterrupt(digitalPinToInterrupt(pin),RPMInt, RISING);
}
RpmDriver::~RpmDriver(void)
{}

bool RpmDriver::GetData(char* dest,char* format)
{
    sprintf(dest,format,currentRpm);
}

void RpmDriver::RPMInt()
{
    double RPMConstant=40000;
    unsigned long newMillis=millis();
    unsigned long t = newMillis-lastMillis;
    t=100;//temp
    currentRpm=(t==0)?0:(int)RPMConstant/t;
    lastMillis=newMillis;
}

and the header file is

#pragma once
class RpmDriver
{
public:
    RpmDriver(int pins[]);
    ~RpmDriver(void);
    bool GetData(char*,char*);
private:
    void RPMInt(void);
};

Any help much appreciated!

You can't.

Simply because a class member is not the right format of function for attachInterrupt.

You can only use normal functions with attachInterrupt, so the normal method is to have a normal function outside your class which then calls the member function within your class.  How you arrange it so that it knows where your objects are is up to you.

If you have only one object then assign it to a global pointer in your library using the constructor
If you have lots of instances then create a linked list within your class in a static context and add each object to it in the constructor, then iterate through that list when the interrupt fires.


Programing a Mini 05 without a USB-to-serial converter I have an Arduino Mini 05 clone Wattuino, an Elegoo Mega, a Powerboost 1000c, but not access to a USB-to-serial converter. Is there any way to program the Arduino Mini with these devices?

I tried to search it but they only mention using an Arduino uno as the chip can be put out of the board. Discusion

You can use the Mega. The only reason for "removing the chip from the board" is to disable it so it doesn't respond to the serial data - you can also disable it by just connecting the RESET pin to GND.


How can I have two Arduino Uno's communicate wirelessly? I'm an art student, using arduino in an Electronic Arts Class.  I have already created a skateboard speedometer, using a Hall Effect Sensor and a magnet embedded in one of my skateboards wheels.  I've attached a speaker to the arduino that plays a tone, with the pitch depending on the RPM's of the wheel.  (the faster the board is going, the higher pitch the tone being played is).  Currently the speaker is attached to the skateboard and wired directly to the arduino.  My goal is to have a speaker with an arduino wirelessly connected to the arduino on the skateboard.  The arduino on the skateboard record's the RPM's and then wirelessly send that information to the second arduino to play the tone through the speaker.  Is this possible? what hardware would yo recommend? I've been looking at the Bluetooth HC-05 but I'm not sure this will work.  Thanks for any help!

ESP8266 is also a good choice. these little guys are really useful and give you a Wi-Fi connection between your Arduino boards.

Also, the cost of one ESP8266 is about $3.. super cheap!


Stop time in Tkinter Stopwatch with a PushButton So, my main goal is to make a stopwatch with Tkinter, in which time is stoppped with an external pushbutton

My void loop function in Arduino Uno is

void loop() {

if(digitalRead(BUTTON) == HIGH){
    Serial.print("E\n");
digitalWrite(LED, HIGH);

while(1){

 if(digitalRead(BUTTON) == HIGH){
  continue;
  }

if(digitalRead(BUTTON) == LOW){
break;}

        }
                               }

}

Basically, whenever the pushbutton is pressed I send via serial the message "E\n" and the arduino enters in an infinte loop that only breaks when the pushbutton stops being pressed (to avoid sending more than one message).

Then I have my Python code that reads the serial through the serial.readline() function.

Part of my Python code is (remember that i'm making a stopwatch and time is appearing in the screen - variable timer[i] is what saves the second and the ms):

def update_timeText():
    if (state):
       global timer
       # Every time this function is called,
       # it increments 1/100 of a second
       timer[1] += 1

      # Every 100 centisecond is equal to 1 second
       if (timer[1] >= 100):
           timer[1] = 0
           timer[0] += 1

       if arduino.readline() == 'E\n':
           print("FLAG\n")

       # TIME STRING
       timeString = pattern.format(timer[0], timer[1])

       # UPTADE THE LABEL WITH TIME STRING
       timeText.configure(text=timeString)

   # Call the update_timeText() function after 1 centisecond
   root.after(10, update_timeText)

The variable state goes True whenever I start the stopwatch (via a Tkinter button, but that's irrelevant for this case).

My problem, is that the program stops in the line

if arduino.readline() == 'E\n':

i.e., it only continues if I press the pushbutton. What I think that is happening, is that the .readline() continues waiting and waiting until it receives the message 'E\n'... I've tried with the .readline.strip() and also only .read() but none of them worked.

It is though very strange, because if the condition in front of If is not verified, it should just continue...

Any suggestion?

In the pyserial docs it states this:

  Be careful when using readline(). Do specify a timeout when opening the serial port otherwise it could block forever if no newline character is received. Also note that readlines() only works with a timeout. readlines() depends on having a timeout and interprets that as EOF (end of file). It raises an exception if the port is not opened correctly.

You need to specify the timeout and the end of line string. Try using this  modified line:

if arduino.readline(eol='\n') == 'E\n':

Also, add the timeout option where you define arduino as a pyserial object. For example:

arduino = pyserial.serial(port,baud,timeout=t,etc...)


Transmitting Variables over RF I'm using the 3715 RF arduino modules and a hc-sr04, and i'm trying to send the distance i get from the ultrasonic over to the arduino with the rf recieving module but i get something like this:

Instead of getting this:

Here are the code snippets for each arduino:

Arduino TX:

#include <VirtualWire.h>

const int led_pin = 11;
const int transmit_pin = 12;
const int receive_pin = 2;
const int transmit_en_pin = 3;
long distance;
long time1;
void setup()
{
   // Initialise the IO and ISR
   Serial.begin(9600);
   pinMode(9, OUTPUT);
   pinMode(8, INPUT);
   vw_set_tx_pin(transmit_pin);
   vw_set_rx_pin(receive_pin);
   vw_set_ptt_pin(transmit_en_pin);
   vw_set_ptt_inverted(true); // Required for DR3100
   vw_setup(2000);   // Bits per sec
}

byte count = 1;

void loop()
{
   digitalWrite(9,LOW);
   delayMicroseconds(5);
   digitalWrite(9, HIGH);
   delayMicroseconds(10);
   time1=pulseIn(8, HIGH);
   distance= int(0.017*time1);
   Serial.println("Distance ");
   Serial.println(distance);
   Serial.println(" cm");
   delay(1000);
   char msg[1] = {distance};

   msg[0] = count;
   digitalWrite(led_pin, HIGH); // Flash a light to show transmitting
   vw_send((uint8_t *)msg, 3);
   vw_wait_tx(); // Wait until the whole message is gone
   digitalWrite(led_pin, LOW);
   delay(1000);

}

Arduino RX:

#include <VirtualWire.h>

const int led_pin = 6;
const int transmit_pin = 12;
const int receive_pin = 11;
const int transmit_en_pin = 3;

void setup()
{
   delay(1000);
   Serial.begin(9600);  // Debugging only
   Serial.println("setup");

   // Initialise the IO and ISR
   vw_set_tx_pin(transmit_pin);
   vw_set_rx_pin(receive_pin);
   vw_set_ptt_pin(transmit_en_pin);
   vw_set_ptt_inverted(true); // Required for DR3100
   vw_setup(2000);  // Bits per sec

   vw_rx_start();       // Start the receiver PLL running
}

void loop()
{
   uint8_t buf[VW_MAX_MESSAGE_LEN];
   uint8_t buflen = VW_MAX_MESSAGE_LEN;

   if (vw_get_message(buf, &buflen)) // Non-blocking
   {
      int i;

      digitalWrite(led_pin, HIGH); // Flash a light to show received good message
      // Message with a good checksum received, print it.
      Serial.print("Got: ");

      for (i = 0; i < buflen; i++)
      {
         Serial.print(buf[i], HEX);
         Serial.print(' ');
      }
      Serial.println();
      digitalWrite(led_pin, LOW);
   }
}

I'm open for pointers as i'm pretty much a noob at this, thank you very much for your help! :)

It looks like you're sending only one byte, but expecting to receive three.
In the TX sketch, char msg[1] = {distance}; declares an array of one char, assigns its zero-th element the value of distance. Then msg[0] = count; over-writes it with the value of count. vw_send((uint8_t *)msg, 3); tries to send three bytes but only the first one has been defined. The second and third bytes transmitted are outside of the 1-length array.

You need something more like:

vw_send(distance, sizeof(distance));

on the TX side, and:

long distance;
uint8_t count;

vw_get_message(distance, &count));
Serial.println(distance);

on the RX side. You must receive the count into a variable but can ignore it, on the RX side; you know you'll be receiving a long; though good defensive coding would check the value anyway.


LEDs Randomly smooth transitioning, accounting for black or how-to switch using HSV I am stuck trying to get it not to account for black in RGB.  My first instinct was to use the HSV color spectrum over the RGB rainbow but, the same code will behaves differently in HSV.  If i could get the same effect in HSV I would, and that would account for the black, but I have not found a solution for that or the accounting for black in RGB.  Here is my code:

#include <FastLED.h>

#define LED_COUNT     96
#define LED_OUT       13
#define BUTTON_IN     10
#define ANALOG_INPUT  A9
#define EXTRA_PIN_A    7
#define EXTRA_PIN_B   11

struct CRGB leds[LED_COUNT];

void setup() {
  Serial.begin(57600);
  LEDS.addLeds<WS2812B, LED_OUT, GRB>(leds, LED_COUNT);
  LEDS.show();
}

void colorLoop() {

  static int Col1;
  static int Col2;
  static int Col3;

  static int C1;
  static int C2;
  static int C3;

  if ((((Col1 == 0) || (Col1 == 250)) && (((Col2 == 0) || (Col2 == 250)) && ((Col3 == 0) || (Col3 == 250))))) {

    // select a random number from 1 to 2 for the array
    C1 = random(1, 3);
    C2 = random(1, 3);
    C3 = random(1, 3);
  }

  if (((C1 == 1) && (Col1 != 0))) {
    Col1 = (Col1 - 10);
  }
  if (((C2 == 1) && (Col2 != 0))) {
    Col2 = (Col2 - 10);
  }
  if (((C3 == 1) && (Col3 != 0))) {
    Col3 = (Col3 - 10);
  }

  if (((C1 == 2) && (Col1 != 250))) {
    Col1 = (Col1 + 10);
  }
  if (((C2 == 2) && (Col2 != 250))) {
    Col2 = (Col2 + 10);
  }
  if (((C3 == 2) && (Col3 != 250))) {
    Col3 = (Col3 + 10);
  }

  for (uint8_t i = 0; i < LED_COUNT; i++) {
    leds[i] = CRGB(Col1, Col2, Col3);
  }
  delay(100);
  LEDS.show();
}

void loop() {
  colorLoop();
}

Black will basically be when all the colours have reduced to 0. That can only happen when all three of C1, C2 and C3 are 1. So you basically need to ensure that never happens.

And that is simple enough to arrange, with a "try again" construct:

if ((((Col1 == 0) || (Col1 == 250)) && (((Col2 == 0) || (Col2 == 250)) && ((Col3 == 0) || (Col3 == 250))))) {

    // select a random number from 1 to 2 for the C1,C2,C3 array
    do {
        C1 = random(1, 3);
        C2 = random(1, 3);
        C3 = random(1, 3);
    } while ((C1 == 1) && (C2 == 1) && (C3 == 1));
}

Pick three numbers. If they are all 1 then you are destined towards black. So go back and pick three new random numbers. Keep trying until you get at least one result that isn't 1.


Ethernet to Cellular Modem Possible? | GSM + Ethernet + Arduino Is it possible to combine an Arduino µC with a GSM shield and an ethernet shield such that a device connected via ethernet to the Arduino has internet access over the GSM network?

I have a system with an ethernet port to connect to the internet. It works fine if I plug it into my switch at home. However, I would like this system to have its own cellular internet connection.

This is what I have found so far:

I'm basically trying to replicate the following:
https://nimbelink.com/e2clink-ethernet2cellular/#parts
If the following reddit post:
https://www.reddit.com/r/arduino/comments/3azxs6/create_gsm_cellular_ethernet_modem_with_arduino/
is any indication, I would think the answer is "no" but I am hoping to confirm from the expertise available here.

No, it's not possible.

Chiefly because the normal Ethernet shield is not capable of routing.  The Arduino never talks to the ethernet - it talks to the chip on the shield and tells it how to handle the ethernet connection - everything else is then done by the ethernet chip and the results passed back to the Arduino.

Similarly with GSM - you make requests to it and it goes off and does the work.

To link the two together you would need raw access to the incoming ethernet packets, and you would then have to perform NAT (Network Address Translation) and maintain internal state tables for current streams and such, and pass reformatted packets on to a GSM modem that could accept raw data like that.

Way outside the scope of a lowly Arduino.

Maybe possible with one of the higher end Arduino-ish systems like the Edison, Galileo or Yun (just) since they run Linux and have a real Ethernet port and a proper USB port to communicate with a proper celular modem.


snprintf crashing my program I have to admit that I can't really use this function.

I'm trying to format some json but it crashing all the time my arduino:

char response[300];
tmp = "123";
snprintf(response, 300, "[{Name:'Furnace',Value=%s,Alarm={MinValue=%s,MaxValue=%s}},{Name:'Room',Value=%s,Alarm={MinValue=%s,MaxValue=%s}}]", tmp);

How should I use this function properly?

char response[300];
tmp = "123";
snprintf(response, 300,
    "[{Name:'Furnace',Value=%s,Alarm={MinValue=%s,MaxValue=%s}},"
    "{Name:'Room',Value=%s,Alarm={MinValue=%s,MaxValue=%s}}]",
    tmp, tmp, tmp, tmp, tmp, tmp);

In other words, you should add, after the format string, as many extra
parameters as there are %s in the format string.

PS: This looks like JSON, but it is not really valid JSON.
The format below should give valid JSON:

"[{\"Name\":\"Furnace\",\"Value\":%s,"
"\"Alarm\":{\"MinValue\":%s,\"MaxValue\":%s}},"
"{\"Name\":\"Room\",\"Value\":%s,"
"\"Alarm\":{\"MinValue\":%s,\"MaxValue\":%s}}]",


What is the difference between a motor driver and a motor shield? what is the difference between a motor driver(like L293D) and a motor shield?

what are the advantage?disadvantages of both?

And which one do you suggest ?

A motor driver is a chip that drives motors.  A motor shield is a circuit board with connections on it that contains a motor driver chip that drives motors.

A shield is convenient since you can just plug it in to your Arduino and wire the motors direct to it, but it lacks the flexibility of a raw driver chip which you can wire up precisely as your project demands.


Is it safe to feed 5v dc 1amp to an Arduino uno R3 board? Is it safe to feed 5v dc 1amp to an Arduino uno board?

Yes as long as the polarity is correct, the board will only take the current it requires


Arduino Uno R3 not recognized by computer, TX and RX not blinking, neither are lit. Is it dead? I was trying to make my arduino uno r3 to work on my Linux machine (including the IDE), but it wouldn't. At first I thought it was a software problem. Added myself to different groups and did everything, people discussed on the forums. It didn't work. It wasn't recognized by the computer at all. I reinstalled. Nothing again. Thought it was a hardware problem of my computer. Tried with dad's (Windows 7 machine). Didn't work. Then I saw that the two leds (TX and RX) are not blinking, neither are lit. I started doing a research on the internet but everybody suggests doing the loopback test from the IDE. My Arduino Uno R3 is not recognized by the computer, therefore the IDE. Is there any way to check if it's dead or if it's a minor problem?

Edit: I read a lot on the case last night and I reach to the conclusion that my ATmega16u2 (the usb-serial chip, I'm sure it is 16u2 and not 8u2, it's written on the chip itself) might be dead. Tried to reflash the firmware but cannot get it in DFU mode (as it says in this article click here). dfu-programmer (the Linux application) throws the following error: dfu-programmer: no device present. What to do?

There is a chance that your bootloader is not working anymore. You can burn a new bootloader to the device with another Uno, there are nice guides on the Arduino-Website.


Irregularly triggering an ISR using timers I seek to call an ISR routine after a fixed time of 400us. This action needs to be done every now and then (in the range of 0.8-3.0ms). For that matter, I thought I'd set timer2 to CTC mode, use OCR2A to set some TOP value for 400us and let the timer call the ISR routine after 400us. Within the ISR I would then stop the timer from triggering interrupts, until I need to count to 400us again, where I would activate the timer interrupt again.

This works, as expected, except for the fact, that after activating the interrupt for OCR2A again, it instantly triggers. The code below, produces a 1ms alternating signal, instead of 1ms+400us.

My question is, am I on a good way with this, or should I use the overflow ISR and preload the timer? Or any other method? The problem is, that after the 1ms waiting time in the main loop, I'd expect the counter to count from 0 to 100, meaning 400us. However on an oscilloscope I see the pin toggle each 1ms.

uint32_t timestamp;

void setup() {
  Serial.begin(115200);
  pinMode(9, OUTPUT);
  cli();         // disable global interrupts
  // Timer2 for counting (to release the pin)
  TCCR2A |= (1 << WGM21); // CTC mode, clear timer on compare match
  TCCR2B |= (1 << CS22); // Prescalar 64

  OCR2A = 99; // ticks, before ISR is called
  TIMSK2 |= (1 << OCIE2A); // enable timer compare interrupt
  TCNT2 = 0x00; // set the timer to 0
  // counting time[s] = (OCR+1)/(F_cpu/prescalar)
  // 99 = 400us | 124 = 500us
  sei(); // enable global interrups
  timestamp = micros();
}

void loop() {
  uint32_t now = micros();
  if (now - timestamp > 1000) {
    timestamp = now;
    cli();
    TIMSK2 |= (1 << OCIE2A); // enable timer compare interrupt
    sei();
    TCNT2 = 0x00;
  }
}

ISR(TIMER2_COMPA_vect) {
  // Serial.print(F("Here\n"));
  PORTB ^= 2; // set pin 9 high again
  // TCNT2 = 0x00; // reset timer for testing
  // deactivate the counter
   cli();
   TIMSK2 = 0x00; // unlink the ISR from timer
   sei();
}

However on an oscilloscope I see the pin toggle each 1ms.

That's what you expect. You set up the timer to fire every 1 ms. Since the ISR is called some time after that (and that is what toggles the pin) you will see the pin toggle every 1 ms.

I've reworked your example a bit to make it clearer, and to toggle the pin when we start the timer, and again when the ISR fires:

uint32_t timestamp;

void setup()
  {
  pinMode(9, OUTPUT);
  // Timer2 for counting
  TCCR2A = bit (WGM21); // CTC mode, clear timer on compare match
  OCR2A = 99;           // ticks, before ISR is called

  // counting time[s] = (OCR+1)/(F_cpu/prescalar)
  // 99 = 400us | 124 = 500us
  timestamp = micros();
  }  // end of seupt

void loop()
{
  uint32_t now = micros();
  if (now - timestamp >= 1000)
    {
    timestamp = now;
    TIFR2 = bit (OCF2A);   // clear any pending interrupt
    TCNT2 = 0;             // make sure counter is zero
    TIMSK2 = bit (OCIE2A); // enable timer compare interrupt
    TCCR2B = bit (CS22);   // start timer: Prescalar 64
    PINB = bit (1);        // toggle pin 9
    }  // end of if
}  // end of loop

ISR(TIMER2_COMPA_vect)
{
  PINB = bit (1); // toggle pin 9
  TCCR2B = 0;     // stop timer
}  // end of TIMER2_COMPA_vect

You can see from the scope output that the timer is started every 1 ms (as expected) because Cursor 1 is at -1 ms. The width of the pulse is 400 µs, as expected.

  In my example I do not have to set so many settings each time I want to start the timer.

I took out the cli and sei so I saved you two lines. Don't forget to count them!

If you leave the timer running, it may well have reached the counter again (even though not generating an interrupt). Thus this line is important (even more so for you):

TIFR2 = bit (OCF2A);   // clear any pending interrupt

Also, if you leave the timer running, you may have a race condition. Say the timer is just about to tick over and generate the interrupt. You clear the flag (as shown above), but one machine cycle later the timer reaches the counter and sets it again, just before you get a chance to zero it. With the timer running, there could be combinations of when you enable interrupts, zero the flag, and clear the pending interrupt flag, that could occasionally work against you. Having the timer stopped is much safer.

Now if you are worried about the number of lines you need to start it (I wouldn't be) then you can move this line into setup:

TIMSK2 = bit (OCIE2A); // enable timer compare interrupt

Since you stop the timer in the ISR it doesn't matter if the interrupt is still enabled. Now you just have three lines to start the timer:

TIFR2 = bit (OCF2A);  // clear any pending interrupt
TCNT2 = 0;            // make sure timer is zeroed
TCCR2B = bit (CS22);  // start timer: Prescalar 64

I think we've agreed that clearing the compare flag is important, so this isn't any lengthier.

  looking at your divisioning of the time axis, and from code, it is clear, that there is a 600us break, not 1ms!

Yes, there's a 600 µs break, because you start the timer every 1 ms, and it runs for 400 µs, thus there will be a 600 µs break.

  I seek to call an ISR routine after a fixed time of 400us.

That's exactly what my posted code does. The pin goes high at the time you desire, in loop, and it goes low 400 µs later. That's what you wanted: a 400 µs interval.


possible to preform VIO from two cameras/imu's on a dual-core esp32? Like the title says, I want to take in the synchronised data from two NXP breakout boards and two Ueye 1220LE Cameras, and use VIO to fuse their data and get positions for both setups. Alot of people have suggested running things like SLAM, which is simmilar to VIO, on something stronger than an arduino, some specifically suggested using a version of a raspi.

Now, I know that raspi's are stronger than an esp-32, but esp-32's are stronger than arduino's, and since raspi's are more expensive than an esp-32 and I need wifi capabilities, before I bought a raspi, I was wondering If it would be possible to preform this on my dual core esp-32. And if the raspi wasnt overkill and I needed all the processing power I could get, what version should I use? the zero? The 3.0? The 4.0? Do let me know. Thank you all. =)

I haven't worked with the ESP-32, but it seems to me you're quibbling over pennies. Pis are cheap and very powerful. They run Linux, so there are tons of open source libraries available for them. You could install OpenCV, for example, and do computer vision quite readily.

I'd recommend at least a PI 3.

If you used an ESP-32 based system, would you run it as an Android device? Android's "OS" (And that the term OS is quite a stretch) is really just a setup function and a run loop. You should use a device with a real OS, including a file system, etc.


Adafruit GPS module with SoftwareSerial affecting servo signals I'm having a bit of an odd problem here. I'm programming a self-built quadcopter using an Arduino Uno for control. One of the sensor's that I'm using is Adafruit's GPS breakout. The motors are controlled with electronic speed controllers (ESCs) that controlled identically to normal servo motors. Everything is connected together with a custom Arduino shield. The GPS is using SoftwareSerial on pins 3 and 4, and the ESCs are connected on pins 5-8. Most of the GPS code is directly copied from Adafruit's documentation.

What I've found is that even when the throttle is held steady (at any power level), the motors experience quick bursts of power far beyond normal whenever there is communication between the GPS module and the Arduino. For example, the GPS updates on 1Hz intervals and so the motors get a burst of speed about every second. Has anyone else experienced something like this or could someone at least point me in the right direction?

Here's an abbreviated version of the code that I'm currently using:

#include <Servo.h>
#include <Wire.h>
#include <Adafruit_GPS.h>
#include <SoftwareSerial.h>

Servo ESC1;
Servo ESC2;
Servo ESC3;
Servo ESC4;
const int maxThrottle = 2000;
const int minThrottle = 1000;

SoftwareSerial softwareSerial(4, 3);
Adafruit_GPS GPS(&softwareSerial);
// Set GPSECHO to 'false' to turn off echoing the GPS data to the Serial console
// Set to 'true' if you want to debug and listen to the raw GPS sentences.
#define GPSECHO false
bool usingInterrupt = false;
uint32_t timer = millis();

void setup() {
    ESC1.attach(5);
    ESC2.attach(8);
    ESC3.attach(6);
    ESC4.attach(7);
    setThrottleAll(minThrottle);

    GPS.begin(9600);
    GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA);
    GPS.sendCommand(PMTK_SET_NMEA_UPDATE_1HZ);
    GPS.sendCommand(PGCMD_ANTENNA);
    useInterrupt(true);
}
int throttleCommand = 20;
void loop() {
    // Map throttle command percentage to raw throttle values that are sent to the ESCs
    int throttle = map(throttleCommand, 0, 100, minThrottle, maxThrottle);
    setThrottle(1, throttle);
    setThrottle(2, throttle);
    setThrottle(3, throttle);
    setThrottle(4, throttle);
}

// GPS interrupt
SIGNAL(TIMER0_COMPA_vect) {
    char c = GPS.read();
    // if you want to debug, this is a good time to do it!
    #ifdef UDR0
        if (GPSECHO)
            if (c) UDR0 = c;
                // writing direct to UDR0 is much much faster than Serial.print
                // but only one character can be written at a time.
    #endif
}
void useInterrupt(boolean v) {
    if (v) {
        // Timer0 is already used for millis() - we'll just interrupt somewhere
        // in the middle and call the "Compare A" function above
        OCR0A = 0xAF;
        TIMSK0 |= _BV(OCIE0A);
        usingInterrupt = true;
    }
    else {
        // do not call the interrupt function COMPA anymore
        TIMSK0 &= ~_BV(OCIE0A);
        usingInterrupt = false;
    }
}

void setThrottleAll(int throttle) {
    setThrottle(1, throttle);
    setThrottle(2, throttle);
    setThrottle(3, throttle);
    setThrottle(4, throttle);
}
void setThrottle(int index, int throttle) {
    if (index == 1)
        ESC1.writeMicroseconds(throttle);
    if (index == 2)
        ESC2.writeMicroseconds(throttle);
    if (index == 3)
        ESC3.writeMicroseconds(throttle);
    if (index == 4)
        ESC4.writeMicroseconds(throttle);
}

The bad news is that you are using the absolute worst libraries (SoftwareSerial and Adafruit_GPS), and your program structure is based on the awful Adafruit_GPS example.

The good news is that there are much better alternatives: NeoSWSerial and NeoGPS.  Still, there's no doubt that you are near the limits of this processor, especially with Wire and timer-based Servos.  It can be an "interesting challenge" or a "beginner's nightmare."

Suggestions:

1) Consider using the HardwareSerial object, Serial, for the GPS interface.  Your excerpt does not show what Serial is currently used for, but if it's debug print statements... don't.  Instead, use a software serial port for debug statements (use a serial-to-USB adapter on those pins to connect it to your PC).  This would have a tremendous impact.

2) If you really really can't use Serial for the GPS (are you sure???), consider using an AltSoftSerial instance on pins 8 & 9, as this is much better than the dreaded SoftwareSerial.  Next best is NeoSWSerial on any pins, including 4&3 that you are using now.  There is absolutely no reason to shoot yourself in the foot with SoftwareSerial.

3) As other's have commented, use HW PWM... let the machine do the work for you.

4) Consider using the faster and smaller NeoGPS library.  And restructure your program to look like the NeoGPS example programs, because their sequencing is much more efficient.  The Adafruit_GPS example uses a timer interrupt... to read a character from the input buffer... that was stored by a SoftwareSerial interrupt... that was on for the entire character time of ~1ms.  What a phenomenal waste!

5) Use interrupt-driven GPS parsing.  All three Neo__Serial libraries (HW, IC and SW) allow NeoGPS to handle the GPS characters during the rx interrupt, avoiding character loss because the port was not read in time (input buffer overflow).  And because just a little work is performed on each character, there is no big chunk of processing when a sentence is complete.  This also uses half the interrupts and saves copying the characters multiple times, in and out of the serial input buffer... into the Adafruit double-buffered sentences, where it gets searched multiple times with strcmp and strchr.  Ugh.  No, I meant to say UGH!

6) NeoGPS will also free up hundreds of bytes of RAM, which you may be able to trade for some more speed, elsewhere.

It's definitely a tight squeeze.  Either reallocate your pins and use better libraries, or get a bigger hammer.      :-)


User input for utility program I am writing a utility program to test relay boards. I'd like to be able to accept a user input of the number of relays on the board. Is this doable via the serial monitor since when I'm testing boards I'm generally doing it at my desk with my testing Arduino attached to my laptop? I'd prefer not to go the LCD and keypad route.

Is there an accepted practice for doing this?

Yes, it is perfectly do-able through the serial monitor.  However the serial monitor is very very basic and you will be able to create a much better user experience using a proper serial terminal emulator (such as TeraTerm, Putty, etc) and using ANSI control codes to lay the screen out as a proper text-based application.

A useful resource is on Wikipedia: https://en.wikipedia.org/wiki/ANSI_escape_code

I have a little library that I started a while back and never finished that performs two basic ANSI control sequences - clear screen and set cursor. You can look at it to see how to perform ANSI control codes: https://github.com/MajenkoLibraries/ANSI


Why can't I declare a class in another tab in Arduino IDE? I wanted to move some of my code out into a second tab in the Arduino IDE, to keep things better organised. At first, I only tried moving a function, and it seemed to work fine. I could call the function from the setup() function in my main tab, and there were no problems compiling or uploading.

However, I tried putting a whole class into the second tab, and suddenly it didn't work any more. For example:

Tab 1:

TestClass obj;

void setup()
{
    obj.init();
}

void loop()
{
    //...
}

Tab 2:

class TestClass
{
public:
    void init()
    {
        //...
    }
};

When I tried to compile this, it gave me the following errors:

tab1:1: error: 'TestClass' does not name a type
tab1.ino: In function 'void setup()':
tab1:5: error: 'obj' was not declared in this scope

Why does it recognise a function in another tab, but not a class? Is there a way to make it work in the Arduino IDE, or do I need to use an alternative like Eclipse?

It is not possible to declare and use classes declared in one .pde file in another .pde file from within the Arduino IDE.

One workaround is to make the second file into a C++ source file (.cpp) and then add a #include "<filename>" directive in the beginning of the first file.

This code compiles correctly:

Tab 1:

#include "test.cpp"

TestClass obj;

void setup()
{
    obj.init();
}

void loop()
{
    //...
}

test.cpp :

class TestClass
{
public:
    void init()
    {
        //...
    }
};


Button for Delay Select My target is to make an Arduino system that is able to change modes with different delays by pushing a button. For example, if I pressed the button, it will go into mode 1 with loop 1 that has a 30s delay. If I pressed it one more time, it will go to mode 2 with with loop 2 that has a 1 min delay, etc. The important thing is that mode 1 should be breaked when the push button pressed.

The code below solved part of the problem. However, LEDs are only constant ON, they are not blinking for a certain time then it turned either on-off within the mode when the push button pressed.

int b =3;int rl= 5;int gl=6;
int yl=7; int s=0; int o=0;
 int bp =0;

void setup() {
  // put your setup code here, to run once:
pinMode(b,INPUT);
pinMode(rl,OUTPUT);
pinMode(gl,OUTPUT);
pinMode(yl,OUTPUT);

 digitalWrite(rl,LOW);
digitalWrite(gl,LOW);
digitalWrite(yl,LOW);
}

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

bp=digitalRead(b);
if (bp==1){
  delay(50);
  bp=digitalRead(b);
  if (bp==0){
    s=o+1;}}
    else{
      delay(100);}
      switch(s){
        case 1:
        digitalWrite(rl,HIGH);
digitalWrite(gl,LOW);
digitalWrite(yl,LOW);
o=s;
break;

case 2 :
digitalWrite(rl,LOW);
digitalWrite(gl,HIGH);
digitalWrite(yl,LOW);
o=s;
break;

case 3:

digitalWrite(rl,LOW);
digitalWrite(gl,LOW);
digitalWrite(yl,HIGH);
o=s;
break;
default:

digitalWrite(rl,LOW);
digitalWrite(gl,LOW);
digitalWrite(yl,LOW);
o=0;
break;}}

S1 is responsible to activate D12 to be constant ON (when it’s pressed once) which lead UNO2 to be powered then blink the right LED ON (1min) OFF(4Hr), (pressing it twice should turn D12 OFF (optional)). The same thing with S2, when it’s pressed once it should first disable D12 and activate D11 instead, powering UNO3, blinking the left LED ON(30S), OFF (4Hr).

In addition, blinking on() off() repeatedly is needed (unless action break/occur, ex: pressing S1 or S2).

About S1 and S2. The LED on D12 will flash ON for 1 minute then turn off for 4 hours. After the 4 hours, the LED on D12 will flash ON again for 1 min then turn off for 4 hours again & again...as an infinite loop. With S2 The LED on D11 will flash ON for 30 seconds then turn off for 4 hours. After the 4 hours, the LED On D11 will flash ON again for 30 s then turn off for 4 hours again and again as an infinite loop.

Do not use delay but millis().
Example:

#define BTN 2
#define MAX_MODE 1   //2 modes

const unsigned int times[] = {1000, 2000};

unsigned int time = times[0];

unsigned long btn_tm = 0;
unsigned long l_time = 0;

byte mode = 0;

void setup(){
  Serial.begin(9600);
  pinMode(BTN, INPUT);
}

void loop(){
  if(digitalRead(BTN) == 1 && millis() - btn_tm > 200){
    btn_tm = millis();
    mode ++
    if(mode > MAX_MODE) mode = 0;
    time = times[mode];
 }
  if(millis() - l_time >= time){
    l_time = millis();
    if(mode == 0) Serial.println("mode 0");
    if(mode == 1) Serial.println("mode 1");
 }
}

Read it and try it.


WS2812B Led Digital Panel Matrix Flexible Screen 8*8. Some LEDs that are not supposed to, switch on My project is composed of an ESP32, a level converter and two WS2812B Led Digital Panel Matrix Flexible Screen 8*8 (from Aliexpress) interconnected with the provided cable. My objective is to show a score, no scrolling or any other animation.
The main functionality works ok, I can display any decimal number between 00 to 99 (one digit in each 8x8 panel).
My problem is that apart from the digits printed, some not so aleatory LEDs switch on, not necessarily on the same color as the intended number, nor on the selected luminosity. Changing the number changes this undesirable pattern that seems to repeat for the same number on the same 8x8 matrix. Problem patters does not follow a specific 8x8 matrix, the problem does not seem to be in the hardware.
The level converter converts the ESP32 3.3v to 5v required by the Matrix but even before I connected the level converter the problem was the same.
The code I am using is as below:
#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
  #include <avr/power.h>
#endif

// Which pin on the Arduino is connected to the NeoPixels?
#define PIN            14

// How many NeoPixels are attached to the Arduino?
#define NUMPIXELS      128

Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);

int delayval = 10; // delay for half a second

void setup() {
  pixels.begin(); // This initializes the NeoPixel library.
}

void loop() {

  // For a set of NeoPixels the first NeoPixel is 0, second is 1, all the way up to the count of pixels minus one.
  pixels.clear();
  pixels.setBrightness(1);

  boolean N0[8][8] PROGMEM = {{0,0,1,1,1,1,0,0},{0,1,1,1,1,1,1,0},{0,1,1,0,0,1,1,0},{0,1,1,0,0,1,1,0},{0,1,1,0,0,1,1,0},{0,1,1,0,0,1,1,0},{0,1,1,1,1,1,1,0},{0,0,1,1,1,1,0,0}};
  boolean N1[8][8] PROGMEM = {{0,0,0,1,1,0,0,0},{0,0,1,1,1,0,0,0},{0,0,0,1,1,0,0,0},{0,0,0,1,1,0,0,0},{0,0,0,1,1,0,0,0},{0,0,0,1,1,0,0,0},{0,1,1,1,1,1,1,0},{0,1,1,1,1,1,1,0}};
  boolean N2[8][8] PROGMEM = {{0,0,1,1,1,1,0,0},{0,1,1,0,0,1,1,0},{0,1,1,0,0,0,0,0},{0,0,1,1,1,1,0,0},{0,0,0,0,0,1,1,0},{0,1,1,0,0,0,1,0},{0,1,1,1,1,1,1,0},{0,1,1,1,1,1,1,0}};
  boolean N3[8][8] PROGMEM = {{0,0,1,1,1,1,0,0},{0,1,1,0,0,1,1,0},{0,1,1,0,0,0,0,0},{0,0,1,1,1,1,0,0},{0,0,1,1,1,1,0,0},{0,0,0,0,0,1,1,0},{0,1,1,0,0,1,1,0},{0,0,1,1,1,1,0,0}};
  boolean N4[8][8] PROGMEM = {{0,0,1,1,1,0,0,0},{0,0,1,1,1,1,0,0},{0,0,1,1,0,1,1,0},{1,1,0,0,1,1,0,0},{0,1,1,1,1,1,1,1},{0,0,0,0,1,1,0,0},{0,1,1,1,1,0,0,0},{0,0,0,1,1,1,1,0}};
  boolean N5[8][8] PROGMEM = {{0,0,1,1,1,1,1,0},{0,1,1,1,1,1,1,0},{0,0,0,0,0,1,1,0},{0,1,1,1,1,1,0,0},{0,1,1,0,0,1,1,0},{0,0,0,0,0,1,1,0},{0,1,1,0,0,1,1,0},{0,0,1,1,1,1,0,0}};
  boolean N6[8][8] PROGMEM = {{0,0,1,1,1,0,0,0},{0,0,1,1,0,0,1,0},{0,0,0,0,0,1,1,0},{0,1,1,1,1,1,0,0},{0,1,1,0,0,1,1,0},{0,1,1,0,0,1,1,0},{0,0,1,1,1,1,0,0},{0,0,0,1,1,0,0,0}};
  boolean N7[8][8] PROGMEM = {{0,1,1,1,1,1,1,0},{0,1,1,0,0,1,1,0},{0,0,1,1,0,0,0,0},{0,0,0,1,1,0,0,0},{0,0,0,0,1,1,0,0},{0,0,1,1,0,0,0,0},{0,0,0,0,1,1,0,0},{0,0,1,1,0,0,0,0}};
  boolean N8[8][8] PROGMEM = {{0,0,1,1,1,1,0,0},{0,1,1,0,0,1,1,0},{0,1,1,0,0,1,1,0},{0,0,1,1,1,1,0,0},{0,1,1,0,0,1,1,0},{0,1,1,0,0,1,1,0},{0,1,1,0,0,1,1,0},{0,0,1,1,1,1,0,0}};
  boolean N9[8][8] PROGMEM = {{0,0,1,1,1,1,0,0},{0,1,1,0,0,1,1,0},{0,1,1,0,0,1,1,0},{0,0,1,1,1,1,1,0},{0,1,1,0,0,0,0,0},{0,0,0,0,0,1,1,0},{0,1,1,1,0,0,1,0},{0,0,1,1,1,1,0,0}};

  int counter = 0;
  for(int line=0;line<8;line++){
    for(int column=0;column<8;column++){
      if(N2[line][column]==1){
        pixels.setPixelColor(counter, pixels.Color(0,255,0));
        pixels.show();
        delay(delayval);
      }

      if(N1[line][column]==1){
        pixels.setPixelColor(counter+64, pixels.Color(255,33,255));
        pixels.show();
        delay(delayval);
      }

      counter++;
    }
  }
  while(1){};
}

This is a non optimized code for testing purposes only.
What am I doing wrong?


If I run a function in loop() or setup(), and the function doesn't work after some time, is there a way to escape the function and return to the code? The hardware is an Arduino Uno, using the Arduino IDE.
As a simplest working example, say I have this code
(partially from Edgar Bonet's answer):

// Simulate an initialization that can hang. Connect pin 8 to ground if
// you want the function to ever return.
void initialize()
{
    pinMode(8, INPUT_PULLUP);
    while (digitalRead(8) == HIGH)
    ;  // wait
}

setup()
{
    initialize();             //Function I want to run

    Serial.begin(9600);       //Baud rate
    Serial.println("TEST 1"); //Test message
}

loop()
{
    Serial.println("TEST 2"); //Test message
    delay(1000);
}

if the initialize() function does not complete after some time, such as 2 secs.,
is there a way to ignore that function and continue with the rest of the code?

In general, the right thing to do in such a situation is to fix the
initialize() function so that it always returns. If there is a timeout
to be handled, it should be handled within that function. This is likely
to be the easiest and cleanest solution.

However, if for whatever reason that is not feasible (maybe it comes
from a library that is too opaque to edit), then the idea suggested by
Michel Keijzers is a viable alternative:

  [...] set up a timer interrupt and start it just before you initialize
  the device/component you want to initialize. When the timer interrupt
  triggers and the device is not initialized, behave the same like a
  timeout has occurred.

The issue with this is that you would want the ISR (interrupt service
routine) to return to the point where initialize() was called. This is
not trivial, but it can be done. Actually, and contrary to what my own
comment says, it can be handled without resorting to assembly hacks, by
using the setjmp “non-local goto” feature of the avr-libc. Here is a
proof of concept:

#include <setjmp.h>

jmp_buf env;

// Simulate an initialization that can hang. Connect pin 8 to ground if
// you want the function to ever return.
void initialize()
{
    pinMode(8, INPUT_PULLUP);
    while (digitalRead(8) == HIGH)
        ;  // wait
}

// This fires when the initialization times out.
ISR(TIMER1_OVF_vect)
{
    TIMSK1 = 0;       // disable timer interrupt
    longjmp(env, 1);  // go to where setjmp() was called
}

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

    // Configure Timer 1 to fire an interrupt in about 4 seconds.
    TCCR1A = 0;           // reset timer
    TCCR1B = 0;
    TCNT1  = 0;
    TIFR1  = _BV(TOV1);   // clear interrupt flag
    TIMSK1 = _BV(TOIE1);  // enable timer overflow interrupt
    TCCR1B = _BV(CS10)    // clock at F_CPU / 1024
           | _BV(CS12);   // ditto

    // Attempt initialization.
    if (setjmp(env) == 0) {

        // This is the normal program flow.
        Serial.println("Attempting initialization.");
        initialize();
        TIMSK1 = 0;  // disable timer interrupt
        Serial.println("Initialization succeeded.");
    } else {

        // We get here through longjmp() in case of timeout.
        Serial.println("Initialization aborted on timeout.");
    }

    Serial.println("Moving on to the rest of the program.");
}

void loop(){}

If pin 8 is grounded, the initialization succeeds and the program prints

Attempting initialization.
Initialization succeeded.
Moving on to the rest of the program.

If pin 8 is left floating, the initialization hangs and the program
prints

Attempting initialization.
Initialization aborted on timeout.
Moving on to the rest of the program.

with a 4 second pause between the first and second lines.


Turning my GPS logger shield off and on I have a Sparkfun GPS Logger Shield and I want to save power by shutting it off when I do not need GPS readings. Now reading the hookup guide it says that the "EN" pin can do this: "Active-high chip-enable – pull low to reset or turn off".

I wanted to ask some advice as to what this actually means and how I safely go about it. Is it as simple as:

pinMode(pin, OUTPUT);

//turn off
digitalWrite(pin, LOW);

//turn on
digitalWrite(pin, HIGH);

Where the pin is a digital pin on the Arduino and it is connected to the "EN" pin of the GPS shield.

Yes, it is as simple as that.

However, since the pin is pulled up already you could also do this:

pinMode(pin, INPUT);
digitalWrite(pin, LOW);

// Turn off
pinMode(pin, OUTPUT);

// Turn on
pinMode(PIN, INPUT);

That then emulates an Open Drain pin which means you're not actively driving the pin when turned on, only when turned off.

Personally I prefer system that are active low not active high, and are pulled down by default (normally off) so that you don't waste power driving the pin in order to save power (it's kind of silly really) - you drive the pin to turn on and let the pin float to turn off (especially good with deep deep comatose sleep on some MCUs where the IO pins all switch off).

However the designers of this module decided otherwise, so you're stuck with driving the pin LOW to make it sleep.


Arduino Uno, Ethernet shield, MySQL I'm trying to connect my Arduino Uno with MySQL.

This is my code:

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

/* Setup for Ethernet Library */
byte mac_addr[] = { 0xC8, 0x0A, 0xA9, 0xAF, 0x83, 0x58 };
IPAddress server_addr(192,168,0,102);

/* Setup for the Connector/Arduino */
Connector my_conn; // The Connector/Arduino reference
char user[] = "root";
char password[] = "fifa2005";
char INSERT_SQL[] = "INSERT INTO test_arduino.hello VALUES ('Hello from Arduino!', NULL)";

void setup() {
Ethernet.begin(mac_addr);
Serial.begin(115200);
delay(1000);
Serial.println("Connecting...");
if (my_conn.mysql_connect(server_addr, 3306, user, password))
delay(500);
else
Serial.println("Connection failed.");
}

void loop() {
}

I have the following database:

mysql> CREATE DATABASE test_arduino;
Query OK, 1 row affected (0.00 sec)
mysql> USE test_arduino;
Database changed
mysql> CREATE TABLE hello (source char(20), event_date timestamp);
Query OK, 0 rows affected (0.01 sec)

This is the output message:

Connecting... Connection failed.

I am not sure this is the right IP address: 192,168,0,102. I tried with the localhost IP address - 127.0.0.1, but nothing happened.

First you have to grant permission to the user!

Type the query in MySQL like:

GRANT ALL ON test_arduino.* TO root@'192.168.0.102' IDENTIFIED BY 'fifa2005';


digital pin's current limit, ohm's law and DC motor A digital pin's output voltage on an UNO board is 5V, which is equal to the output from the VCC. I read that the DC current limits of those pins are 40mA and 200mA respectively, and that a higher current could damage the board. Now, since V=RI, I expect to get the same current whether I connect a DC motor to the VCC or to a digital pin. But, the motor spins slower when connected to the digital pin. Therefore, I'm not getting the same current, and the only thing I could think of in order to explain this apparent contradiction with ohm's law is that there must be some mechanism to keep the current flowing through a digital pin inferior to 40mA. But I also read somewhere (can't find/remember the source) that there are no such mechanisms (except for a fuse concerning the USB)... So as you see, I can't understand what's going on. It will be really nice if someone could explain that to me... thanks in advance!

The ATmega (or any other processor that could reasonably be used on an Arduino) output pins consist of a Totem Pole driver with a PMOS transistor which can drive the output towards Vdd and an NMOS transistor which can drive it towards ground.  Each of these can be modeled as a switch which has a small resistance when "on", and due to device physics the PMOS transistor has a higher resistance than the NMOS.

The 40ma figure is an "Absolute Maximum" rating - a limit above which damage could be possible.  At some current less than that, it is likely the voltage drop across the PMOS transistor will start to be great enough that the output voltage can only marginally be considered a logic "high" - it will be notably less than the supply.

Connecting your motor to an ATmega pin is an extreme, far out of spec.  When you do that, the voltage drop across the PMOS transistor is much larger, making the output voltage quite low.  Additionally, the current flowing through the resistance produces heat within the chip, which can (at least as a rule-of-thumb concern) lead to damage.  Finally, your motor will produce inductive kickback, "spike" voltage possibly high enough to pierce the gate oxide of the MOS gates in the chip, destroying it.  Latchup is another possibility - a sometimes temporary condition where the bulk of the die ends up biased to conduct in the wrong direction and the chip effectively shorts out its power supply, turning it into a miniature space heater.

There really are no components on your typical Arduino board designed to directly control a motor.

Instead, for unidirectional control you should use a circuit with an NPN bipolar transistor, NMOS FET, magnetic relay, or solid state relay.  The latter are commonly available pre-assembled on shields.  With a transistor solution driving the motor in only one direction, it is generally advisable to pick an NPN transistor or NFET and place it in the negative lead of the motor, as the N devices work better due to the greater mobility of electrons than electron-holes.

For bidirectional control, look for a motor shield based on an H bridge IC such as the TB6612FNG or the less efficient bipolar L298 or L293/SN754410.  This basically puts a high current Totem Pole driver on each lead of the motor, allowing you to drive them high & low for one direction or low & high for the other.


Self-diagnose components in the circuit How can I tackle self-diagnosis problem within my Arduino project?
For example, I have a temperature sensor and humidity sensor. How can I know if they work or not on Arduino start or inside the sketch loop?

You could get your program to output messages to the serial pin on your board, Tx. For example:

Serial.begin(9600) //baud rate of 9600

Serial.print("Debug Message");

You can use this to print out string and integers. Here is the link to further information on the Arduino website - https://www.arduino.cc/en/reference/serial

If you are already using the Serial pins then you could use the SoftwareSerial Library - https://www.arduino.cc/en/Reference/softwareSerial

This library allows you to make two other pins on your board Tx and Rx. For example:

SoftwareSerial mySerial(12,13) //Makes pin 12 Rx and pin 13 Tx

mySerial.begin(9600) //baud rate of 9600

mySerial.println("Debug Message");

To read the output from any of the pins on your arduino - use a USB to TTL serial cable. Plug it into your computer and use a program like PuTTY to connect to the serial cable and read the messages coming from the Arduino.