Detecting step motor effort I'm working on a project using steper motor which turn a threaded shaft (long screw) in order to open or close a water valve (high flow, high pressure).

My fear is that, after a long time of use, the grease on the threaded shaft will dissapear and it can became hard for the stepper motor to rotate correctly the threaded shaft.

In order to tell the user to add grease, I have to know when the stepper needs more effort than before to rotate the threaded shaft. So, would it be possible to detect the "effort" made by the stepper in order to get this information on the Arduino?

Any ideas are welcomed!

I suggest that if the answer involves the Arduino, the question might be appropriate to this forum.

If you can mount your stepper motor in such a manner as to apply pressure to a force sensor, you may have a method to resolve your goal.

As the motor rotates, under normal conditions, pressure on the sensor will give you a baseline on which you can base your program for consideration of the amount of force involved.

Picture the motor mounted in the center of a circle, with cut-outs appropriate for the mounting bolts. On the outside of the circle, you would have suitable bearing surfaces to reduce rotational friction. From the motor circle platform, a lever pressing against a fixed point on the outside of the circle provides the contact points for the pressure sensor.

If you will be rotating the motor in both directions, perhaps a pair of sensors mounted to encase the lever would be suitable.

When the screw is new, clean and lubricated, you can collect pressure readings and establish a safe and comfortable range. Those numbers would be fixed into your code and measured during motor activity.

If the activity results in force outside the range, you can either stop or reverse the motor and have the same checks apply.

The logic and code is beyond my capability, but you'd have very few parameters to examine during operation.


Reverse turning of Stepper motor I have a stepper motor connected to my Arduino like this using the ULN2003A Darlington Array:

(Ignore the potentiometer)

And I have programmed it with the following code:

#include <Stepper.h>

int in1Pin = 22;
int in2Pin = 23;
int in3Pin = 24;
int in4Pin = 25;

Stepper motor(512, in1Pin, in2Pin, in3Pin, in4Pin);

void setup()
{
    pinMode(in1Pin, OUTPUT);
    pinMode(in2Pin, OUTPUT);
    pinMode(in3Pin, OUTPUT);
    pinMode(in4Pin, OUTPUT);

    motor.setSpeed(25);
}

void loop()
{
    int steps = 360;

    motor.step(steps);
    delay(500);
}

At the moment the motor rotates clockwise, how could I have it so it rotates in the opposite direction?

My code was copied and edited from here.

The problem was that I had the two middle wires the wrong way round as said here: http://forum.arduino.cc/index.php?PHPSESSID=kvi8dt2b5en5hhk02dlmjrotl5&topic=143276.msg

The answer is simple. Just pass a negative number of steps as an argument to motor.step();.

Another note: You forgot a semicolon on your second to last line. IIRC this doesn't matter in C, but it's just bad practice to do this. If you add a line of code below that, then it won't work.

Example code:

#include <Stepper.h>

int in1Pin = 22;
int in2Pin = 23;
int in3Pin = 24;
int in4Pin = 25;

Stepper motor(512, in1Pin, in2Pin, in3Pin, in4Pin);

void setup()
{
    pinMode(in1Pin, OUTPUT);
    pinMode(in2Pin, OUTPUT);
    pinMode(in3Pin, OUTPUT);
    pinMode(in4Pin, OUTPUT);

    motor.setSpeed(25);
}

void loop()
{
    int steps = 360;
    motor.step(steps);
    delay(100);

    steps = -360;
    motor.step(steps);
    delay(500); //Semicolon added
}


Looking for Power Bank with "Always-On-Feature" I want to build a mobile weather station with an Arduino and some sensors. I want to use a power bank as power source. The Powerbank should support "Always-On", because weather data should not be measured continuously. This means that almost no current flows between the time intervals. Common power banks switch off automatically when the current flow is low.

I don't want to connect an additional device or electronic component to increase the power consumption. So I need a power bank that doesn't switch off even when the current flow is low.

During my search I found the Powerbank "V44 USB Battery Pack" from Voltaic. Unfortunately I cannot buy them in Germany.
https://www.voltaicsystems.com/v44

Can anyone recommend an alternative?

Lithium cell based powerbanks use a boost converter to boost the voltage from the Cell to the 5V for the USB. They turn off because keeping the voltage boosted when not used wastes quite a bit of power.

If all your devices can run straight on 3.3V you can use a Lithium cell directly with a voltage regulator (and with the normal protection circuitry).

Otherwise you can simulate a button press on the on button with a gpio pin to activate the boost circuitry when you are ready to take your measurements; let he voltage stabilize; use transistors to connect the components to power; take your measurements; disconnect the components and then let the timeout expire after which the voltage will drop again.


Int64_t aka long long acts as int32_t and overflows at 2^31 I have an int64_t variable. When I add another int64_t variable

and convert it to a double to print it on the serial monitor, it acts as if it was a int32_t variable. This is the program:

int64_t a = 1 << 31;
double b = static_cast<double>(a);
Serial.println(b);

The output on the serial monitor is -2147483648.00.

What is going on?

1 << 31 is interpreted by the compiler as (int)1 << (int)32.
See the implicit types of integer literals. The
rules of usual arithmetic conversions state that no implicit conversion
is performed in this case. The result is then computed as an int, and
it overflows. Note that this is undefined behavior. The assignment
int64_t a = ... converts the (already overflowed) result to the wider
type, without changing its value.

You probably want to write something like:

int64_t a = 1LL << 31;


Hex String -> Byte Array -> Serial Write I'm writing code that I discussed in a previous post. I now have a setup where I send my Arduino an ASCII-encoded Hex String that represents the bytes I want to write to my serial device. I think I've got most the code figured out other than the way to best convert the hex string for sending

This Code is working

void SendCTRL (String &input)
{
  const char *hin = input.c_str();    // Get character array
  int clen = input.length()/2;
  unsigned char cmd[clen+1]; // Leave a byte for null terminator
  for (int i=0; i < 2*clen; i+=2)
  {
    cmd[i/2] = dehex(hin[i])<<4 | dehex(hin[i+1]);
  }
  cmd[clen] = 0;                     // Null-byte terminator
  digitalWrite(SSerialTxControl, RS485Transmit);  // Enable RS485 Transmit
  for (int i=0; i< clen; i++)
  {
  RS485Serial.write(cmd[i]);   // Send string someplace
  }
  delay(clen/4);
  digitalWrite(SSerialTxControl, RS485Receive);  // Disable RS485 Transmit
  Serial.println();

}

byte dehex(char c)
{
  // Get nibble value 0...15 from character c
  // Treat digit if c<'A', else letter
  return c<'A'? c & 0xF : 9 + (c & 0xF);
}

From what I understand something along the lines of char ISS = SubS.GetBytes(), but guidance would be appreciated

What your code is aiming at isn't particularly clear to me, but I will assume that for some obscure reason you want to accept an input String containing a series of ASCII-encoded hex digits, and create an array of half that many bytes with reconstituted byte values.

First, here are several criticisms of the code shown.

It's likely length(input) won't compile but that input.length() will.

The expression input.substring((2*i),(2*i)+1)) is a String of one character.  If you want two characters, use input.substring((2*i),(2*i)+2)).  And use i += 2 instead of i++ in the for loop.

I don't understand String CMD = CMD+ISS.  I won't say it's invalid, as I don't know without more research.  But it looks like it's declaring variable CMD and using CMD in the initialization of CMD.  [In the example code I give below, I assume CMD should begin as an empty string and be filled up with reconstituted bytes.]

RS485Serial.write(input); // Send byte to Remote Arduino looks mis-commented; presumably it will write out all of the input, not just a byte.

Using a timed delay for holding RS485 Transmit open, as in
delay(10);
 digitalWrite(SSerialTxControl, RS485Receive);  // Disable RS485 Transmit
may cause problems.  On the one hand, it may usually waste five to ten milliseconds of time; on the other, it might occasionally disable RS485 transmit before transmission finishes.  Instead, look for a flag to test for transmission complete, or look for a buffer-fill count, or compute how long to wait, etc.

The next paragraph describes some reasons that Strings may perform badly in this sketch.  For additional discussion of Arduino String objects, see arduino.cc's String page, and see Majenko's The Evils of Arduino Strings page.

Each of the String-object operations in the code creates a new String.  New String objects SubS and CMD are created and destroyed in each pass of the for loop.  The object headers (with type data and member variables, such as a buffer pointer and buffer size) can be stack-allocated, which is harmless (does not leak or fragment memory) but takes some time.  Each String object's character-buffer is heap-allocated: see code in cores/arduino/ file WString.cpp.  Heap fragmentation can and will occur.  ... In brief:  In this application where using String objects is clunky and in the way, you might as well use ordinary C strings instead of String objects.

Ok, with criticisms out of the way, here's some example code that converts ASCII-encoded hex digits into a command string.  Note, as I don't know the specs for RS485Serial.write() or how it determines how much to send, for demonstration purposes I've supposed it can handle a C string.

// Function declaration for dehex()
byte dehex(char c); // Get nibble value 0...15 from character c

void SendCTRL (String input) {
  const char *hin = input.c_str();  // Get character array
  int clen = input.length/2;
  // Next line invalid in C++, ok in C99.  Probably need to
  // instead declare a fixed-length array, cmd[MAXCMDLEN], etc
  char cmd[clen+1]; // Leave a byte for null terminator
  for (int i=0; i < 2*clen; i+=2) {
    cmd[i/2] = dehex(hin[i])<<4 | dehex(hin[i+1]);
  }
  cmd[clen] = 0;                     // Null-byte terminator
  digitalWrite(SSerialTxControl, RS485Transmit);  // Enable RS485 Transmit
  RS485Serial.write(cmd);   // Send string someplace
  delay(clen/4);        // Wait for write to complete? What rate?
  digitalWrite(SSerialTxControl, RS485Receive);  // Disable RS485 Transmit
}

byte dehex(char c) { // Get nibble value 0...15 from character c
  // Treat digit if c<'A', else letter
  return c<'A'? c & 0xF : 9 + (c & 0xF);
  // Above assumes that c is a 'hex digit' in 0...9, A or a ... F or f.
  // It would make more sense to just use 16 consecutive characters,
  // like eg 0123456789:;<=>? or @ABCDEFGHIJKLMNO so the above
  // could just say `return c & 0xF;`
}

Edit 2:

The first statement, byte dehex(char c); is a function declaration for the dehex() function.  It tells the C/C++ compiler the datatypes that the function accepts and returns.  Note, instead of a function declaration at that point, one could instead put the function definition itself (which in the above follows SendCTRL(), a dehex() caller that needs to know dehex()'s datatypes).  Some versions of the Arduino IDE appear to work ok without function declarations ahead of use, but almost all other C/C++ environments will not.
In this edit I added const before char *hin = input.c_str(); because ATE-ENGE reports  “char *hin =input.c_str() is giving me an invalid conversion error from const char* to char*”.  That error indicates the left-hand-side variable has a datatype different from that of the right-hand-side expression and an automatic conversion isn't available.  Note, unfortunately the arduino.cc c_str() webpage doesn't specify the return type of c_str().

Edit 3:  Changed for (int i=0; i < clen; i+=2) to for (int i=0; i < 2*clen; i+=2) per notes in another question's answer.

Edit 4:  Changed cmd[i/2] = dehex(hin[i])<<4 + dehex(hin[i+1]) to  cmd[i/2] = dehex(hin[i])<<4 | dehex(hin[i+1]) to avoid an operator precedence problem.  The precedence of +, addition, is higher than that of <<, bitwise shift, which in turn is higher than that of |, bitwise OR.  The unparenthesized expression with + adds 4 to dehex(hin[i+1]) and uses the total as a shift count; not at all as desired.  Note, one can of course use parentheses to control the problem, as in the expression (dehex(hin[i])<<4) + dehex(hin[i+1])


Ramping up and down arduino motor due to ultrasonic sensor input Im working on an arduino robot that needs to follower a leader robot infront of it. The leader robot can accelerate, decelerate , and stop and my robot needs to be able to follow the leader without crashing into it.

I have my two sensors working however Im having a harder time integrating the motors to ramp up or down. Currently only one wheel turns on at a time for the right and left commands.
How can I appropriatly ramp up or down the wheel speed.

int SpRMotor = 5;  //speed Right Motor
int MotorA1 = 7; //Right Motor = +
int MotorA2 = 6; //Right Motor = -
int MotorB1 = 8; //Left Motor = -
int MotorB2 = 9; //Left Motor = +
int SpLMotor = 10;  //speed Left Motor

int TriggerPIN1 = 3;//right
int EchoPIN1 = 2;
int TriggerPIN2 = 12;//left
int EchoPIN2 = 11;

void setup(){
  pinMode(TriggerPIN1,OUTPUT);
  pinMode(EchoPIN1,INPUT);
  pinMode(TriggerPIN2,OUTPUT);
  pinMode(EchoPIN2,INPUT);

  pinMode(MotorB1, OUTPUT);
  pinMode(MotorB2, OUTPUT);
  pinMode(MotorA1, OUTPUT);
  pinMode(MotorA2, OUTPUT);
  pinMode(SpLMotor, OUTPUT);
  pinMode(SpRMotor, OUTPUT);

  analogWrite(SpRMotor, 170);
  analogWrite(SpLMotor, 170);
  Serial.begin(9600);
  }
void loop(){

  int limit;
  int sampledata1, sampledata2;
  sampledata1 = distance(TriggerPIN1, EchoPIN1);
  Serial.print("distance1: ");
  Serial.print(sampledata1);
  delay(100);
  sampledata2 = distance(TriggerPIN2, EchoPIN2);
  Serial.print(" distance2: ");
  Serial.println(sampledata2);
  delay(100);
  limit = 10;
  if((15> sampledata1 >= limit)&&(15> sampledata2 >= limit))
  {
    Serial.print("True");
    forward();
    delay(100);
  }
     if (sampledata2  >= 15 )
    {turnRight();}
  if (sampledata1  >= 15 )
    {turnLeft();}
  if ((limit > sampledata1)&&(limit> sampledata2 ))
  {
    Stop();
  }

}

void forward(){
digitalWrite(MotorA1, LOW);
digitalWrite(MotorA2, HIGH);
digitalWrite(MotorB1, HIGH);
digitalWrite(MotorB2, LOW);
}

void turnRight(){
digitalWrite(MotorA1, LOW);
digitalWrite(MotorA2, LOW);
digitalWrite(MotorB1, HIGH);
digitalWrite(MotorB2, LOW);
}

void turnLeft(){
digitalWrite(MotorA1, LOW);
digitalWrite(MotorA2, HIGH);
digitalWrite(MotorB1, LOW);
digitalWrite(MotorB2, LOW);
}

void Stop(){
digitalWrite(MotorA1, LOW);
digitalWrite(MotorA2, LOW);
digitalWrite(MotorB1, LOW);
digitalWrite(MotorB2, LOW);
}
int distance(int trig, int echo)
{ digitalWrite(trig,LOW);
  delayMicroseconds(2);
  digitalWrite(trig,HIGH);
  delayMicroseconds(10);
  digitalWrite(trig,LOW);
  long timedelay = pulseIn(echo,HIGH);
  int distance = 0.0343 * (timedelay/2);

  return distance;
}

The speed seams to be defined by a an analog write to SpRMotor and SpLMotor. You did that once (with value 170)  in the setup. If you use variables for that (e.g. speedValueL and speedValueR) you can change their values as you need it and write it to the PWM channels on each forward, backward, left or right statement.

A short example:

int SpRMotor = 5;  //speed Right Motor
int MotorA1 = 7; //Right Motor = +
int MotorA2 = 6; //Right Motor = -
int MotorB1 = 8; //Left Motor = -
int MotorB2 = 9; //Left Motor = +
int SpLMotor = 10;  //speed Left Motor

int TriggerPIN1 = 3;//right
int EchoPIN1 = 2;
int TriggerPIN2 = 12;//left
int EchoPIN2 = 11;

int speedValueL = 0;
int speedValueR = 0;

void setup()
{
  pinMode(TriggerPIN1,OUTPUT);
  pinMode(EchoPIN1,INPUT);
  pinMode(TriggerPIN2,OUTPUT);
  pinMode(EchoPIN2,INPUT);

  pinMode(MotorB1, OUTPUT);
  pinMode(MotorB2, OUTPUT);
  pinMode(MotorA1, OUTPUT);
  pinMode(MotorA2, OUTPUT);
  pinMode(SpLMotor, OUTPUT);
  pinMode(SpRMotor, OUTPUT);

  analogWrite(SpRMotor, speedValueR);
  analogWrite(SpLMotor, speedValueL);

  Serial.begin(9600);
}

void loop()
{
  int limit;
  int sampledata1, sampledata2;
  sampledata1 = distance(TriggerPIN1, EchoPIN1);
  Serial.print("distance1: ");
  Serial.print(sampledata1);
  delay(100);
  sampledata2 = distance(TriggerPIN2, EchoPIN2);
  Serial.print(" distance2: ");
  Serial.println(sampledata2);
  delay(100);
  limit = 10;
  if( (15> sampledata1 >= limit) && (15> sampledata2 >= limit) )
  {
    Serial.print("True");
    // Just my guess - do what fits for you
    speedValueL = 170;
    speedValueR = 170;

    forward();
    delay(100);
  }

  if (sampledata2  >= 15 )
  {
    // Just my guess - do what fits for you
    speedValueL = 200;
    speedValueR = 0;

    turnRight();
  }

  if (sampledata1  >= 15 )
  {
    // Just my guess - do what fits for you
    speedValueL = 0;
    speedValueR = 200;

    turnLeft();
  }

  if ( ( limit > sampledata1 ) && ( limit> sampledata2 ) )
  {
    // Just my guess - do what fits for you
    speedValueL = 0;
    speedValueR = 0;

    Stop();
  }
}

void forward()
{
  analogWrite(SpRMotor, speedValueR);
  analogWrite(SpLMotor, speedValueL);

  digitalWrite(MotorA1, LOW);
  digitalWrite(MotorA2, HIGH);
  digitalWrite(MotorB1, HIGH);
  digitalWrite(MotorB2, LOW);
}

void turnRight()
{
  analogWrite(SpRMotor, speedValueR);
  analogWrite(SpLMotor, speedValueL);

  digitalWrite(MotorA1, LOW);
  digitalWrite(MotorA2, LOW);
  digitalWrite(MotorB1, HIGH);
  digitalWrite(MotorB2, LOW);
}

void turnLeft()
{
  analogWrite(SpRMotor, speedValueR);
  analogWrite(SpLMotor, speedValueL);

  digitalWrite(MotorA1, LOW);
  digitalWrite(MotorA2, HIGH);
  digitalWrite(MotorB1, LOW);
  digitalWrite(MotorB2, LOW);
}

void Stop()
{
  analogWrite(SpRMotor, speedValueR);
  analogWrite(SpLMotor, speedValueL);

  digitalWrite(MotorA1, LOW);
  digitalWrite(MotorA2, LOW);
  digitalWrite(MotorB1, LOW);
  digitalWrite(MotorB2, LOW);
}

int distance( int trig, int echo )
{
  digitalWrite( trig, LOW );
  delayMicroseconds( 2 );
  digitalWrite( trig, HIGH );
  delayMicroseconds( 10 );
  digitalWrite( trig, LOW );
  long timedelay = pulseIn( echo, HIGH );
  int distance = 0.0343 * ( timedelay / 2);

  return distance;
}


List of sketches disappears off the bottom of my screen v 2:1.0.5

The list of sketches disappears off the bottom of my screen and there is no scroll to reach them. This renders the IDE nearly useless.

Is there a solution?

That issue has been fixed since the Arduino IDE 1.5.5 release, 4 years ago.

The version of the Arduino IDE you get from apt-get install arduino has not been able to be updated for years due to licensing issues. The versions available from various package managers may also be modified in ways that introduce new bugs. For this reason you should always install the official Arduino IDE version downloaded from:
https://www.arduino.cc/en/Main/Software


Best way to send text to ESP8266 remote display I need a remote display to show information sent via WiFi from another ESP8266. What needs to be sent is a string along with some variables, for example a string to be displayed along with two integers for the position on the display:

0, 12, "message to display on screen"

As I am absolutely new to network stuff, what would be the best way to achieve this?

Sending a POST request through REST API?
Use UDP instead?
Or better use a framework like MQTT?

Try the esp8266 UDP messages

With UDP you can send and receive messages quite easily and without consuming lots of resources.


Interfacing Arduino with matplotlib animation I've also asked this question over on stack exchange so I'll link the actual question here.

The short story is I have a plot that updates in real time from data collected on an Arduino. The plot updates on a 50ms + overhead interval and I can either choose on the Arduino side to either delay the loop 50ms + compensation or use flush(). I'm running into some problems with the delay option where my program begins to lag (Python side). I'm wondering if flush will work as I expect and hold the output until my python program reads from the serial port. So then the Python program is completely controlling the flow of data every time it polls for an update.

Edit: Here's a snippet of the code.

void loop() {
  // put your main code here, to run repeatedly:
  val1 = analogRead(0);
  val2 = analogRead(1);
  Serial.print(val1);
  Serial.print(" ");
  Serial.print(val2);
  Serial.print("\n");
  //Serial.flush();
  delay(50);
}

On the Arduino side, flush simply waits until the last byte has been fully transmitted.  It says nothing about how quickly it is being read by the PC.

The general problem you are having is called "flow control".  It has been solved with many different techniques, like "handshaking".  For example, the PC could send a character when it has received the last byte of a data set (a line, as returned by readline):

line = self.ser.readline()
self.ser.write("!"); // Tell Arduino line was received
line = line.split()

While the PC proceeds to parse the line, the Arduino will eventually receive the handshake character:

void loop()
{
  // Send a line
  Serial.println( ... );

  // Wait for handshake character
  bool gotHandshake;
  do {
    while (!Serial.available())
      ; // wait for chars
    char c = Serial.read();
    gotHandshake = (c == '!');
  } while (!gotHandshake);
}

Then the Arduino can proceed to send the next data set (i.e., a line).  The OS on the PC will buffer characters from the Arduino until the python program receives them with readline and sends another handshake character.  No delay required.


Why doesn't the master branch BOSSA work on Arduino Due? I have downloaded BOSSA for Linux, and have run bossash->scan. I have also tried erasing and resetting the board before scanning. It does not work. According to the Arduino website, the native USB port is connected directly to the chip.

Isn't the master branch BOSSA (Arduino IDE uses it's own modified version of BOSSA) working because of a problem with this specific board, or have Arduino modified something inside the chip which alters the behaviour of the native port?

No Arduino did not alter the chip, custom chips are massively expensive. If they are using their own modified version of BOSSA, then there must be a reason for it, probably the support of Arduino's hardware platform. To find out what the difference is, you have to find the code base used for Due and the original version when the code was forked. Often in such cases a project like Arduino can provide a patch to the BOSSA project, and that patch may or may not be applied to the master tree. Only way to find out is to check the BOSSA project repository / bug  reports and documentation.


Trying to use a 7 segment display to count 0/9 with a potentiometer im trying to switch number on the display using a
    potentiometer, it is just counting from 0/9.
    All help is much appreciated!

int SegmentA = 6;
int SegmentB = 7;
int SegmentC = 8;
int SegmentD = 9;
int SegmentE = 10;
int SegmentF = 11;
int SegmentG = 12;

const int PP = A0;

void setup()
{
  pinMode (SegmentA, OUTPUT);
  pinMode (SegmentB, OUTPUT);
  pinMode (SegmentC, OUTPUT);
  pinMode (SegmentD, OUTPUT);
  pinMode (SegmentE, OUTPUT);
  pinMode (SegmentF, OUTPUT);
  pinMode (SegmentG, OUTPUT);

}

void loop() {

  int POD = analogRead(PP);
  int SM = map(POD, 0, 1023, 0 , 8);
  switch (SM) {

    case 0:
      digitalWrite (SegmentA, HIGH);
      digitalWrite (SegmentB, HIGH);
      digitalWrite (SegmentC, HIGH);
      digitalWrite (SegmentD, HIGH);
      digitalWrite (SegmentE, HIGH);   //0
      digitalWrite (SegmentF, HIGH);
      digitalWrite (SegmentG, LOW);

      delay(1000);

    case 1:
      digitalWrite (SegmentA, LOW);
      digitalWrite (SegmentB, HIGH);
      digitalWrite (SegmentC, HIGH);
      digitalWrite (SegmentD, LOW);
      digitalWrite (SegmentE, LOW);   //1
      digitalWrite (SegmentF, LOW);
      digitalWrite (SegmentG, LOW);

      delay(1000);

    case 2:
      digitalWrite (SegmentA, HIGH);
      digitalWrite (SegmentB, HIGH);
      digitalWrite (SegmentC, LOW);
      digitalWrite (SegmentD, HIGH);
      digitalWrite (SegmentE, HIGH);   //2
      digitalWrite (SegmentF, LOW);
      digitalWrite (SegmentG, HIGH);

      delay(1000);

    case 3:
      digitalWrite (SegmentA, HIGH);
      digitalWrite (SegmentB, HIGH);
      digitalWrite (SegmentC, HIGH);
      digitalWrite (SegmentD, HIGH);
      digitalWrite (SegmentE, LOW);   //3
      digitalWrite (SegmentF, LOW);
      digitalWrite (SegmentG, HIGH);

      delay(1000);

    case 4:
      digitalWrite (SegmentA, LOW);
      digitalWrite (SegmentB, HIGH);
      digitalWrite (SegmentC, HIGH);
      digitalWrite (SegmentD, LOW);
      digitalWrite (SegmentE, LOW);   //4
      digitalWrite (SegmentF, HIGH);
      digitalWrite (SegmentG, HIGH);

      delay(1000);

    case 5:
      digitalWrite (SegmentA, HIGH);
      digitalWrite (SegmentB, LOW);
      digitalWrite (SegmentC, HIGH);
      digitalWrite (SegmentD, HIGH);
      digitalWrite (SegmentE, LOW);   //5
      digitalWrite (SegmentF, HIGH);
      digitalWrite (SegmentG, HIGH);

      delay(1000);

    case 6:
      digitalWrite (SegmentA, HIGH);
      digitalWrite (SegmentB, LOW);
      digitalWrite (SegmentC, HIGH);
      digitalWrite (SegmentD, HIGH);
      digitalWrite (SegmentE, HIGH);   //6
      digitalWrite (SegmentF, HIGH);
      digitalWrite (SegmentG, HIGH);

      delay(1000);

    case 7:
      digitalWrite (SegmentA, HIGH);
      digitalWrite (SegmentB, HIGH);
      digitalWrite (SegmentC, HIGH);
      digitalWrite (SegmentD, LOW);
      digitalWrite (SegmentE, LOW);   //7
      digitalWrite (SegmentF, LOW);
      digitalWrite (SegmentG, LOW);

      delay(1000);

    case 8:
      digitalWrite (SegmentA, HIGH);
      digitalWrite (SegmentB, HIGH);
      digitalWrite (SegmentC, HIGH);
      digitalWrite (SegmentD, HIGH);
      digitalWrite (SegmentE, HIGH);   //8
      digitalWrite (SegmentF, HIGH);
      digitalWrite (SegmentG, HIGH);

  }

}

You miss the break statement at the end of each case. e.g.:

  digitalWrite (SegmentF, LOW);
  digitalWrite (SegmentG, HIGH);

  delay(1000);

  break;

case 4:

This causes each case to perform, and continue with the next case. However, since there is a delay of 1 second, it looks like it is counting.

Actually, I would expect it counts from a certain value depending on the pot meter to 7, since there is no digit 9 implemented, and the delay for the 8 digit is missing too.

To further improve your code, you can add the delay not in every case but at the end, since I assume there always will be one digit selected.

Also you can make a function void showDigit with a parameter for each of the possible segment states and replace all (almost) duplicated code by that function call, or send the digit and use showDigit to set internally the states of each segment (by using a boolean array[nr_of_digits][nr_of_segments], somewhat like Nic Hartley proposes below.


Send button press over RF I'm trying to send a button press over RF (performing a closed circuit operation on the receiving end).

I have a controller with an UP and DOWN button. Unfortunately I am limited to the cable length, and would like to extend it with radio frequency. The controller has one cable for GND and one each for the corresponding UP and DOWN buttons.

The RF units is the typical 433mhz bought online (ebay).

Can I in someway send the signal over RF (directly on the data pin of the transmitter) without hooking it up to a microcontroller (Arduino)?

No. You need a micro-controller at both the sending, and receiving sides.

eBay does set RF remotes with a few buttons. This might be easier and cheaper than making your own.


Arduino Time Clock Accuracy I'm currently trying to create an Arduino time clock by using the PJRC Time library (http://www.pjrc.com/teensy/td_libs_Time.html). I know that since most of the Arduino boards are running with a 16MHz clock and a single resonator, the time can become "out-of-sync" after a certain period of time.

However, I was wondering if anyone has an idea about the accuracy of the Time library when used on the Arduino DUE with a 84MHz clock. I've been testing it out and so far, the clock has been kept in sync for a few hours. Thanks!

The limitations of accuracy of the library depend on accuracy of the crystal. When they make, or cook, the crystal they can only make it to a certain degree accurate, also the environment of the crystal (temperature, humidity, etc.) play a role in the accuracy of it. Let's say you have a crystal that is off by .5 second every hour, great for short term, but if you expand that over a year it is over 1 hour off by that time. If you want something to keep an accurate time over a long period I suggest a real time clock (they still have inaccuracies), a GPS module, or an internet connect to sync with.

For further information look at the wikipedia article on quartz crystals

The use of a 84MHz crystal versus a 16MHz crystal will not necessarily improve the accuracy of the Arduino clock since the frequency of the crystal is more an indicator of processor speed than accuracy. The accuracy of the Arduino clock is primarily dependent on the accuracy of the crystal oscillator.

EDIT: I am no expert on crystal oscillators so if you see anything wrong here please let me know


LCD write a line at bottom without lcd.setCursor and without deleting any char above already there? lcd.cursor and lcd.noCursor won't work for what I want to use it for since it seemed to be "global" sort of speak and follow lcd.setCursor which I don't want it to but it is otherwise exactly what I want to be done; just to put a line at the very bottom and also remove the line whenever I want to but without removing the entire char above.

Just like lcd.cursor do but as said it won't work in the code since the line has to reside where it is even if lcd.setCursor is used elsewhere but then the cursor line follow to that other point which I don't want and such a controllable cursor that sits at the place even if lcd.setCursor is used elsewhere. But the char there first and then the line of vice versa doesn't matter just as long as there it a line. And I cant create custom chars with a line under them since its numbers from 0 - 9 and so many custom chars can't be made.

It's fully possible to write to the bottom row though and I thought it would be possible to do something with lcd.createChar by not no write anything at all at the bytes rows but the lowest one, but that surprisingly failed. This is what I tested:

byte line[8] = {

  B,
  B,
  B,
  B,
  B,
  B,
  B,
  B11111,
};

And that writes on the lowest row as expected, but strangely enough STILL deletes any char that is written above even if nothing should have been written there as I see it.

The test here put out pretty much garbage and pretty much delete the char written but something still remain but the line is written at top instead of bottom and I guess it all goes out of the normal bounds in the registry or something:

#include <LiquidCrystal.h>
LiquidCrystal lcd(40, 42, 28, 26, 24, 22);

byte line[1] = {

  B00000,
};

byte noline[1] = {

  B11111,
};

byte sure[8] = {   //It didn't like to use "square" as name by whatever the reason

  B00000,
  B00000,
  B01110,
  B01110,
  B01110,
  B01110,
  B00000,
  B00000,
};

void setup() {

  lcd.createChar(0, line);
  lcd.createChar(1, noline);
  lcd.createChar(2, sure);

  lcd.begin(20, 4);
  lcd:clear:
}

void loop() {

  delay(500);
  lcd.setCursor(0, 0);
  lcd.write(byte(2));
  delay(500);
  lcd.setCursor(0, 0);
  lcd.write(byte(1));
  delay(500);
  lcd.setCursor(0, 0);
  lcd.write(byte(0));

}

Any tips on how to do the same with create.Char or any other simple way? I mean the lcd.cursor and lcd.noCursor can do it, how do that do it then? It's an ordinary 20X4 LCD if that would matter.

I do not really understand what you mean by your first sentence. Did you succeed in getting a "hardware" cursor to display together with a character or not? And if you do, why doesn't this fulfill your requirements?

You have to realize that your LCD cannot display partial characters, like a line at the bottom, leaving the rest of the character that was already there intact. An exception is a hardware generated cursor.

You also have to realize that createChar always expects a full character with 8 rows.

Your code examples

In your first example, starting with byte line[8] = {, the first 7 "empty" B, lines actually produce a value of (binary) zero. So here you create an empty character with a line at the bottom, exactly like you said you see on the display.

In your second piece of code, you define characters byte line[1] = and byte noline[1] = consisting of just 1 byte. createChar expects 8 bytes. createChar will fill the characters with the single byte defined in your character definition, plus whatever it finds in the 7 memory locations following your actual definition (which will probably contain some random data). This explains the "garbage" you see on the screen.

Possible solution

One solution would be to re-create each character you want your cursor to display under, on the fly. I.e. if you want your cursor to be displayed under the letter "A", you create a complete custom character which contains "A", plus a cursor underneath and you display it in place of the real "A" at this location. When you move the cursor, you replace the "custom" A with the real "A" again.

This will be cumbersome in code complexity as well as code size (you'd have to create a complete character map for every character you wish to display), but should be a feasible solution.


Having problems registering my SIM800 with the network I have a SIM808, connected via hardware serial to an Arduino Mega. Communication between the Arduino and the SIM808 is fine. However, the quality of the signal is listed as 0 all the time. (AT+CSQ)

I've checked, and there is definitely 2G (and 3G) signal. Power is fine. SIM is unlocked, and works in other M2M equipment.

The network status lights blink rapidly (ie searching for a network) for about 5 seconds. Then it takes one long blink, then goes back to blinking rapidly.

The module is picking up the names of the available networks, yet does not seem to be able to register.

I'm using a prepaid data SIM card from Vodacom (South Africa).

I think you are not giving it enough power, SIM800 module needs 5v/2A stable power source in order to register to network. Try to use a desktop computer power supply it has 5v/2A output wire (refer to colors).


Change timeout of `Serial.parseInt()`? Serial.parseInt() reads from the serial buffer until it sees a non-numeric character or it's timeout is reached. When I use it, I put a space after the last number to make it return faster. Can I change the timeout so if I forget the number it doesn't take as long?

Don't use Serial.parseInt(). It is very very wrong. The whole idea behind how it operates is completely wrong and teaches bad practices and methods.

Part of your way of speeding it up is half-way to doing it properly.

You require a delimiter to say "this is the end of the number". Relying on time in a system that is inherently asynchronous is just plain daft. You have chosen to add a space. A better choice is to use a proper line ending "\n".

Then you should either read the serial character-by-character and parse it as it arrives until you find the EOL character, or read it character by character into a string (NOT a String, a "string" - a C string - a character array terminated by a NULL character), and then use atoi() etc to convert it to the numerical format you want.

Many of the methods that Arduino provide are not suitable for professional use and should be avoided at all cost lest they teach you the completely wrong way of doing things.


Sparkfun OBDII - Arduino Uno Stuck at 832RPM-13Kmh I'm working on a hobby project with Sparkfun OBDII UART + Arduino Uno + 16x2 LCD Screen, i'm trying to read my car's RPM-Speed-Coolant Temprature-Oxy Sensor on runtime.
Product Page
Wired OBDII to Arduino as:
OBD TX -> ARDUINO RX
OBD RX-> ARDUINO TX
OBD GND -> ARDUINO GND
As far as i understand OBDII board does all the job and it's just communicating with arduino through serial, they provided an example here : Hookup Guide
I don't have sparkfun serial lcd, so i've changed codes according to my lcd as follow;
#include <SoftwareSerial.h>
#include "DFRobot_RGBLCD.h"
const int colorR = 255;
const int colorG = 0;
const int colorB = 0;
DFRobot_RGBLCD lcd(16,2);  //16 characters and 2 lines of show
char rxData[20];
char rxIndex=0;
int vehicleSpeed=0;
int vehicleRPM=0;
void setup()
{
lcd.init();
lcd.setRGB(colorR, colorG, colorB);
Serial.begin(9600);
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Hiz: ");
lcd.setCursor(0,1);
lcd.print("Devir: ");
delay(1500);
Serial.println("ATZ");
delay(2000);
Serial.flush();
}

void loop()
{
Serial.println("010D");
getResponse();
getResponse();
vehicleSpeed = strtol(&rxData[6],0,16);
lcd.setCursor(4,0);
lcd.print(vehicleSpeed);
lcd.print(" km/h");
delay(100);
Serial.flush();
Serial.println("010C");
getResponse();
getResponse();
vehicleRPM = ((strtol(&rxData[6],0,16)*256)+strtol(&rxData[9],0,16))/4;
lcd.setCursor(6,1);
lcd.print(vehicleRPM);
delay(100);
}
void getResponse(void){
  char inChar=0;
  while(inChar != '\r'){
    if(Serial.available() > 0){
      if(Serial.peek() == '\r'){
        inChar=Serial.read();
        rxData[rxIndex]='\0';
        rxIndex=0;
      }
      else{
        inChar = Serial.read();
        rxData[rxIndex++]=inChar;
      }
    }
  }
}

with above code i believe arduino receives last rpm and speed record before i shut down the engine which is 832RPM - 13 Kmh (at this point i'm not sure if arduino receive speed value correctly because when i shut down the engine i was parked the car and speed was 0kmh), in normal case when i start the car rpm and speed value should have changed but even after started the car the value stands still,it's not changing.
I bought waveshare's USB FTDI(TTL) adapter to figure it out is this board communicate with car or pc properly, connected usb ttl as;
OBD TX -> TTL RX
OBD RX-> TTL TX
OBD GND -> TTL GND
connected to OBDII port of my car, opened tera term, connected to COM20 (ttl defined as com20 on the pc) and run below commands as suggested in their manual;
ATZ -- resetted card successfully
ATRV -- returned 12.4 V as it should be, which is my battery voltage
ATSP0 -- auto find and select car's protocol it returned OK
010C -- RPM of the car it returned 41 0C 00 00 (engine wasn't started)
010C -- RPM of the car it returned 41 0C 10 F4 (engine started--idle RPM arround 1.000 rpm)
010D -- speed of the car it returned 41 00 00
010D -- speed of the car it returned 41 00 00 both value is the same because the car is not moving :)

According to above outcome the board is fine and communicating with car or pc or arduino without any problem.
But when i try with arduino when i connect the board to my car and turn my ignition to battery mode it reads rpm as 832 and speed as 13 and don't update those values even i start the engine.
What am i doing wrong?

after 1 week of try i finally solved it :)
As you guys know UNO has 1 i/o serial port, and Sparkfun's OBDII board doesn't work on same i/o serial port (at least i couldn't be able to), with uno when you send a command through serial to obd board you need to wait minimum 3 seconds to send another command or car's can-bus thinks that you canceled the first command returns STOPPED error, but with MEGA it works perfectly because mega has 3 i/o serial ports. You simply define Serial(TX)-Serial1(RX) and it works perfectly with 75ms delay.
Here is the working code.
//Set up ring buffer
char rxData[20];
char rxIndex = 0;
int rpmstored = 0;

    void setup()
    {
      Serial.begin(9600); // prints to serial monitor
      Serial1.begin(9600); //Hardware serial connection to the obdii uart
      OBD_init(); //initiates obd link
      delay(3000);
    }

    void loop()
{
rpmstored = getRPM();
//int mph = (int)((getSPEED() * 10000L + 5) / 16090); //convert to mph
//  Serial.print (mph);
Serial.print("S:");
Serial.print (getSPEED());
Serial.print (",");
Serial.print("R:");
Serial.println (getRPM());
//Serial.print (",");
//Serial.print("W:");
//Serial.print (getWATERTEMP());
//Serial.print (",");
//Serial.print("O:");
//Serial.print (getOILTEMP());
//Serial.print (",");
//Serial.print("F:");
//Serial.print (getFUEL());
//Serial.print (",");
//Serial.print("V:");
//Serial.println (getVOLT());
delay(100);
Serial.flush();
    }

    void OBD_init(void)
    {
      //Wait for a little while before sending the reset command to the OBD-II-UART
      delay(2000);
      //Reset the OBD-II-UART
      Serial1.print("ATZ\r");
      //Wait for a bit before starting to send commands after the reset.
      delay(2);
      OBD_read();
      Serial1.print("ATE0\r");
      OBD_read();
      //Serial1.flush();
    }

    int getRPM(void)
    {
      //Query the OBD-II-UART for the Vehicle rpm
      Serial1.flush();
      Serial1.print("010C\r");
      OBD_read();

      return ((strtol(&rxData[6], 0, 16) * 256) + strtol(&rxData[9], 0, 16)) / 4;
    }

    int getSPEED(void)
    {
      //Query the OBD-II-UART for the vehicle speed
      Serial1.flush();
      Serial1.print("010D\r");
      OBD_read();

      return strtol(&rxData[6], 0, 16);
    }

    int getOILTEMP(void)
    {
      //Query the OBD-II-UART for the vehicle speed
      Serial1.flush();
      Serial1.print("015C\r");
      OBD_read();

      return strtol(&rxData[6], 0, 16);
    }

    int getFUEL(void)
    {
      //Query the OBD-II-UART for the vehicle speed
      Serial1.flush();
      Serial1.print("012F\r");
      OBD_read();

      return strtol(&rxData[6], 0, 16);
    }

    int getVOLT(void)
    {
      //Query the OBD-II-UART for the vehicle speed
      Serial1.flush();
      Serial1.print("0142\r");
      OBD_read();

      return strtol(&rxData[6], 0, 16);
    }

    int getWATERTEMP(void)
    {
      //Query the OBD-II-UART for the Engine Coolant Temp
      Serial1.flush();
      Serial1.print("0105\r");
      OBD_read();

      return strtol(&rxData[6], 0, 16) - 40;
    }

    void OBD_read(void)
    {
      char c;
      do {
        if (Serial1.available() > 0)
        {
          c = Serial1.read();
          if ((c != '>') && (c != '\r') && (c != '\n')) //Keep these out of our buffer
          {
            rxData[rxIndex++] = c; //Add whatever we receive to the buffer
          }
        }
      } while (c != '>'); //The ELM327 ends its response with this char so when we get it we exit out.
      rxData[rxIndex++] = '\0';//Converts the array into a string
      rxIndex = 0; //Set this to 0 so next time we call the read we get a "clean buffer"

    }

I only need RPM & Speed that's why i comnented out other parameters but tested all and works perfectly.


Arduino.Mk together with MightyCore There's no end to my frustration trying to figure out how the arduino build system works -- despite my best efforts I just can't seem to grok it. Anyhow, I did this:
ALTERNATE_CORE_PATH=/path/to/MightyCore/avr
BOARD_TAG=324
...

make show_boards shows me several boards available, including 324. Yet whenever I try to build my project, I get this error:
avr-g++: error: missing device or architecture after ‘-mmcu=’

Can someone point me in the right direction?
Thanks.

Resolved with the following Makefile options:
BOARD_TAG=324
MCU=atmega324a
VARIANT=standard


Will an ATmega2560 board be faster than a Uno for hard real-time data logging? I am designing a hard real-time data logger. The Uno is a bit marginal in processing speed.

a) Would it be faster if I changed to an ATmega2560?

b) On the datasheet, ATMEGA2560 has 135 instructions; it is 4 instructions more than the ATmega328p.

What are the extra 4 instructions for?

Are they involved in floating point maths?

c) How to select compiler option for fastest code at the expense of bigger code size, longer compilation time, etc.?

The system is:

Receive data from wireless transceiver chip via hardware SPI port.
A good portion of the time is spent on data calculation using floating point maths.
Output processed data on serial port (then to PC via the Arduino board USB to Serial chip).
Code and RAM size is not an issue, Uno has plenty space left.

No, it will not be any faster. The extra instructions are to access the extra flash memory of the 2560. Instructions like EIJMP - Extended indirect jump, EICALL - Extended indirect call, etc.

The compiler option -O3 optimises the most, but there are other options you can enable, such as -funroll-loops which will cause major code bloat but speed things up.  Read the GCC manual pages to boggle at all the millions of optimisation options.

Or... use a faster chip, like an ARM or PIC32.


Signal noise on R/C car channel output Doing a little project for work and trying to get the Arduino hooked to an RC car to read the throttle channel output and send that via bluetooth to a nearby laptop which will output an animation based on that speed.

Initial test worked very well and signals from my airplane Tx were solid with very little variance. Once the proof of concept worked, we went ahead and purchased a Traxxas car. I have a wire going from pin 5 to the signal wire on the Rx. With the serial monitor up and arduino powered via my usb cable, the #s jump from the 1400 (where its supposed to be) to 6000 and sometimes 11000.  Even more interesting, is when I engaged the throttle via the transmitter, values went down to 30-50...?? I removed the Rx from the car and powered it via the 5v on arduino...#s are solid.

So, it appears the battery or esc is giving a lot of interference. Do I need to use a different kind of wire? If so, what kind of wire? Or ground it somehow?

Old post, but here was my solution. Had to pickup some shielded cable. Pics below should clearly explain how everything was wired up.


HTTP request not sending so I have a wifi shield and I am sending a web request, but its not going through. I know it's not the server because the other function of the program works properly. My code is available on pastebin

EDIT:

The request that is not working is on line 318

You are lacking a space:

client.println((String)"GET /msg.php?action=send&ID=2&message=" += currentMessage += "HTTP/1.1");
                                                                                ^

Your HTTP is running in to the content of your message ending up with a corrupt request. Also you are doing appending within your strings (+=) when you don't need to (+ is all that is needed). In fact, you don't even need that - just do multiple prints and reduce the hammering your heap is getting. Oh, and don't forget to use F():

client.print(F("GET /msg.php?action=send&ID=2&message="));
client.print(currentMessage);
client.println(F(" HTTP/1.1"));


ESP8266 - How to know if incoming connection is from AP or station network? I have an ESP8266 module connected with my Arduino configured as a server, with both AP and station modes (AT+CWMODE=3) activated, and I want to know if an incoming connection comes from the AP's network or the station's network. This is the package I'm receiving, and it's exactly the same whether it comes from one or another network:

+IPD,0,437:GET /?uuid=7be547af980d13c5&cmd=10 HTTP/1.1
Host: 192.168.0.222:51813
Connection: keep-alive
Cache-Control: max-age=0
Accept: */*
Origin: http://127.0.0.1:8020
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36
DNT: 1
Referer: http://127.0.0.1:8020/domo_ctrl/www/index.html
Accept-Encoding: gzip, deflate, sdch
Accept-Language: es-419,es;q=0.8,en;q=0.6

At first I thought that it would reject packages addressed towards another IP (AP's IP is different from station's IP), but since this IS the gateway, it receives ALL incoming traffic. Please help!

EDIT:

This is the firmware and other stuff shown by AT+GMR:

AT+GMR

AT version:1.1.0.0(May 11 2016 18:09:56)
SDK version:1.5.4(baaeaebb)
Ai-Thinker Technology Co. Ltd.
Jun 13 2016 11:29:20
OK

I don't think the default AT firmware allows to automatically reject packets because that would probably require a higher degree of control, but looking at the Expressif documentation about the AT command set I've discovered you can actually retrieve the remote address rather than the local one, just by using the same command you were using but with a different parameter

AT+CIPDINFO=1

Not sure though this actually might solve your problem.


Port D isn't Working as Input I'm using an Atmega328p SMD with 32 pins.  I'm trying to get several pins on Port D to function as inputs.  As outputs, they work fine, but for some reason, not as inputs.  Here's a simple example of what I'm dealing with.

void setup() {

DDRB |= (1<<PB3);  //Set up an output on PB3 for an LED
DDRD = B00000000;  //All of Port D set as inputs
DDRC = B00000000;  //All of Port C set as inputs
}

void loop() {

int Power = (PIND & (1 << PORTD5));  //Read input

  if(Power == 1){
PORTB |= (1 << PORTB3);      //set high
  }
  else{
  PORTB &= ~(1 << PORTB3);  // set  low
}

I get no response from my LED like this, no matter which pin on Port D I use as an input.  But when I simply change over to Port C, it works fine.

int Power = (PINC & (1 << PORTC5));  //Read input

Ideas?

You check if power is 1, but it will never be 1. Instead it will be 1<<5 or 32. Better use:

if(Power != 0){
  PORTB |= (1 << PORTB3);      //set high
}
else{
  PORTB &= ~(1 << PORTB3);  // set  low
}


Store button presses in an array and sequince it with the LEDs Example: If the user presses the button sequence 1-2-2-1 then the LEDs light up in the order 1-2-2-1
int userAmount[4];
const int ledPins[] = {4, 5};
const int btnPins[] = {8, 9};

int buttonState_1 = 0;

void setup() {
  Serial.begin(9600);
    for (int n = 0; n < 4; n++)
     {

     }
     pinMode(PIN_BUTTON_1, INPUT_PULLUP);
}

void loop() {
  buttonState_1 = digitalRead(PIN_BUTTON_1);
   if (buttonState_1 == LOW)
      {
        for (int i = 0; i < 4; i++)
        {

        }
      }
}

Start by writing a sketch that debounces your buttons to get an accurate count of each button press. Install the Bounce2 Library available in the IDE.
Use a byte array to store the sequence of button presses (record the pin numbers).
Once the pre-set limit (sequence length) is reached, play back the sequence.
Playing back the sequence could look something like this:
const byte ledPin1 = 4;
const byte ledPin2 = 5;
const byte sequenceLength = 4;
byte sequence[sequenceLength] = {4, 5, 5, 4};

void setup(){

  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  digitalWrite(ledPin1, LOW);
  digitalWrite(ledPin2, LOW);

  for(byte i = 0; i < sequenceLength; i++){
    if(sequence[i] == ledPin1){
      digitalWrite(ledPin1, HIGH);
      digitalWrite(ledPin2, LOW);
    }
    else{
      digitalWrite(ledPin1, LOW);
      digitalWrite(ledPin2, HIGH);
    }
    delay(500);
    digitalWrite(ledPin1, LOW);
    digitalWrite(ledPin2, LOW);
    delay(500);
  }

}

void loop(){}

EDIT: Adding a couple of buttons using the Bounce2 library is a trivial task.
// Arduino IDE 1.8.9
// Sketch uses 1696 bytes (5%) of program storage space.
// Global variables use 30 bytes (1%) of dynamic memory,
#include <Bounce2.h>
const byte ledPin1 = 4;
const byte ledPin2 = 5;
const byte buttonPin1 = 8;
const byte buttonPin2 = 9;
const byte sequenceLength = 4;
byte sequence[sequenceLength];
byte counter = 0;

Bounce button1 = Bounce();
Bounce button2 = Bounce();

void setup(){

  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  digitalWrite(ledPin1, LOW);
  digitalWrite(ledPin2, LOW);

  pinMode(buttonPin1, INPUT_PULLUP);
  pinMode(buttonPin2, INPUT_PULLUP);

  button1.attach(buttonPin1);
  button1.interval(50);
  button2.attach(buttonPin2);
  button2.interval(50);

}

void loop(){

  if(button1.update()){
    if(button1.read() == 0){
      addToSequence(ledPin1);
    }
  }

  if(button2.update()){
    if(button2.read() == 0){
      addToSequence(ledPin2);
    }
  }

  if(counter == sequenceLength){
    for(byte i = 0; i < sequenceLength; i++){
      if(sequence[i] == ledPin1){
        digitalWrite(ledPin1, HIGH);
        digitalWrite(ledPin2, LOW);
      }
      else{
        digitalWrite(ledPin1, LOW);
        digitalWrite(ledPin2, HIGH);
      }
      delay(500);
      digitalWrite(ledPin1, LOW);
      digitalWrite(ledPin2, LOW);
      delay(500);
    }
    counter = 0;
  }
}

void addToSequence(byte pinNumber){
  sequence[counter] = pinNumber;
  counter++;
}


How To Make LCD Shield Button Code Work with Pot I am trying to convert this code into something useable with a potentiometer and push button because I don't have a lcd shield and dont feel like wiring that many buttons.  I want the pot to have options 1-4 depending on resistance and the push button will select. However I don't understand the code so I was wondering if anyone new a good way to convert it.
Here is part of the code that I need to change:

    #define BUTTON_ADC_PIN           A0  // A0 is the button ADC input
#define LCD_BACKLIGHT_PIN         3  // D3 controls LCD backlight
// ADC readings expected for the 5 buttons on the ADC input
#define RIGHT_10BIT_ADC           0  // right
#define UP_10BIT_ADC            145  // up
#define DOWN_10BIT_ADC          329  // down
#define LEFT_10BIT_ADC          505  // left
#define SELECT_10BIT_ADC        741  // right
#define BUTTONHYSTERESIS         10  // hysteresis for valid button sensing window
//return values for ReadButtons()
#define BUTTON_NONE               0  //
#define BUTTON_RIGHT              1  //
#define BUTTON_UP                 2  //
#define BUTTON_DOWN               3  //
#define BUTTON_LEFT               4  //
#define BUTTON_SELECT             5  //

I think what may be most helpful is an explanation of some tools which would serve you well on this.  In order to use the potentiometer to select different options, a simple solution would be along these lines:

Read the potentiometer value.
Check which range the value fits in.
Perform a corresponding action.

Here is one idea for accomplishing this:
Read the potentiometer value:

int reading = analogRead(A0);

Check which range the value fits in.

if(reading < 1023/4){
    //Action 1
}else if(reading < (1023/4)*2){
    //Action 2
}else if(reading < (1023/4)*3){
    //Action 3
}else{
    //Action 4
}

Perform a corresponding action.

//Do something cool.


Will there be any pin interference in this Project? I am working on a project with Arduino Uno Clone. After having a look on my arrangement, please tell me whether I will have to face any difficulty or consider any thing.

I have a relay on pin 2 (drive An Induction cooktop from AC Mains),

6 mini 9g servo from pin 3-8 (want to drive non-pwm pins with any Software library),

a 8 ohm speaker on pin 9,

a microSd card module from pin 10-13 (play .wav files through speaker),

5 pushbuttons from pin A0-A4,

a toy dc motor on A5 (Drive through a transistor). So my questions are:

Will I have to face any pin arrangement problem in my project? If yes, please give me a solution
I have six servos and a dc motor in which only one will be moving at a time, is there really a need of external power source for motors
I have to drive this arrangement through AC Mains, but i dont want to buy An adapter. I have a mobile charger which have written "INPUT 100-250V AC, OUTPUT 4-12V, 800mA" , can I drive my arduino with this?
Can I boost the volume of my speaker by using a transistor or capacitor (I have no idea about amplifier IC) ?
I have to include these librairies, SD library, tmrpcm, SPI, servo, and any one extra to drive servos on non-pwm pins. What would be the total size because my arduino has only 30kb approx?  Thanks To Give Me Time. Please help me.

possibly you will face problems with current drain and timing. There is no ready made solution. You have to get a bit farther by yourself and come back with detailed descriptions of your problems.
check on other threads (google) the issues with driving directly a coil. There are plenty of explanations why you need to be careful about it.
you should at least try to do the math yourself, then ask for verification. Try to calculate the power requirements of each component (average, maximum, peak) and add them up for every scenario. The you can report your finding and ask for confirmation/advice.
Sure you can, there are plenty of solutions available, but you have to define your requirements and constraints. Then it's easy to pick one solution (or at least google for it).
Just try to include them in the project and compile them. It's fast and you will get the answer immediately. There are ways to optimize things, but first you should assess if it's needed.

All in all, to get more help, you should show more in detail what you have already done, what are your concerns and why.


How to properly construct objects on ATmega2056? I was wondering the correct method to construct objects for use in the setup and loop scopes. I tried working constructing in the global scope, but I get garbage values printed to serial (probably from misusing pointers)? If I use the new keyword, then it works, but I heard that that is not best practice.

I is there a better way I should do this?

// navigator.cpp

#include "navigator.h"

Navigator::begin(Waypoint* w, int count) {
  waypoints = w;
  pointCount = count;
  next = 0;                               // start with first waypoint
  course = 90;                          // Notice that initial course is due East

  Serial.println('here');
}

-

// navigator.h

#define _navigator_h

#if defined(ARDUINO) && ARDUINO >= 100
  #include "Arduino.h"
#else
  #include "WProgram.h"
#endif

struct Waypoint {
  double lat, lon;
};

class Navigator {
public:
  begin(Waypoint* w, int);
};

#endif

-

// TransAt.ino

#include "navigator.h"

Waypoint w = { 43.36, -75.1 };  // These objects must be accessible in both setup() and loop(), but we can't use the new keyword
Navigator nav();                    // That means we have to do a lot of the heavy lifting here

uint32_t timer = millis();

void setup() {
  nav.begin(&w, 1);
}

void loop()
{

}

I tried working constructing in the global scope, but I get garbage values printed to serial ...

Constructors in global scope are called before init and setup and thus are probably executing too soon for you. This would account for the garbage printed to serial, because your constructor is printing before the Serial.begin() call.

You can put constructors in global scope, however they should do fairly trivial things (eg. setting a counter to zero, or a pointer to NULL). Do not rely upon the system being initialized, thus do not call functions like millis, nor should you be using dynamic memory allocation at this point.

Most classes defer their "real" initialization to a begin function (eg. Serial.begin) because it is safe to do that, usually in the setup function.


What is Vin for the EthernetPOE board? I am working on a project that needs to drive a relay board. I'm looking at the ETHERNET board with PoE and according to the documentation here (http://arduino.cc/en/Main/ArduinoBoardEthernet) the output of the PoE module is 9V.

Is that the voltage to expect out of the Vin pin?

The Relay board that I want to use (http://numato.com/downloads/dl/file/id/29/product/47/user_manual.pdf) specifies that it wants a 7-12V power supply.

I want to confirm that this is the case so I can use the voltage out of the PoE and I don't need to add a separate DC power supply to this system.

Your question is a little confusing, so let me give you a couple pieces of information.

First things first - the VIn pin on the Arduino is strictly for power going to the Arduino board, you shouldn't be drawing power from this pin. The documentation in the link you sent is a little misleading on this - it's basically saying 9v is coming OUT of the PoE module, and going IN to the VIn on the Arduino itself. If you wanted to tap into this 9v power, you should connect to the PoE module VOut instead.

PoE by default can deliver 37-57 volts or 42-57 volts, depending on what type of PoE you're using (which 802.3 specification). Wikipedia has a good overview of this information.

That being said, the Arduino Ethernet board you're using can't handle this voltage by itself - unless these boards have changed, they require an additional PoE module, which is basically just a DC-to-DC buck converter that will convert the high PoE voltage down to 9v or 12v. At this point, the Arduino's built-in converter can consume that 9 or 12v and distribute it at 5v across the board.

Now, to your problem - you want to power a relay that requires 7-12v. You could theoretically connect the relay to the VOut of the PoE module, giving you 12v. However, if the relay draws too much power for too long, you will either get brownouts (and your Arduino will restart) or potentially damage the Arduino board. Unless the relay draws a lot of current or is being powered for extended periods, you should be fine. If you want to be more thorough, you could put a large capacitor between your PoE module and the relay.

You should NOT try to connect the relay directly to the PoE VOut, as the voltage will be far too high.


Problem activating HC-05 AT command mode with Arduino Uno Bluetooth shield Please be gentle with me. I am attempting to modify the configurations of my HC-05 bluetooth module by using the AT command set. The method by which I'm trying to do this is by implementing the following connection:

HC-05 GND --> Arduino GND;
HC-05 3.3v --> Arduino 3.3V;
HC-05 TX --> Arduino Pin 10;
HC-05 RX --> Arduino Pin 11;
HC-05 KEY --> Arduino Pin 9

This is the code which I uploaded to my Arduino (btw my arduino uno is an SMD clone): (code's from http://www.instructables.com/id/Modify-The-HC-05-Bluetooth-Module-Defaults-Using-A/step2/The-Arduino-Code-for-HC-05-Command-Mode/)

#include <SoftwareSerial.h>

SoftwareSerial BTSerial(10, 11); // RX | TX

void setup() {
  pinMode(9, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
  digitalWrite(9, HIGH);
  Serial.begin(9600);
  Serial.println("Enter AT commands:");
  BTSerial.begin(38400);  // HC-05 default speed in AT command more

 }

void loop() {
  // Keep reading from HC-05 and send to Arduino Serial Monitor
  if (BTSerial.available())
    Serial.write(BTSerial.read());

  // Keep reading from Arduino Serial Monitor and send to HC-05
  if (Serial.available())
    BTSerial.write(Serial.read());

}

The problem is I can't seem to activate the AT mode. I don't get any response from the Serial Monitor whatever AT command I try. I double-checked the wiring and it's all good. I can't figure out what the problem is.

After 3 hours I magically solved my pretty simple problem myself. If you wired the HC-05 and arduino correctly, the module should indicate that it's in AT Mode by blinking the LED in an interval of 2 seconds. You should get response in the Serial Monitor by typing the AT commands by switching from "No line ending" to "Both NL and CR". That's about it.


Arduino UNO R3 possibility Can I use an ultrasonic sensor, ir sensor, serial communication with MATLAB on computer and i2c communication with a D6T MEMS thermal sensor simultaneously in Arduino UNO ?

Yes, it is possible for the arduino handle communicating over serial and I2C in real time, I've done it frequently. The IR sensor should not pose a problem either.

The ultrasonic sensor might use a timed pulse to send its information that can take a relatively long time, and the basic ultrasound code will just wait for it to finish without doing anything else. The delay itself will not cause you problems but if a lot of data is being sent to the arduino very quickly over serial it might miss some. These delays can be worked around with interrupts/some clever coding but I doubt it will ever be a problem.


Loop code without manually pressing the button In a piece off code I am modifying I have a button connected to start the code and then it resets its self afterwards. Is they a way to make the arduino loop that code without manually pressing the button again?

This is a section off the code:

#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
  #include <avr/power.h>
#endif
#define PIN 6
#define BUTTON_PIN 9

Adafruit_NeoPixel strip = Adafruit_NeoPixel(120, PIN, NEO_GRB + NEO_KHZ800);

bool oldState = HIGH;
int showType = 0;

void(* resetFunc) (void) = 0; //declare reset function @ address 0

void setup() {
  pinMode(BUTTON_PIN, INPUT_PULLUP);
  strip.begin();
  strip.show(); // Initialize all pixels to 'off'
}

void loop() {
  // Get current button state.
  bool newState = digitalRead(BUTTON_PIN);

  // Check if state changed from high to low (button press).
  if (newState == LOW && oldState == HIGH) {
    // Short delay to debounce button.
    delay(20);
    // Check if button is still low after debounce.
    newState = digitalRead(BUTTON_PIN);
    if (newState == LOW) {
      showType++;
      if (showType > 9)
        showType=0;
      startShow(showType);
    }
  }

  // Set the last button state to the old state.
  oldState = newState;
}

void startShow(int i) {
  colorWipe(strip.Color(75, 0, 0), 50); // Red
  colorWipe(strip.Color(0, 75, 0), 50); // Green
  colorWipe(strip.Color(0, 0, 75), 50); // Blue
  theaterChase(strip.Color(75, 75, 75), 50); // White
  theaterChase(strip.Color(75, 0, 0), 50); // Red
  theaterChase(strip.Color(0, 0, 75), 50); // Blue
  rainbow(20);
  rainbowCycle(20);
  theaterChaseRainbow(50);
  resetFunc();  //call reset
}

Thanks Reece

As pointed out by Delta_G, there is no point in resetting your program.
What you should do is think your program in terms of the Arduino logic:

You put in setup() the code you want to run when your program
starts.
You put in loop() the code you want to run over and over again.

In this case loop() is fairly simple, as the stuff you want to run
over and over again is the animation, thus:

void loop() {
  colorWipe(strip.Color(75, 0, 0), 50); // Red
  colorWipe(strip.Color(0, 75, 0), 50); // Green
  colorWipe(strip.Color(0, 0, 75), 50); // Blue
  theaterChase(strip.Color(75, 75, 75), 50); // White
  theaterChase(strip.Color(75, 0, 0), 50); // Red
  theaterChase(strip.Color(0, 0, 75), 50); // Blue
  rainbow(20);
  rainbowCycle(20);
  theaterChaseRainbow(50);
}

Note that I removed the call to resetFunc().

The stuff you want to do at startup is the initialization. Oh, wait. In
a comment you wrote “I want to wait for the button press”. So this also
has to be done before the program starts looping. Hence your setup()
should initialize stuff, then wait for the button press:

void setup() {
  // Initialize the strip to all piwels off.
  strip.begin();
  strip.show();

  // Wait until the button is pressed.
  pinMode(BUTTON_PIN, INPUT_PULLUP);
  while (digitalRead(BUTTON_PIN) == HIGH)
      ; // do nothing
}


Receiving and sending on the Arduino Duemilanove with an MAX3232 chip I have a max3232 hooked up to the RX and TX pins of the Arduino Due.  I'm trying to write a simple program to relay messages received from USB and output as RS232 through the chip.  Here is my code:

char readbyte;

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

void loop(){

  while (Serial.available() > 0 ) {
    readbyte = Serial.read();
    Serial.print(readbyte);
  }
}

This program works when I don't have the MAX2323 hooked up (e.g. I send "123" and get "123" echoed back), but when I hook up the MAX2323, the Arduino isn't sending back.  I've written another test program that sends random data and it seems to work fine.  I'm at a lost at what is wrong with my simple program, can anyone help?

Here is the schematic:

With your final comment, the behavior is understandable.  The schematic will help

You have wired two devices to the single UART on the processor.

The TX pin (output) on the ATMEGA8 is connected to the input pins of both your MAX2323 and the FT232 chip on the Ardiuno.  That works okay because 1 output pin can easily drive 2 inputs.

The RX pin (input) on the ATMEGA8 is connected to the output pins of both your MAX and FT.  The two transceivers are both attempting to drive the single input -- this is a bad thing.  When one output pin tries to drive logic 1 and the other is driving logic 0, one of the devices will win and one will lose.  Whether any of the devices is physically damaged depends on whether one device can source enough current to damage the other.

But you haven't broken anything because of the wise series resistors, R8, you see on the schematic.  The series resistor limits the current to 5 mA even if you short the RX pin to ground.  The series resistor is what creates the unequal behavior:

The ability of the FT chip to source current and drive a logic 1 is limited. So when the FT chip tries to drive logic 1 and the MAX is output 0, a 5 V drop will be seen across R8.  The RX pin is on the MAX side, so the Arduino sees 0.
The MAX chip is not limited.  When it drives 1 and the FT is at 0 there is still 5 V across the resistor.  But the RX pin is on the MAX side and sees the 1's (data).

If you want the Arduino to receive from two devices you need to "add" the data correctly with a circuit.  There are several ways, here are two:

Use an OR gate to combine the data.  The serial bus is idle at zero.  When data comes across it is a sequence of 1 bits.  Remove R8 and connect the M8RXD side to the OR input.  Connect the MAX to the other OR input.  Connect the OR output to the RX input.
Cheap and small is "wire or'd".  Remove R8 and replace with small diode, pointing at RX.  Connect small pull down resistor (10k) from RX to ground.  Connect external MAX with diode pointing at RX.  In this arrangement, either chip will source current towards the RX ping to drive a logic 1, but neither chip can sink current to drive the logic 0.  Only the pull down resistor creates the 0.


How to limit the number of message that an Arduino sends to a phone without terminating it I just stayed on delay() since that is the only thing I know but the thing is delay() cannot be interrupted. What I'm trying to achieve with this code is:

When the soilSensor detects moisture it would send a text message to a number only ONCE without terminating the program even if in the next loop the soilSensor is still detecting moisture.
The soilSensor's delay is delay(60000) and we would still wait for while to finish the delay but what if in the middle of the soilSensor's delay(60000) there is a movement for just about 5 seconds? What to do so that the tiltSensor can overlap the soilSensor's delay and sends a message to a number?

I want this program to run forever. Please help me! I needed this ASAP!

#include <SoftwareSerial.h>
SoftwareSerial SIM900(7, 8);
int led=22;

void setup()
{
  Serial.begin(9600);
  SIM900.begin(19200);
  pinMode(led, OUTPUT);
  delay(1000);
}

void sendSMS1()
{
  SIM900.println("AT + CMGS = \"+************\"");
  delay(100);
  Serial.println("Water Detected");
  delay(100);
  SIM900.println("Water Detected");
  delay(100);
  SIM900.println((char)26);
  delay(100);
  SIM900.println();
  delay(100);
}

void sendSMS2()
{
  SIM900.println("AT + CMGS = \"+************\"");
  delay(100);
  Serial.println("Movement Detected");
  delay(100);
  SIM900.println("Movement Detected");
  delay(100);
  SIM900.println((char)26);
  delay(100);
  SIM900.println();
  delay(100);
}

void loop()
{
  int soilSensor = analogRead(A0);
  int tiltSensor = analogRead(A1);

  if(soilSensor >= 10)
  {
    digitalWrite(22, HIGH);
    Serial.println(soilSensor);
    sendSMS1();
    delay(60000);
  }
  else
  {
    digitalWrite(22, LOW);
    delay(60000);
  }

  if (tiltSensor >= 100)
  {
    digitalWrite(led, HIGH);
    Serial.println(tiltSensor);
    sendSMS2();
    delay(60000);
  }
  else
  {
    digitalWrite(led, LOW);
    Serial.println(tiltSensor);
    delay(60000);
  }
}

You use millis() to keep track of time and also prevent blocking. Replicating your program logic:

long soil_timer = 0;
long tilt_timer = 0;
char soil_flag = 1;
char tilt_flag = 1;

void loop() {
    int soilSensor = analogRead(A0);
    int tiltSensor = analogRead(A1);

  if (soil_flag == 1) {
    if (soilSensor >= 10) {
      digitalWrite(22, HIGH);
      Serial.println(soilSensor);
      sendSMS1();
    }
   else {
      digitalWrite(22, LOW);
    }
    soil_timer = millis();
    soil_flag = 0;
  }

  if (tilt_flag == 1) {
    if (tiltSensor >= 100) {
       digitalWrite(led, HIGH);
       Serial.println(tiltSensor);
       sendSMS2();
    }
    else {
       digitalWrite(led, LOW);
       Serial.println(tiltSensor);
    }
    tilt_flag = 0;
    tilt_timer = millis();
  }
  if (millis() - soil_timer >= 60000){
     soil_flag = 1;
  }
  if (millis() - tilt_timer >= 60000){
     tilt_flag = 1;
  }
}


Can I design Arduino Mega 2560 circuit without adding ATMega 16? I want to make Arduino Mega 2560 board.
As the reference files are given on Arduino Site, I don't want to add USB communication on the board.
So can I remove part of ATMega 16?
Will it cause any kind of problem in working of board?
And if It will fine to remove ATMega 16 part, How much part of schematic to be change?

Yes, you can omit the ATmega16U2 and its accompanying parts. That is, the whole right block of schematic in this sheet.

The resulting board will work perfectly fine, it will simply no longer have a built-in programming interface, nor a built-in USB-serial interface. You will likely want to buy an FTDI cable and an AVR programmer, if you do not already have these.


Function declared in another file not recognized (undefined reference to) I am making a multi-file arduino project, but the compiler can't recognize a function.
I am using the arduino-cli version 0.10.0
This is the error I received
undefined reference to pin_init() collect2.exe: error: ld returned 1 exit status Error during build: exit status 1
This is the command:
arduino-cli compile -b arduino:avr:uno C:\Users\Cioccarelli\Desktop\transmitterCopy\main

main.ino:
#include "C:\Users\Cioccarelli\Desktop\transmitter\automation\automation.h"

void setup() {
    pin_init();
}

void loop() {}

automation.h:
#pragma once

// This is where the components input pins are stored, they are put here by the add_pin function
byte pinSetup[0];
byte pinSetupSize = 0;

// This function is called in the setup() and it initializes every pin listed in pinSetup[] as input
void pin_init();

automation.cpp:
#include "C:\Users\Cioccarelli\Desktop\transmitter\automation\automation.h"

extern pinSetup;
extern pinSetupSize;

void pin_init() {
    for (int i = 0; i < pinSetupSize; i++)
        pinMode(i, INPUT);
}

I think this issue might have to do with the fact that I don't completely understand file inclusion, but I haven't found anything useful in my research

Update: today I rebuilt the project with different names and I cut everything which wasn't related to the problem, in hope to identify it.
new main:
#include "C:\Arduino\transmitter\nightmare\nightmare.h"

void setup() {
    pin_init();
}

void loop() {}

new automation.h (nightmare.h):
#pragma once

// This function is called in the setup() and it initializes every pin listed
//in pinSetup[] as input
void pin_init();

new automation.cpp (nightmare.cpp):
#include "C:\Arduino\transmitter\nightmare\nightmare.h"

void pin_init() {}

new file structure:

I also made a copy and made some changes so it could become a C++ file
(substituting the setup() with main() and replace every "byte" type with "int")
I then put it in Visual studio, it compiled perfectly.
The arduino IDE gives the same error

The compiler didn't have a problem; the linker did. That is, once your main function was compiled (correctly) to call pin_init(), the loader tried to put together all of the compiled modules and link up calls that were not satisfied locally - within the same file - to functions defined in another module. That is when this message got generated. No such function definition was found, despite the declaration of it in main.ino.
If you can compile this with the Arduino IDE, watch what it does: It will compile each of your source-code modules, one at a time. Then link all of your modules' compiled versions together to produce the .hex file (that will eventually get uploaded to the Arduino). You need to mimic that when you're compiling & loading from the command line.
Update:

today I rebuilt the project with different names

Is your .cpp file in the same folder as your .ino file? Or in another folder, such as the folder containing your .h file? I suspect it's the latter. When I built your project it in the Arduino IDE, it succeeded when the .ino and the .h were in the same folder, failed exactly as you described when I moved the .cpp file to where the .h file is.
The solution goes back to what I suggested earlier; that no definition of pin_input() was found, as the .cpp file containing it wasn't seen by the IDE (or your command-line compiler) and therefore not compiled and linked. Each of your files needs to be compiled and all of them together need to be linked, for the external calls to be satisfied.
With the IDE, put your project's .ino and .cpp files in the same folder so the IDE will see and compile each of them and know what to files to link. The IDE won't give you much flexibility for locating your .cpp files.
With the command line compiler, you can put your files wherever you will, make a separate[1] compile only run for each of them, then make another run of the linker component[2] naming all of the compiled units (the IDE names them as .d) and provide the path to your library folder(s).
[1] I'm not familiar with the command-line compiler's command-line syntax; maybe you're able to specify a number of compiles with one command.
[2] Again, IDK whether you need invoke the linker with the same command but with a link-only option switch, or you'll need to invoke the linker yourself, on the command line.


Timer with ajustable time delay I have a led strip, and each led should be turned on sequentially, such as this one:
[http://1.bp.blogspot.com/-CTT6yvYtdos/VihhhBItwjI/AAAAAAAAAvM/q1jbUylMMdM/s400/ezgif.com-video-to-gif.gif][1]
The time delay between 2 consecutive leds is ts, and that time should be adjusted externally through a pushbutton switch. Each time the button is pressed, the time period shoud increment in a fixed amount.
I've already used the timerOne library, but it just works with a fixed time delay ts. How can I solve this issue with VARIABLE time delay?
I prefer to use interruptions rather than polling, since this system will be more complex (other buttons and variables will be involved).
Thanks!
Fernando

https://github.com/PaulStoffregen/TimerOne/blob/master/TimerOne.h#L55

Defines the function in TimerOne called SetPeriod(). That will change the period.


Regarding Strings and assignments I have this code which works :

String ErrorMsg;
.......
if(!UploadPacketError)
{
    ErrorMsg="OK";
}
else
{
   ErrorMsg="NOK";
}

String creates a dynamically allocated array which I want to avoid. I would prefer something like :

unsigned char ErrorMsg[5];
......
if(!UploadPacketError)
    {
        strcpy(ErroMsg,"OK",3); // +1 for the Null Termination ?
    }
    else
    {
       strcpy(ErroMsg,"NOK",4); // +1 for the Null Termination ?
    }

i.e. is there a way to dynamically assign a value to a fixed size character array ?

Cheers
Thomas

Almost.

First it's char not unsigned char:

char ErrorMsg[5];`

Second you don't specify a size with strcpy:

strcpy(ErrorMsg, "OK");

There is a variant of strcpy called strncpy which copies at most n characters:

strncpy(ErrorMsg, "OK", 5);

That is used to prevent buffer overruns. But when working with string literals like that it's pretty pointless.


Privacy of a program I have created a algorithm and using arduino harware, and I don't want that users of my hardware could read or copy the Program so is there any security code or something that I could use. But I must access it whenever I needed to. It should be like admin and users.

The code that's sent to Arduino is "compiled" which means it's changed from human readable form to a binary data that can be understood by the processor. The "code" you wrote remains on your computer only.

This itself is a way of encryption since it's impossible to retrieve the original source code from that binary data. That data can only be "decompiled". This is a process that takes the binary data and converts it automatically into a human readable code, but it's not the same code that you originally made. It doesn't have comments, and logical variable names. This makes it also hard to understand.

Decompilation is usually to difficult and time consuming to even bother doing that unless your hardware is a lock on a vault with million dollars inside. If that's the case don't use Arduino, but instead use a custom designed chip with cryptographic key built inside the hardware.


Has anybody seen/created a gps guided vehicle with arduino? I thought the idea of Amazon Prime air drone delivery was a pretty cool one when it first came out and I started to question whether something like that (an autonomous gps guided vehicle) could possibly be created with the Arduino microcontroller(s). Any thoughts?

Yes, someone (not me) has: https://www.youtube.com/watch?v=3-r2Jk0uA6U

I doubt it would work very well with non-flying vehicles - in the air, a 3 meter margin of error is fine, on the ground it's the difference between the sidewalk and the middle of the road.


Can it time between blips, store the time between blips, subtract one time from the other and divide one time by another and display it? I am counting rotations of a shaft and timing events that occur during that rotation.  I wish to display
the event timing as a percentage of ~1/4 of the rotation timing.  This would involve recording the rotation time, dividing that number by 3.6 and dividing that number by the value of the event timer, then displaying that percentage on an LCD array.

What you are looking for is the millis() function.
It returns the time that passed in milliseconds since the board power up.
With this function you can find the time delta, and achieve all the described calculations.
For more information


Inaccurate and non-precise voltage reading from Arduino Analog pin float get_volt() {
  rawVolt = analogRead(voltageSensor);
  vOUT = (rawVolt * 4.6) / 1024.0;
  vIN = vOUT / (R2/(R1+R2));
  //if(vIN>12.0){vIN=12;}
  //if(vIN<11.12){vIN=11.12;}
  //return (vIN - 10.18) * (100 - 0) / (12.0 - 10.18) + 0;
  return vIN;
}

I am using a voltage sensor module which has a voltage divider with R1=30K Ohms and R2=7.5K Ohms and can measure up to 0-25V by using 10-bit Analog pin of arduino. the battery voltage comes as 11.4 volts when measured with a multimeter but I am getting an inaccurate reading from arduino ranging from 10.8 to 11.4. the Arduino voltage reference is stable at 4.6 V. Please help me to fix this, you can see the voltage reading in the image
PS: the battery and arduino are connected to the same ground.

edit1: adding 0.1uf capacitor helped to improve from this

to this!

the data is taken for over a period of 1 hr at every 5 seconds, its a 12V 4000 mAh battery

This should be a lot of fun but you might consider doing some research on analog circuits and A/D circuits. You have way too many digits to the right of the decimal, the accuracy is not there. The best you can get is 0.0044 volts per count with a 4.6v reference. What are you using to make your measurements, you need at 5 1/2 digit meter to have the decade better accuracy then what you are calibrating to. Your reference you state is 4.6 volts, something is not correct is should be 5.000V. You know any load placed on the on board regulator will have an effect on your A/D readings. The tolerance of the resistors you are using will have an impact on your reading. They generate noise that could be affecting your readings. 100nF should be enough capacitance,this will lower the input impedance. Increasing capacitance beyond this will slow the settling time of the circuit. If you are powering this from a computer USB expect noise from that power source, That would also explain the lower reference voltage on the A/D. With what you indicate you have, you are actually doing very well.


Can ESP 32 use the wire library exactly like that was in Arduino? Compare the YouTube video and this webpage, the former one made programming very different in ESP32 and that was in Arduino nano, while the webpage seemed to imply that they work exactly the same.

Can we use the same code for standard Arduino library, like wire library, for ESP32 and ESP8266, or do we have to do something different?

Code using the Arduino Wire library is generally portable between processors, but there are pitfalls to watch for.  One that I'm aware of is a difference in the Wire libraries for the ESP32 and ESP8266. The TwoWire::begin() method for the ESP32 has prototype:
bool TwoWire::begin(int sdaPin, int sclPin, uint32_t frequency);

whereas for the ESP8266 it is:
void TwoWire::begin(int sda, int scl, uint8_t address);

So, a call to begin() using the ESP#2 library will set the clock using the third parameter, whereas on the ESP8266 it will truncate the third parameter and use it as an address.
If you wish code to be portable between the ESP32 and ESP8266, then the fix for this particular issue is to call TwoWire::begin( my_SDA_pin, my_SCL_pin ) (specifying only two parameters:the SDA and SCL pins), and use a separate call to TwoWire::setClock( my_clock_speed ) to set the clock.
There may be other differences I'm not aware of...


NEMA17 and DRV8825 200 steps give only half revolution I have this code:

#include <stdint.h>

# define STEP 14

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

long steps = 0;
void loop()
{
    if (steps < 200)
    {
        digitalWrite(STEP, digitalRead(STEP) ^ 1);
        delay(10);
        steps++;
    }
}

Simple implementation and I have a nema17 motor with 1.8 degrees per step, which should give 200 steps per revolution, but I only have half a revolution on 200 steps, I tried connecting all MODEx pins to VCC and this should give me 6400 steps per revolution but 6400 steps also gives mi half an revolution.
Could there be an issue with the wiring of the motor? Why don't I receive a full revolution?
By full revolution I mean that the motor shaft should complete the whole circle but it completes only half.

See page 33 of the DRV8825 datasheet https://www.ti.com/lit/ds/symlink/drv8825.pdf.

DRV8255 moves the stepper on a rising edge in the signal.

That requires the signal to go low, then high.

That is two cycles of your program.

Add two lines to your code so that it is output low, delay 10, output high, delay 10


Python PySerial with Arduino fails byte check I'm struggling with my first steps with Python and PySerial. I have one Arduino which reads impulses from an electricity power meter, passes the counts over to another Arduino over an RF link and then sends the data over to an Raspberry Pi. The Arduino to Arduino communication works well. However the last step of passing this to the RPi fails.

The MeterValue from the Arduino side is an unsigned Long (32 bits) and therefore split in 4 pieces of 8-bit transmissions plus a frame start and frame end:

[0x01] Frame start
[0xMeterValueByte0]
[0xMeterValueByte1]
[0xMeterValueByte2]
[0xMeterValueByte3]
[0x04] Frame end

This is my Arduino code continuously sent to the RPi in debug purpose :

void loop() {
//static test loop
Serial.write(0x01); //start frame
Serial.write(0x00);
Serial.write(0x00);
Serial.write(0x02);
Serial.write(0x04); //end frame
delay(3000);

}

This is my Python code:

Import serial
ser = serial.Serial('/dev/ttyACM0',9600)
print("Connected to: " + ser.portstr)

inputbuffer=[]
inputbuffer = [0 for i in range(10)]

while True:
    if ser.inWaiting() > 0:
        inputbuffer = ser.read(1)
        print "Byte received"
        print "Inputbuffer[0]: " + hex(ord(inputbuffer[0]))

        j = inputbuffer[0]
        print "j= " + hex(ord(j))

This check of the "j" parameter somehow fails:

        if (j == 0x1): #look for start of frame
            print "Start found\n"
            print "Filling buffer\n"
            while ser.inWaiting() < 5: #hold here until 5 bytes arrived
                pass #proceed here
            inputbuffer +=ser.read(5) #read 5 bytes

            if inputbuffer[5] == 4: #check that the message has frame end
                RXval = inputbuffer[1]
                RXval |= (inputbuffer[2] << 8)
                RXval |= (inputbuffer[3] << 16)
                RXval |= (inputbuffer[4] << 24)
                print "RXval: ", RXval
            else:
                print "RX error, no frame end\n"
        inputbuffer = []

This is the Python output:

Connected to: /dev/ttyACM0
Byte received
Inputbuffer[0]: 0x1
j= 0x1
Byte received
Inputbuffer[0]: 0x0
j= 0x0
Byte received
Inputbuffer[0]: 0x0
j= 0x0
Byte received
Inputbuffer[0]: 0x2
j= 0x2
Byte received
Inputbuffer[0]: 0x4
j= 0x4

And then it repeats. Obviously the Python code doesn't realize j == 1. How should I handle the checking of the received bytes?

I think the problem is that you can't count ;)

Spot the difference:

0: [0x01] Frame start
1: [0xMeterValueByte0]
2: [0xMeterValueByte1]
3: [0xMeterValueByte2]
4: [0xMeterValueByte3]
5: [0x04] Frame end

and:

0: Serial.write(0x01); //start frame
1: Serial.write(0x00);
2: Serial.write(0x00);
3: Serial.write(0x02);
4: Serial.write(0x04); //end frame

Your receiver is looking for a pattern of 6 bytes, but your Arduino sketch is only sending a pattern of 5 bytes.

Your check for the start character is simple enough - you solved it fine a few lines above:

print "j= " + hex(ord(j))

But you forgot to do something similar for the check:

if (j == 0x1):

That should really be:

if (ord(j) == 0x1):


How can I save my float 'ave' on the EEPROM continuously? How can I save my output continuously to EEPROM? Or is this even possible? Please help me out.

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

void loop() {
  static unsigned long count = 0;
  static float sum = 0;
  float ave = 0;
  int volt = analogRead(A1);
  float voltage = map(volt, 0, 1023, 0, 2500) / 100.0;
  Serial.print("Voltage: ");
  Serial.println(voltage, 2);
  sum = sum + voltage;
  count++;
  ave = sum / count;
  Serial.print("Average: ");
  Serial.println(ave, 2);
  Serial.println("-----");
  delay(3000);
}

It's possible, but it's certainly not advised.

EEPROM has a limited number of writes before it's dead. By writing continuously to the EEPROM you will kill it in no time at all.


nrf24l01 (8pin) + adapter board (10pin) oops? I just got my first arduino boards and have been learning the basics (so I know very little). I got the 2.4GHz NRF24L01+ (this one: NRF24L01+) and along with it a breakout board (this one: NRF24L01+ board) which I didn't realize was 10pin (nor that there is an 8pin version) vs the wireless board's 8pin. So my question is, is it safe to connect the module to this adapter board in some way? From the pinout of both I would assume not, since for example the bottom two pins on the board are ground (and therefore connected together) and the ground pin on the NRF24L01+ is next to the VCC (NRF24L01+ pinout) and the top two on the board are both VCC 3.3 and from what I can tell by looking at the etched lines, it seems it leads to the resistors (not sure if they are resistors or what, like I said, I know very little still). There seems to be an LED on this board as well, connected to the AMS1117 chip (that's a voltage regulator, correct?).

So, I am guessing I cannot just connect the NRF24L01+ to the adapter board straight in, right? But, can it with some wires? Would that even make sense? Also, is this board even necessary for anything? I bought it having read something somewhere (been reading too much to keep track of where exactly) that recommended it, but a tutorial I saw today didn't make use of it, instead just soldering a capacitor to two of the pins saying some other place recommended it to reduce noise.

To be honest, I don't see much added value for this breakout board.

First, as you mentioned, you won't be able to plug your NRF24 directly into it because the pinout is not compatible; hence, you will have to use wires for that. But you could as well use wires directly from your Arduino to the NRF24 module.

Second, regarding power (you are right, AMS1117 is a voltage regulator), the Arduino 3.3V pin is enough (50mA for UNO) to power your NRF24 as its current consumption is low (max 13.5mA as per the datasheet):

Please note these are specifications for the chip itself not for the board, which may need a bit more current, but not much more according to my own experiments.

As a side note, I have created my own very simple breakout for the NRF24 board, with just a tiny piece of stripboard, that's something you can easily do by yourself if you have the right tools (saw, cutter, soldering iron), a few pin headers and some stripboard scrap:

Last, the only utility I see with your breakout board is to be used as 3.3V supply for higher currents in future experiments.

EDIT:

as commented by @Hans-Neve, a capacitor would be useful between 3.3V and GND pins, as near the NRF24L01 board as possible, so that short consumption peaks do not impact correct function of the board. The breakout board has one (or more exactly 2: 100nF and 10uF) It is advised you add those two (at least the large 10uF cap) in your circuit. I saw some people directly soldering one cap on the pins of the NRF24 board, but if you use short enough wires to connect it, you can perfectly put this cap on a breadboard during your experiments.


Broken Loop and dim LEDs I want to make 2 LEDs blink back and forth continuously, but they only do so once, and the second one is very dim.

code:

int ledone = 12;
int ledtwo = 10;
int keepgoing = 1;

void setup() {
pinMode(ledone, OUTPUT);
pinMode(ledtwo, OUTPUT);
}

void loop() {
 while (keepgoing == 1) {
  digitalWrite(ledone, HIGH);
  delay(80);
  digitalWrite(ledone, LOW);
  digitalWrite(ledtwo, HIGH);
  delay(80);
  digitalWrite(ledtwo, LOW);
  delay(500);
 }
}

I am using an Arduino Uno and one 220 ohm resistor for each LED.

I think the problem is, that your delays are just too short, so you see the blinking not as blinking, but as a dim lit led.

Maybe you can try the following code:

void loop() {
 while (keepgoing == 1) {
  digitalWrite(ledone, HIGH);
  digitalWrite(ledtwo, LOW);
  delay(500);
  digitalWrite(ledone, LOW);
  digitalWrite(ledtwo, HIGH);
  delay(500);
 }
}

Is this working?


Calculate how much battery power left I run my 12V car battery trough a trimpot into my pro micro, micro controller.
I am using (voltPinValue1 * 0.01465) to get the Volt out of analog in. I have trimmed the pots and getting the right V.

But now I want to calculate for how long I can run for, example the stereo and some LED:s, but don't know how.. Does anybody know how I can do this??

Sorry for my English

Thanks! //Rasmus

You really need to know the current being drawn rather than the instantaneous voltage. A voltage drop profile of a battery changes depending on the current draw, and just using the voltage is very very hard indeed.

You could measure the voltage over time, and try and calculate the slope of the voltage and attempt to predict when it would reach a specific pre-determined cut-off point, but since that change in voltage will be non-linear it's not really something that can easily be calculated.

But, if you can measure the current instead, and you know the Ah of the battery, then you can get a better estimate of how long the battery will run until it's considered flat.


Arduino Com port and PHP Bug so please read this whole thing.

My Project: I am making a bell system that is based on PHP. The bell is connected to the arduino UNO via a relay and the arduino is connected to the computer via a USB cable. The interface with the database is built with PHP and MySql. Then we have the code which checks every minuit if the bell has to be rung and if it does send a numeric value to the arduino. There is also an option for a longer bell if we send a '0' to the arduino.

My Code: So this is the file that checks if bell has to rung and sends value to arduino

<?php
include('database.php');
$usb_comPort = "COM3";
date_default_timezone_set("Asia/Kolkata");
$time = date("H:i");
$time = trim($time);
$sql = "SELECT bell_amount FROM bell_db WHERE DATE_FORMAT(bell_time,'%H:%i') LIKE '$time'";
$result = mysqli_query($conn, $sql);
$numRows = mysqli_num_rows($result);
if ($numRows == 0) {
  echo 'Error: Nothing found!';
} else {
  $row = mysqli_fetch_assoc($result);
  $bellAmount = $row['bell_amount'];
  $runCommand = "ECHO " . $bellAmount . " > $usb_comPort";
  echo $runCommand;
  exec($runCommand);
}
?>
<html>
<meta http-equiv="refresh" content="60">
<body>
</body>
</html>

and this is the arduino's code:

int b = 0;
void setup() {
Serial.begin(9600);
pinMode(10, OUTPUT); //relay
}

 void loop() {
  b = Serial.read();

    b = b - 48;
    if(b == 0){
      digitalWrite(10,HIGH);

      delay(3000);
      digitalWrite(10,LOW);
      }
    else{
    for (int i=0; i < b; i++){
      digitalWrite(10, HIGH);
      delay(200);
      digitalWrite(10, LOW);
      delay(200);
      }

    }

}

The Issue that i am facing: My aim is that the code should run automatically when the computer is turned on. The code works fine but there is random bug. The code is uploaded to the arduino. When the computer is turned on i want that the system should work but when i run the file  (the one that checks if there is a bell to be rung or not ) it processes the code but it is not able to send a value to the com port so the bell does not ring(the serial light on the arduino does not flash). But if i go to the arduino ide and send a value through the serial monitor once then run the php file, it works!

I am running this on a windows 10 computer, i have an arduino UNO and i have tried this with 2 arduino's same result on both.

So anyone know what i can do?

Sounds like the COM port is not setup. Opening the Arduino IDE probably does this automatically.

Try running the following command, only once, after turning on your pc to initialize the COM port.

mode COM3 BAUD=9600 PARITY=n DATA=8

Ps. I'm not a windows user, so this is an educated guess - reference.

Pps. I think you're winning the award for the most complicated way to ring a bell. :)