text:
Time remaining with os_timer_t
The Ticker library for the ESP chips is quite useful, which wraps a os_timer_t object. I'd like to be able to see the time remaining on the timer, is it possible to do that witha os_timer_t object?

The library just calls os_timer_setfn and os_timer_arm which will call the callback function after some time. To add the feature to see how many remaining time there is, you would need to extend the library (the Ticker class, specifically) to save a timestamp when the timer was started. You can then write a function which returns for how much time is remaining or has passed by doing uint32_t remaining = timestamp_now() - timestamp_started.
A good function to hook would be the _attach_ms in Ticker.cpp. Add a uint32_t timestamp_started variable in the Timer.h header for the class. Then set timestamp_started = system_get_time() (from user_interface.h). Then write a function uint32_t remainingUs() { return system_get_time() - timestamp_started; }. Beware of integer overflows -- system_get_time returns passed microseconds since µC startup.

I was hoping there would be an os_timer call to see this, but this will work well enough.

The documentation (http://espressif.com/sites/default/files/documentation/2c-esp8266_non_os_sdk_api_reference_en.pdf, section 3.1) lists no such call for os_timer objects.


text:
How can I find the time taken while a function is being called?
I tried using millis, but I wanted to know if there is any better way to find out the exact time from when a function is called and finally when it terminates.

micros() is more exact.

Here is a set of macros for benchmarking functions https://github.com/mikaelpatel/Arduino-GPIO/blob/master/src/benchmark.h. They can be used like this https://github.com/mikaelpatel/Arduino-GPIO/blob/master/examples/Benchmark/Benchmark.ino

There is micros() which returns the number of microseconds the board has been active. But it rolls over much more frequently (a bit over an hour vs the month and a half for millis())
unsigned long preFunction = micros();
foo();
unsigned long timeElapsed = micros() - preFunction;

The rollover is not an issue as long as foo() executes in less than 71.5 minutes.

Beyond the answer of ratchet freak, I also suggest to (for test only), put it in a loop and divide it to get a better result, like:
unsigned long preFunction = micros();
for (int i = 0; i < 1000; i++)
{
  foo();
}
unsigned long timeElapsed = (micros() - preFunction) / 1000;

The number of repeats depend on the length of foo(), make sure it will not have a value beyond an unsigned long.

The most accurate method would be to toggle a pin high right before the function, and low after.
If you than connect an oscilloscope or logic analyzer to the pin, you can measure the exact time it took for the function to execute.

What kind of oscilloscope? What precision do you expect to obtain?

@LookAlterno: Any oscilloscope would do. Even a cheap pocket scope, like the DSO nano, is likely to be more accurate than micros().

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Detect current in car handbrake circuit

Using Arduino, how can I detect that the switch is on? I have access to the wire within the red rectangle only. That's because the switch is closely connected to the car body (ground). When the handbrake is up, the switch is pushed by a coil to touch car body and close the circuit. And when the handbrake is down, the switch go away from the car body and the circuit is open.

Can you insert a voltage monitor? Or other parts?

If you literally only have access to that wire, you cannot. You will need access either to the ground or 12v, or the bulb to see if it is lit.

Actually that's not quite true. You could do it by cutting the wire and putting a resistor in series, then measuring the voltage across the resistor.

this seems like a school assignment. ... did i guess correctly?

@CodeGorilla what will voltage monitor do?

@jsotola Nope, It's an idea I'm making in my car

@MegamindSaiko it will monitor the voltage.

If you are doing this in your car, as you say, then you can easily get a ground somewhere else (the whole body is ground) and just use a voltage divider (two resistors) to measure the voltage.

It's the handbrake switch button, the switch is directly connected to the ground, there's no wires or space to place anything. while the handbrake is up, a coil push the switch to touch car body, and while down the switch get away from the car body and open the circuit.

A friend of mine said that I can just check for the voltage (without shunts or any other tools). He said that if the switch is closed, the voltage would be zero as the ground, and if the switch is open, it will read 12 V. Is that true?? I will try it using a multimeter.

After examining the answers provided by "Jose can u c", "Alberto Perro" and "VE7JRO", and the comments by "Mark Smith", It was clear to me that there are a lot of methods to use, but I found out that the simplest way is to just measure the voltage at any point within the red rectangle. While the circuit is close, it will read 0V, and while the circuit is open, it will read about 12V.
And of course we will use voltage divider to reduce the voltage to  about 4V, and 4.7 zener diode to protect Arduino's pin.

If you truly only have access to the red rectangle content, and not the Ground or +12V supply, you could use an opto-isolator, assuming you can use enough of the wire in the red rectangle to be able to form a voltage divider to get at least 1-2 mA through the input side of the opto.

It gets easier if you have access to the Ground point, too...

Wrap the wire around a ferrite or some iron core and detect magnetic field.

This may not be the most practical answer, but here's an upvote for creative thinking!

If you can modify the cabling, you can add a shunt resistor in series and measure the voltage drop between the terminals. This way you can measure the current draw that would be 0 if the switch is open and something if the switch is closed.
Other way you can use an ACS712 Current Sensor.

Based on your comments:
"It's the handbrake switch button..." and "..if the switch is closed, the voltage would be zero as the ground, and if the switch is open, it will read 12 V.",
you could splice into the wire and use it as an input for the Arduino. You can NOT connect it directly to an Arduino because 5V is the maximum voltage permitted on a digital input (assuming your Arduino is running at 5V).
There are several ways to connect it to the Arduino safely, such as an opto-isolator, a level-shifter or using passive components.
This circuit using 2 resistors and a zener diode may work for you:

Be sure to connect the vehicle ground to the Arduino GND.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
What does drawmenu() mean
Can anybody tell me what drawmenu() means, I got an answer on here that has the term on and I don’t quite understand it, I’m very new to this.
Any help you can give will be greatly appreciated.
Liam

It calls the function drawmenu() that is included in some code somewhere.  Does your code have any interesting #include ... statements?

the code I am writing is to create a simple menu for my Arduino LCD push button shield, so I will be using #include <LiquidCrystal.h>

Possible duplicate of Creating a simple menu for Arduino LCD button shield

I gave you that particular answer
The function drawMenu() has no meaning. I was suggesting that you create a function with that name, whose action is to write text to the LCD with your selected menu item. The name of the function is not relevant. It does not exist until you create it.

thanks for your answer, i wasn't sure whether i should ask this question in the comments on the other page or start a new thread. I understand now, thank you.


text:
Put integer and double into char array
I want to print text and numbers mixed in a table with Serial.print(); from a char array. My problem is the conversion between the different data types. My idea is to print the data of the rows in a for loop with the variable i and the columns in a for loop with the variable j.
I have in the following example two variable, one is type integer and the second is a double. Now i want to add the values of the variables into the char-array, but I can't find a way to do this...
In my main program the variables need to have this data types and should be inserted later into the char array.
Does someone have a solution for this challenge?
Here is a small example code:
int a = random(0, 100);
double b = random(0, 100);

char* myStrings[][6] = {"This is string 1", "This is string 2", "This is string 3",
                        "This is string 4", "This is string 5", "This is string 6"
                       };

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

void loop() {

  //now put the integer and double variables into the char array in the second column

  //Print the values
  for (int i = 0; i < 2; i++)
  {

    for (int j = 0; j < 6; j++)
    {
      Serial.print(myStrings[i][j]);
      Serial.print("  ");
      delay(100);
    }
    Serial.println();
  }

}

Many thanks in advance.
Guss
EDIT:
The output should look like this:
Headline (in this example it is the text "This is string 1", "This is string 2"...)
and then the values of the variables in the next row. It should be like this:
This is String 1     This is String 2     This is String 3

Variable a           Variable b           Variable int

Variable double      Variable double      Variable int

Did I understand you correctly that you want to write an integer value into a char buffer? You can do that using snprintf(). Also, you example code crashes because you access memory out of bounds of the myStrings array. Can you give an example of how the output should look like?

Thanks for your fast answer. I have in edit in my question above. Maybe char array isn't the best way. I'm open for improvements.

Do you need the data tabulated like that, or would one item per line be ok? Tabulating it will be a bit more complicated. Still doable but harder.

It should be tabulated because the column names are different in its length.

First of all, you should decide for a datastructure for you table. There are many options with various advantages and disadvantages. I am choosing a statically allocated table here, with a fixed width for each entry in the table and a fixed number of columns. One may also use pointers to strings which are allocated on the heap or elsewhere, but I find this to be the simplest.
Anyways, the basic problem doesn't change: We want to write a integer value in some string buffer. I am using the C library function snprintf() here. This function is like printf(), just that it writes its output to a given buffer of a maximum size. Thus, we can use simple format strings here and some workarounds for non-working format strings (floating points..)
Here is the code.
#include <Arduino.h>

/* A table is a 2 dimensional array of char buffers.
   The core element is a char buffer of fixed size.
   The number of columns must be fixed at compile time.
   Rows can by dynamically added in the structure without having to
   declare the number of elements.
   You can declare the number of rows at compile time, but do not need to fill them.
   Thus you can dynamically add rows to the table.
 */

#define MAX_ENTRY_SIZE 20
#define NUM_COLUMNS 3
#define COLUMN_PRINT_WIDTH MAX_ENTRY_SIZE

char myTable[][NUM_COLUMNS][MAX_ENTRY_SIZE] = {
        {"Column 1", "Column 2" ,"Column 3"}, //Row 1
        {"Variable a", "Variable b", "Variable int"}, //Row 2
        {"Variable double", "Variable double" ,"Variable double"}, //Row 1
};

char* get_table_entry(int row, int column) {
    char* entry = myTable[row][column];
    return entry;
}

void write_int_to_table(int value, int row, int column) {
    //Get a pointer to where the entry is
    char* entry = get_table_entry(row, column);
    //write a new string inside it
    snprintf(entry, MAX_ENTRY_SIZE, "%d", value);
}

void write_double_to_table(double value, int row, int column) {
    //Same as above, different format string..
    char* entry = get_table_entry(row, column);
    //Formatting floats on an Arduino Uno is tricky. %f formatters don't work (cut out due to size.)
    //use String API instead
    String stringFloat(value);
    const char* cString = stringFloat.c_str();
    strncpy(entry, cString, MAX_ENTRY_SIZE);
}

void print_table() {
    //Get number of Rows
    int numRows = sizeof(myTable) / (MAX_ENTRY_SIZE * NUM_COLUMNS);
    for(int row = 0; row < numRows; row++) {
        //Print all columns of this row
        for(int column = 0; column < NUM_COLUMNS; column++) {
            char* entry = get_table_entry(row, column);
            Serial.print(entry);
            //fill with spaces to the right
            for(unsigned int i=0; i< COLUMN_PRINT_WIDTH - strlen(entry); i++) Serial.print(" ");
        }
        Serial.println();

        //Table header seperator
        if(row == 0)
            Serial.println("============================================");
    }
}

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

void loop() {
    int a = random(0, 100);
    double b = random(0, 100);

    Serial.print("Will write new values for a = ");
    Serial.print(a);
    Serial.print(" and b = ");
    Serial.println(b);

    //write these in the second row (first row after header), first and second column.
    write_int_to_table(a, 1, 0);
    write_double_to_table(b, 1, 1);

    //Print table again
    print_table();
    Serial.println();
    Serial.println();

    delay(5000);
}

Two rounds give the output:
Column 1            Column 2            Column 3
============================================
Variable a          Variable b          Variable int
Variable double     Variable double     Variable double

Will write new values for a = 7 and b = 49.00
Column 1            Column 2            Column 3
============================================
7                   49.00               Variable int
Variable double     Variable double     Variable double

Wow, very impressive. Thanks a lot for this code. One little question, how can I print the table head seperator to the length of the table head automatically?

You can calculate the number of needed characters by doing int num = NUM_COLUMNS * MAX_ENTRY_SIZE, then print the seperator character in a for loop from 0 to num.


text:
How well will the Arduino Uno survive in a vacuum?
Im doing some experiments with Pocketlab and Arduino, Vacuum will get to around -30inHg. I tried with my raspberry pi and it just kept dying everytime a vacuum was pulled. The only problem I can image is the arduino heating up.

http://www3.telus.net/schmaus2/vacf/vace1.html

This is a SE Electrical Engineer question.

Interesting question. You're right- heat is your enemy. Given the power dissipated by a Pi even when idle I'm not surprised it died. Most chips depend on convection to get rid of heat. A loaded Pi might require a (convective) heat sink and/or fan to keep it's core temperature down to an acceptable level, and that's at normal pressure and temperature. An Arduino -might- be able to work in a vacuum- it can lose some of it's heat through lead conduction- it'll only draw ~.25 watts normally vs 2.5 watts plus for a loaded Pi.
Ultimately it will depend on your application. If you have idle time when you can put the Arduino to sleep that will help keep it cool. If you have a conductive heat sink you can use then that would certainly help.

Also (assuming an Uno as it's tagged) the electrolytic capacitors on the board will most certainly pop. You'd want to replace those with tantalums at the very least.

Thanks, I've never had problems with capacitors in a vacuum before so I dont expect problems with that, I do expect the on board LED's to die though.


text:
Temperature control using a DHT11
I am trying to do a project on temperature control and found an example but cannot get the code to work. I have read forums and tried to fix the issue which is below the code.
Code:
#include<DHT.h>      // Including library for dht
#include<LiquidCrystal.h>
LiquidCrystal lcd(2, 3, 4, 5, 6, 7);
#define dht11dpin 12
DHT11;
#define pwm 9
#byte degree[8] =
{
  0b00011,
  0b00011,
  0b00000,
  0b00000,
  0b00000,
  0b00000,
  0b00000,
  0b00000
};

#void setup()
{
  lcd.begin(16, 2);
  lcd.createChar(1, degree);
  lcd.clear();
  lcd.print("   Fan Speed  ");
  lcd.setCursor(0, 1);
  lcd.print("  Controlling ");
  delay(2000);
  analogWrite(pwm, 255);
  lcd.clear();
  lcd.print("Circuit Digest ");
  delay(2000);
}

void loop()
  DHT11.read(DHT11pin);
  int temp = DHT11.temperature;
  lcd.setCursor(0, 0);
  lcd.print("Temperature:");
  lcd.print(temp);   // Printing temperature on LCD
  lcd.write(1);
  lcd.print("C");
  lcd.setCursor(0, 1);
  if (temp < 26 )
  {
    analogWrite(9, 0);
    lcd.print("Fan OFF            ");
    delay(100);
  }
  else if (temp == 26)
  {
    analogWrite(pwm, 51);
    lcd.print("Fan Speed: 20%   ");
    delay(100);
  }
  else if (temp == 27)
  {
    analogWrite(pwm, 102);
    lcd.print("Fan Speed: 40%   ");
    delay(100);
  }
  else if (temp == 28)
  {
    analogWrite(pwm, 153);
    lcd.print("Fan Speed: 60%   ");
    delay(100);
  }
  else if (temp == 29)
  {
    analogWrite(pwm, 204);
    lcd.print("Fan Speed: 80%    ");
    delay(100);
  }
  else if (temp > 29)
  {
    analogWrite(pwm, 255);
    lcd.print("Fan Speed: 100%   ");
    delay(100);
  }
  delay(3000);
}

Error:
In file included from C:\Users\neilb\Documents\Arduino\sketch_jan20b\sketch_jan20b.ino:2:0:
C:\Users\neilb\Documents\Arduino\libraries\DHT_sensor_library/DHT.h:32:15: error: expected unqualified-id before numeric constant
 #define DHT11 11
               ^
C:\Users\neilb\Documents\Arduino\sketch_jan20b\sketch_jan20b.ino:6:1: note: in expansion of macro 'DHT11'
 DHT11;
 ^
C:\Users\neilb\Documents\Arduino\libraries\DHT_sensor_library/DHT.h:32:15: error: expected initializer before numeric constant
 #define DHT11 11
               ^
C:\Users\neilb\Documents\Arduino\sketch_jan20b\sketch_jan20b.ino:35:1: note: in expansion of macro 'DHT11'
 DHT11.read(DHT11pin);
 ^
sketch_jan20b:36: error: request for member 'temperature' in '11', which is of non-class type 'int'
 int temp=DHT11.temperature;
                ^
sketch_jan20b:37: error: 'lcd' does not name a type
   lcd.setCursor(0,0);
   ^
sketch_jan20b:38: error: 'lcd' does not name a type
   lcd.print("Temperature:");
   ^
sketch_jan20b:39: error: 'lcd' does not name a type
   lcd.print(temp);   // Printing temperature on LCD
   ^
sketch_jan20b:40: error: 'lcd' does not name a type
   lcd.write(1);
   ^
sketch_jan20b:41: error: 'lcd' does not name a type
   lcd.print("C");
   ^
sketch_jan20b:42: error: 'lcd' does not name a type
   lcd.setCursor(0,1);
   ^
sketch_jan20b:43: error: expected unqualified-id before 'if'
   if(temp <26 )
   ^
sketch_jan20b:50: error: expected unqualified-id before 'else'
     else if(temp==26)
     ^
sketch_jan20b:57: error: expected unqualified-id before 'else'
      else if(temp==27)
      ^
sketch_jan20b:64: error: expected unqualified-id before 'else'
      else if(temp==28)
      ^
sketch_jan20b:71: error: expected unqualified-id before 'else'
     else if(temp==29)
     ^
sketch_jan20b:77: error: expected unqualified-id before 'else'
      else if(temp>29)
      ^
sketch_jan20b:83: error: expected constructor, destructor, or type conversion before '(' token
   delay(3000);
        ^
sketch_jan20b:84: error: expected declaration before '}' token
 }
 ^
exit status 1
request for member 'temperature' in '11', which is of non-class type

Are you mixing 2 libraries? Code seems like https://playground.arduino.cc/Main/DHT11Lib but you seem ot be using the Adafruit library https://github.com/adafruit/DHT-sensor-library/blob/master/examples/DHTtester/DHTtester.ino ? Can you tell us whhich library installed test with above example instead? Also why are there # in #byte degree[8] and #void setup()?

It's a bit hard to see, but
DHT11;

does not look like a correct statement, assuming DHT11 is a class (not a define like shown) it should be something like
DHT11 dht;

where dht is an instance and you can use that.
Than in
DHT11.read(DHT11pin);

you should replace it by
dht.read(DHT11pin);

so got past that bit but getting issue with the line lcd.createChar(1, degree);
saying degree was not declared in sope

degree should be a variable, which you haven't declared (unless it's global and you didn't post it).

Several variable declarations and the setup definition are prefixed by #.  Those will prevent the line from being processed correctly. degree is one of those with that error.

It seems the code has been changed since my comment.


text:
Rfid reader and SD card shield won't work together
I recently encountered a problem that's been bugging me for days. I want to make a project using a RFID reader and log data on an SD card with an Arduino Nano, but apparently no matter what I do, I can't seem to make them work together on SPI. They both work individually, and the SD shield works in parallel with the RFID reader, but the RFID doesn't work in parallel with the SD shield.
I'm absolutely sure that the wiring is correct, slave select on both modules are wired to different digital pins, and both are connected through bidirectional level shifters.
I noticed that the RFID reader works fine when I disconnect the MISO pin from the SD shield. I tried putting a diode between SD MISO and digital pin 12, I tried adding pullup resistors on both SS pins, I tried adding resistors on MISO lines, I tried pulling HIGH the SS i don't use, and low the one I want active. Nothing seemes to work and I'm out of ideas. The last thing I will try is conencting the modules on separate VCC, but I don't have faith that it will make any difference.
I hope someone has some advice for my problem.
Thanks in advance

Show wireup schematics and the code declaring the pin connections.

SD cards (or really their breakout boards) don't tend to obey the rules with regards to SPI. In particular the MISO pin isn't set to high impedance when the slave select is not selected.
You can fix this with a tri-state buffer that you feed the SD card's miso line to and controlled by the slave select. The output from the buffer goes to the arduino's MISO.

I used a tri state  buffer and it worked, thanks a bunch !

The only way I could get it to work was to buy a separate SD logger shield (which contains an SD card via SPI).
When I used the SRAM (SPI) together with the SD card (SPI) it never did work. At least not on an Arduino (Uno or Mega).


text:
How fast an Arduino mouse would be?
I'm thinking about making a custom Arduino-based mouse and I expect not to be the first one to have the idea. Does anybody know what speed I can expect to achieve? Suppose I use a mechanical mouse as a base, meaning I'll have to monitor 3 buttons and 3 axes (X, Y and wheel), debounce the signals coming from the buttons and transmit all that data via USB. How many times per second will I be able to do this, theoretically? Are there any projects which did something similar, and if so, what speed were they able to achieve?
To make a good mouse, I suppose I should at least beat my display's refresh rate which is 60 Hz, otherwise pointer movement won't be smooth. My current (commercially produced) mouse runs at 100 Hz.

I suppose that 1000 times per second could be possible, but I don't know if that is somewhere slowed down, for example in the driver on the computer. The pro micro board uses a usb interface which is very fast. Please add to your question why you ask this. You know someone who presses a button 1000 times per second? or is the button only shortly pressed and you don't want to miss it?

Thanks for updating your question. 100 Hz is no problem, and there is still time to debounce the buttons. What kind of mechanical mouse? With rotary encoders? With two interrupts per encoder and 3 axis you need 6 interrupts. The pro micro has 4 normal interrupts and 6 pcint interrupts. Pinmapping: http://www.pighixxx.com/test/portfolio-items/pro-micro/


text:
Having trouble passing data through RF24
I have three RF24, all of them are connected to one arduino-uno each. The first one has sensors that sends data to the second one then the second one passes it to the third one. The first pass from RF24 #1 to RF24 #2 is successful but from the RF24 #2 to RF24 #3 there seems to be a problem.
Code for the RF24 #1 (I just copied the setup and loop the other functions are for the sensors, I think it's unnecessary):
//Libraries for temperature
#include <OneWire.h>
#include <DallasTemperature.h>
#define motor1 8
// Data wire is plugged into port 2 on the Arduino
#define ONE_WIRE_BUS 2
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);

//for pH meter
#define SensorPin A0            //pH meter Analog output to Arduino Analog Input 0
#define Offset 0.00            //deviation compensate
#define LED 13
#define samplingInterval 20
#define printInterval 800
#define ArrayLenth  40    //times of collection
int pHArray[ArrayLenth];   //Store the average value of the sensor feedback
int pHArrayIndex = 0;

//for NRF24L01
RF24 radio(7, 8); // CE, CSN
const uint64_t waddress = 0xB00B1E50D2LL;
struct package {
  float temperature, ph, Do, inch, cm1;
};
typedef struct package Package;
Package data;
int LID = 4, LOD = 6;

//for ultrasonic
const int trigPin = 3;
const int echoPin = 4;
long duration, inches, cm, meter;

void setup(void)
{
  // start serial port
  radio.begin();
  radio.openWritingPipe(waddress);
  radio.setPALevel(RF24_PA_MIN);
  radio.stopListening();

  pinMode(LED, OUTPUT);
  // Start up the library
  sensors.begin();
}

/*
   Main function, get and show the temperature
*/

void loop(void)
{
  static unsigned long samplingTime = millis();
  static unsigned long printTime = millis();
  static float pHValue, voltage;
  if (millis() - samplingTime > samplingInterval)
  {
    pHArray[pHArrayIndex++] = analogRead(SensorPin);
    if (pHArrayIndex == ArrayLenth)pHArrayIndex = 0;
    voltage = avergearray(pHArray, ArrayLenth) * 5.0 / 1024;
    pHValue = 3.5 * voltage + Offset;
    samplingTime = millis();
  }
  if (millis() - printTime > printInterval)  //Every 800 milliseconds, print a numerical, convert the state of the LED indicator
  {
    digitalWrite(LED, digitalRead(LED) ^ 1);
    // call sensors.requestTemperatures() to issue a global temperature
    // request to all devices on the bus

    sensors.requestTemperatures(); // Send the command to get temperatures

    // After we got the temperatures, we can print them here.
    // We use the function ByIndex, and as an example get the temperature from the first sensor only.

    //Serial.print(pHValue,2);
    //Serial.print(",");
    //Serial.print(sensors.getTempCByIndex(0));

    radio.write(&data, sizeof(data));

    data.ph = (pHValue);
    data.temperature = (sensors.getTempCByIndex(0));
    Serial.print(data.ph);
    Serial.print(data.temperature);
    Serial.print(data.Do);
  }
}

RF24 #2
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
RF24 radio(7, 8); // CE, CSN
const uint64_t raddress = 0xB00B1E50D2LL;
const uint64_t waddress = 0xB00B1E50B1LL;
struct package {
  float temperature, ph, Do, inch, cm1;
};
typedef struct package Package;
Package data;

void setup() {
  Serial.begin(9600);
  radio.begin();
  radio.openWritingPipe(waddress);
  radio.openReadingPipe(1, raddress);
  radio.setPALevel(RF24_PA_MIN);
}

void loop() {
  radio.startListening();

  while (radio.available()) {
    radio.read(&data, sizeof(data));
    Serial.print(data.ph);
    Serial.print(",");
    Serial.print(data.temperature);
    Serial.print(",");
    Serial.print(data.Do);
    Serial.print(",");
    Serial.print(data.inch);
    Serial.print(",");
    Serial.println(data.cm1);
  }
  if (radio.write(&data, sizeof(data))) {
    Serial.println(" delivery failed");
  }
  radio.stopListening();
  delay(200);
}

RF24 #3
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
int lid = 2 , lod = 4;
RF24 radio(7, 8); // CE, CSN
const uint64_t raddress = 0xB00B1E50B1LL;
struct package {
  float temperature, ph, Do, inch, cm1;
};
typedef struct package Package;
Package data;

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

  radio.begin();
  radio.openReadingPipe(2, raddress);
  radio.setPALevel(RF24_PA_MIN);
  radio.startListening();
  pinMode(lid, OUTPUT);
  pinMode(lod, OUTPUT);
}

void loop() {
  unsigned long startTimer = millis();
  bool timeout = false;

  while (!radio.available() && !timeout) {
    if (millis() - startTimer > 500 )
    {
      timeout = true;
    }
    // radio.read(&temperature, sizeof(temperature));
    //radio.read(&Do, sizeof(Do));
  }
  if (timeout) {
    Serial.println("Failed to receive data");
  }
  else {
    radio.read(&data, sizeof(data));

    Serial.print(data.ph);
    Serial.print(",");
    Serial.print(data.temperature);
    Serial.print(",");
    Serial.print(data.Do);
    Serial.print(",");
    Serial.print(data.inch);
    Serial.print(",");
    Serial.println(data.cm1);
  }
}

The serial monitor for RF24 #2 displays:
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
6.92,28.25,7.20,15.00,38.00
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
 delivery failed
6.91,28.25,7.20,15.00,38.00

RF24 #3 Serial Monitor:
0.00,0.00,0.00,0.00,0.00
0.00,0.00,0.00,0.00,0.00
0.00,0.00,0.00,0.00,0.00
0.00,0.00,0.00,0.00,0.00
0.00,0.00,0.00,0.00,0.00
0.00,0.00,0.00,0.00,0.00
0.00,0.00,0.00,0.00,0.00
0.00,0.00,0.00,0.00,0.00
0.00,0.00,0.00,0.00,0.00

Sometimes RF24 #3 receives the data and prints it continuously. I don't know why. Most of the time it displays the above.
Edit: Revision
Update: It turns out that RF24 #3 continuous to print even if RF24 #2 is unplugged/not powered.

You should always call stopListening() right before you write(). Also write() returns true when messages are delivered so your condition is wrong. Try changing the loop() in the second node to:
void loop() {
  while (radio.available()) {
    radio.read(&data, sizeof(data));
    Serial.print(data.ph);
    Serial.print(",");
    Serial.print(data.temperature);
    Serial.print(",");
    Serial.print(data.Do);
    Serial.print(",");
    Serial.print(data.inch);
    Serial.print(",");
    Serial.println(data.cm1);

    radio.stopListening();
    if (!radio.write(&data, sizeof(data))) {
      Serial.println("Delivery failed");
    }
    radio.startListening();
  }
}

If a packet is available, it's read, printed and forwarded.
The third node's loop() should also be adjusted to something like:
bool new_data = false;

void loop() {
  if (radio.available()) {
    radio.read(&data, sizeof(data));

    Serial.print(data.ph);
    Serial.print(",");
    Serial.print(data.temperature);
    Serial.print(",");
    Serial.print(data.Do);
    Serial.print(",");
    Serial.print(data.inch);
    Serial.print(",");
    Serial.println(data.cm1);
    new_data = true;
  }
  if (new_data) {
    // do stuff
    new_data = false;
  }
}

Data is sent in 32-byte payloads and your entire package is 20 bytes (without padding), assuming a float = 4 bytes. So a complete packet has either arrived or it hasn't; no point in waiting in one place. new_data lets you know when there's new stuff obviously and you clear the flag when you're done processing the data. This way, you can do other stuff while you wait for a packet to show.


text:
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()
{

}

No Serial.begin(baudrate);? Also Navigator nav(); is kind of function prototype. You can use Navigator nav;

What might be easy in such cases, is first to make it in e.g. VisualStudio (without using Arduino), and later when everything works on a PC (where you can debug everything easily) run it on an Arduino. Only calls like Serial, you have to comment out or stub.

Debugging questions need to include the actual output produced.  Is it repeatable or random?  also, you should reduce your code to a minimum example which demonstrates the problem, and correct your title for the fact that there is no such thing as an ATmega2056.  Are you targeting the bare chip, or an Arduino Mega2560/clone?

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.


text:
Buffer reverse to string
A few hours since I started messing with my first Arduino and I was trying to understand a small program and need some help. The program sends out the MAC address to the serial port. As it's little endian, the "printBufferReverse" reverses the buffer as shown below. But instead of sending this data to the serial port, how do I store the same data into a string variable? Thanks so much
#include <bluefruit.h>
void scan_callback(ble_gap_evt_adv_report_t* report)
{
  uint8_t len = 0;
  uint8_t buffer[32];
  memset(buffer, 0, sizeof(buffer));

  // MAC is in little endian --> print reverse
  // NOTE: I want to store this into a string variable
  // NOTE: the reversing
  Serial.printBufferReverse(report->peer_addr.addr, 6, ':');
  Serial.print("\n");

  /* TX Power Level */
  if (Bluefruit.Scanner.parseReportByType(report,
    BLE_GAP_AD_TYPE_TX_POWER_LEVEL, buffer, sizeof(buffer)))
    {
      Serial.printf("%14s %i\n", "TX PWR LEVEL", buffer[0]);
      memset(buffer, 0, sizeof(buffer));
    }
}

And the below line how do I store the data to a string instead of sending to serial port? It's adding a hypen to make the end result look like this:12-09-69-57-45-45-43-41-52-45-20
Serial.printBuffer(report->data, report->dlen, '-');

I don't want to send this to serial port but to store in a string variable.
This is the board that I am using: https://www.adafruit.com/product/3406
Complete code
/*********************************************************************
 This is an example for our nRF52 based Bluefruit LE modules

 Pick one up today in the adafruit shop!

 Adafruit invests time and resources providing this open source code,
 please support Adafruit and open-source hardware by purchasing
 products from Adafruit!

 MIT license, check LICENSE for more information
 All text above, and the splash screen below must be included in
 any redistribution
*********************************************************************/

#include <bluefruit.h>

/* For a list of EIR data types see:
 *    https://www.bluetooth.com/specifications/assigned-numbers/generic-access-profile
 *    Matching enum: cores/nRF5/SDK/components/softdevice/s132/headers/ble_gap.h */

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

  Serial.println("Scanning for beacons");
  Serial.println("------------------------------------\n");

  // Initialize Bluefruit with maximum connections as Peripheral = 0, Central = 1
  // SRAM usage required by SoftDevice will increase dramatically with number of connections
  Bluefruit.begin(0, 1);

  // Set max power. Accepted values are: -40, -30, -20, -16, -12, -8, -4, 0, 4
  Bluefruit.setTxPower(4);

  /* Set the device name */
  Bluefruit.setName("Bluefruit52");

  /* Set the LED interval for blinky pattern on BLUE LED */
  Bluefruit.setConnLedInterval(250);

  /* Start Central Scanning
   * - Enable auto scan if disconnected
   * - Filter out packet with a min rssi
   * - Interval = 100 ms, window = 50 ms
   * - Use active scan (used to retrieve the optional scan response adv packet)
   * - Start(0) = will scan forever since no timeout is given
   */
  Bluefruit.Scanner.setRxCallback(scan_callback);
  Bluefruit.Scanner.restartOnDisconnect(true);
  Bluefruit.Scanner.filterRssi(-80);
  //Bluefruit.Scanner.filterUuid(BLEUART_UUID_SERVICE); // only invoke callback if detect bleuart service
  Bluefruit.Scanner.setInterval(160, 80);       // in units of 0.625 ms
  Bluefruit.Scanner.useActiveScan(true);        // Request scan response data
  Bluefruit.Scanner.start(0);                   // 0 = Don't stop scanning after n seconds

  Serial.println("Started ...");
}

void scan_callback(ble_gap_evt_adv_report_t* report)
{
  uint8_t len = 0;
  uint8_t buffer[32];
  memset(buffer, 0, sizeof(buffer));
  boolean hasPayload;
  String bleDvcID;
  String advPayload;

  hasPayload = false;
  bleDvcID = "";
  advPayload = "";

  /* Display the timestamp and device address */
  /*
  if (report->scan_rsp)
  {
    Serial.printf("[SR%10d] Packet received from ", millis());
  }
  else
  {
    Serial.printf("[ADV%9d] Packet received from ", millis());
  }
  */
  // MAC is in little endian --> print reverse
  // bleDvcID = printBufferReverse(report->peer_addr.addr, 6, ':');
  // char buffer[18] = "";
  /*
    snprintf(buffer, "%02X-%02X-%02X-%02X-%02X-%02X", 18,
        report->peer_addr.addr[5],
        report->peer_addr.addr[4],
        report->peer_addr.addr[3],
        report->peer_addr.addr[2],
        report->peer_addr.addr[1],
        report->peer_addr.addr[0]
    );
   */
  Serial.printBufferReverse(report->peer_addr.addr, 6, ':');
  Serial.print("\n");

  /* Raw buffer contents */
  Serial.printf("%14s %d bytes\n", "PAYLOAD", report->dlen);
  if (report->dlen)
  {
    hasPayload = true;
    Serial.printf("%15s", " ");
    Serial.printBuffer(report->data, report->dlen, '-');
    Serial.println();
  }

  /* RSSI value */
  Serial.printf("%14s %d dBm\n", "RSSI", report->rssi);

  /* Complete Local Name */
  if(Bluefruit.Scanner.parseReportByType(report, BLE_GAP_AD_TYPE_COMPLETE_LOCAL_NAME, buffer, sizeof(buffer)))
  {
    Serial.printf("%14s %s\n", "COMPLETE NAME", buffer);
    if (strcmp((const char*)buffer, "Temperature Fren")==0)
    {
        Serial.println("Found beacon!");
    }
    memset(buffer, 0, sizeof(buffer));
  }

  /* TX Power Level */
  if (Bluefruit.Scanner.parseReportByType(report, BLE_GAP_AD_TYPE_TX_POWER_LEVEL, buffer, sizeof(buffer)))
  {
    Serial.printf("%14s %i\n", "TX PWR LEVEL", buffer[0]);
    memset(buffer, 0, sizeof(buffer));
  }

  /* Check for UUID16 Complete List */
  len = Bluefruit.Scanner.parseReportByType(report, BLE_GAP_AD_TYPE_16BIT_SERVICE_UUID_COMPLETE, buffer, sizeof(buffer));
  if ( len )
  {
    printUuid16List(buffer, len);
  }

  /* Check for UUID16 More Available List */
  len = Bluefruit.Scanner.parseReportByType(report, BLE_GAP_AD_TYPE_16BIT_SERVICE_UUID_MORE_AVAILABLE, buffer, sizeof(buffer));
  if ( len )
  {
    printUuid16List(buffer, len);
  }

  /* Check for UUID128 Complete List */
  len = Bluefruit.Scanner.parseReportByType(report, BLE_GAP_AD_TYPE_128BIT_SERVICE_UUID_COMPLETE, buffer, sizeof(buffer));
  if ( len )
  {
    printUuid128List(buffer, len);
  }

  /* Check for UUID128 More Available List */
  len = Bluefruit.Scanner.parseReportByType(report, BLE_GAP_AD_TYPE_128BIT_SERVICE_UUID_MORE_AVAILABLE, buffer, sizeof(buffer));
  if ( len )
  {
    printUuid128List(buffer, len);
  }

  /* Check for BLE UART UUID */
  /*
  if ( Bluefruit.Scanner.checkReportForUuid(report, BLEUART_UUID_SERVICE) )
  {
    Serial.printf("%14s %s\n", "BLE UART", "UUID Found!");
  }
  */
  /* Check for DIS UUID */
  /*
  if ( Bluefruit.Scanner.checkReportForUuid(report, UUID16_SVC_DEVICE_INFORMATION) )
  {
    Serial.printf("%14s %s\n", "DIS", "UUID Found!");
  }
  */
  /* Check for Manufacturer Specific Data */
  /*
  len = Bluefruit.Scanner.parseReportByType(report, BLE_GAP_AD_TYPE_MANUFACTURER_SPECIFIC_DATA, buffer, sizeof(buffer));
  if (len)
  {
    Serial.printf("%14s ", "MAN SPEC DATA");
    Serial.printBuffer(buffer, len, '-');
    Serial.println();
    memset(buffer, 0, sizeof(buffer));
  }
  */
  Serial.println();
}

void printUuid16List(uint8_t* buffer, uint8_t len)
{
  /* Serial.printf("%14s %s", "16-Bit UUID"); */
  for(int i=0; i<len; i+=2)
  {
    uint16_t uuid16;
    memcpy(&uuid16, buffer+i, 2);
    /* Serial.printf("%04X ", uuid16); */
  }
  /* Serial.println(); */
}

void printUuid128List(uint8_t* buffer, uint8_t len)
{
  (void) len;
  /* Serial.printf("%14s %s", "128-Bit UUID"); */

  // Print reversed order
  for(int i=0; i<16; i++)
  {
    const char* fm = (i==4 || i==6 || i==8 || i==10) ? "-%02X" : "%02X";
    /* Serial.printf(fm, buffer[15-i]); */
  }

  /* Serial.println(); */
}

void loop()
{
  // Toggle both LEDs every 1 second
  digitalToggle(LED_RED);

  delay(1000);
}

Please edit your question to state which Arduino board you're compiling for. I believe Serial.printBufferReverse() is only part of the Adafruit nRF52 core, and even that only added recently so many people here may not be familiar with it.

Sorry I was supposed to mention that I am using Arduino IDE to program Adafruit nRF52 board. But the question itself isn't tied strictly to a particular board.

You can do it with snprintf_P:
char mac[18];

snprintf_P(mac, 18, (PGM_P)F("%02X-%02X-%02X-%02X-%02X-%02X"),
    report->peer_addr.addr[5],
    report->peer_addr.addr[4],
    report->peer_addr.addr[3],
    report->peer_addr.addr[2],
    report->peer_addr.addr[1],
    report->peer_addr.addr[0]
);

That is, assuming that report->peer_addr.addr is an array of 6 bytes.
If your strange board doesn't support the _P variants of string manipulation functions then you can drop that part along with the (PGM_P)F(...) bit:
char mac[18];

snprintf(mac, 18, "%02X-%02X-%02X-%02X-%02X-%02X",
    report->peer_addr.addr[5],
    report->peer_addr.addr[4],
    report->peer_addr.addr[3],
    report->peer_addr.addr[2],
    report->peer_addr.addr[1],
    report->peer_addr.addr[0]
);

Doing so on an Ardunio, though, would waste RAM.

Thanks. The first one with _P does not exist. And the 2nd one snprintf throws the following error; invalid conversion from 'uint8_t* {aka unsigned char*}' to 'char*' [-fpermissive]. Btw this is the board: https://www.adafruit.com/product/3406

@M.M, please add the reference about the board to your question

@jsotola sure, done.

@Majenko, the 2nd function seems to help but I get this error; conflicting declaration 'char buffer [18]'

So choose another name that doesn't conflict with whatever is in the rest of your sketch.

Choose another name? Can I know for which one to choose another name? The only other things that I have in the sketch are                                       #include <bluefruit.h>
void scan_callback(ble_gap_evt_adv_report_t* report)
{
uint8_t len = 0;
uint8_t buffer[32];
memset(buffer, 0, sizeof(buffer));

So your buffer variable is doing nothing then? So delete it. But first engage brain.

buffer is used elsewhere. I have edited my question to add that.

So pick a new name for your Mac variable. Maybe mac would be a good choice.

Even if I put the "snprintf" code that you provided in a new sketch, I get an error; invalid conversion from 'const char*' to 'size_t {aka unsigned int}' [-fpermissive] ... apologies but it's only been a few hours using Arduino IDE and C++. Yet to get a hang of things.

Hang on, seems I got the parameters in the wrong order. Check the new version of the code.

@Majenko, cool! Yup, that was it. Thanks a zillion. One tiny part left; how do I get this into a string? Serial.printBuffer(report->data, report->dlen, '-'); cos this is dynamic buffer

You will have to do it peacemeal and strcat each chunk.

Okay. Thank you so much. I'll figure the remaining part out.

I have a blog post that may help you out: https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/

wow, that is cool! Appreciate your help so much. Cheers


text:
Reading Arduino Serial Input
I am reading an input from my Ohaus weighing scale using it's RS232 output using this code:
#define HWSERIAL Serial1

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

void loop() {
  int incomingByte;

  if (Serial.available() > 0) {
    incomingByte = Serial.read();
    Serial.print("USB received: ");
    Serial.println(incomingByte, DEC);
    //HWSERIAL.print("USB received:");
    //HWSERIAL.println(incomingByte, DEC);
  }
  if (HWSERIAL.available() > 0) {
    incomingByte = HWSERIAL.read();
    Serial.print("UART received: ");
    Serial.println(incomingByte);
    //HWSERIAL.print("UART received:");
    //HWSERIAL.println(incomingByte);
  }
}

When pressing the print button on the scale, I was expecting data to come over in single burst with just the readings, but what I am getting is the expected data, but the scale keeps sending data afterwards (ES over and over). I need to parse out just what's needed. The below is the output from the console on my computer.
UART received:
UART received:
UART received:
UART received:
UART received: 0
UART received: .
UART received: 0
UART received: 0
UART received:
UART received:
UART received:
UART received:
UART received:
UART received:
UART received: ?
UART received: (This is a CR)

UART received: (This is a LF)

UART received:
UART received:
UART received:
UART received:
UART received: 0
UART received: .
UART received: 4
UART received: 0
UART received:
UART received:
UART received:
UART received:
UART received:
UART received:
UART received: ?
UART received: G
UART received:
UART received:
UART received: (CR)

UART received: (LF)

UART received: E
UART received: S
UART received: (CR)

UART received: (LF)
... (The ES loops over and over until the print button is pressed again)

0.00 is the current scale reading and 0.40 is the tare weight. That's all I need and I can't figure out how to parse it. The blocks aren't the same length so how do I pull out the needed information and ignore the repetitive 'ES'? I'm not 100% sure if I'm even going about this the right way?
Output as DEC
UART received: 32
UART received: 32
UART received: 32
UART received: 32
UART received: 48
UART received: 46
UART received: 48
UART received: 48
UART received: 32
UART received: 32
UART received: 32
UART received: 32
UART received: 32
UART received: 32
UART received: 63
UART received: 13
UART received: 10
UART received: 32
UART received: 32
UART received: 32
UART received: 32
UART received: 48
UART received: 46
UART received: 52
UART received: 48
UART received: 32
UART received: 32
UART received: 32
UART received: 32
UART received: 32
UART received: 32
UART received: 63
UART received: 71
UART received: 32
UART received: 32
UART received: 13
UART received: 10
UART received: 69
UART received: 83
UART received: 13
UART received: 10
UART received: 69
UART received: 83
...

From the manual:
http://dmx.ohaus.com/WorkArea/showcontent.aspx?id=4294974226 > The balance will return “ES” for invalid commands. Check to make sure you're using the correct serial parameters that the RX line is wired correctly.

Can you give a full working sketch and a output that is actually from that sketch. Make incomingByte an int, and remove the cast to char when you print it. Print it as DEC or HEX, so you can see the numbers of the characters or spaces or linefeeds or other fancy bytes.

Is that a real RS-232 signal? What do you use to convert it to a ttl-level signal? If you use a module, tell us which module. Add to you question the model of the weighting scale. The document mentioned by @jdwolf show different formats for different models. The 'g' is the unit and the '?' is unstable. The rest should fit into one of the formats. I suppose the two character 'term' is the cr lf.

Well, I tried to use a Max 3232, but for some reason, the scale wasn't pushing enough voltage to trigger it to send the ttl, so what I did was connect it directly to pin 0 on the leonardo to get this readout and I actually got the above UART readings. The problem was that the 232 was sending some erroneous signals and causing issues. I don't understand why this worked, because RS232 is inverted from ttl, so my only assumption is that ohaus already converts their signal to ttl?

Noise on your TX line? Sounds like maybe your sending random data the device doesn’t understand.

I'm trying to do pretty much the same thing with an OHAUS Ranger 3000 scale. Have you figured out whether the signal coming from the OHAUS is at 5V TTL or 13V RS232? Thanks

From the manual:
http://dmx.ohaus.com/WorkArea/showcontent.aspx?id=4294974226

The balance will return “ES” for invalid commands.

Check to make sure you're using the correct serial parameters that the RX line is wired correctly.

Thanks, that definitely helped. I just removed the TX line from the Arduino, as I'm not sending data to the scale.


text:
Light Powered Motor Troubles
I'm working on a small car (<1 kg) which will drive when there is light and stop when there isn't. Below is a plan with code drawn up (the only numbers I know for sure are the current gains for the TIP31C transistor and the rated load current of the 6 V motor I'm using). I'm going to map the analog voltages to a digital signal output.
I read that the maximum digital output was 40 mA and also that analogWrite gives a pulse width modulation (PWM) which can be set to 100% (255) [the code: outputval/1], 50% (127) [the code: outputval/2]. I'm concerned with the lack of control I have here over the current. Will Arduino by default draw 7.75 mA maximum if the input signal is high [giving the output signal also as high]? If not, can I control the current in this manner reliably? Also are there anything I should worry about if I added another 6 V motor in parallel? Coding and electrical suggestions greatly welcomed.
TIP31 transistor: http://www.hobbytronics.co.uk/datasheets/TIP31.pdf
6 V dc motor: http://www.kysanelectronics.com/graphics/RF-370CA-22170.pdf
maximum digital output: https://www.arduino.cc/en/Tutorial/DigitalPins
PWM: https://www.arduino.cc/en/Tutorial/PWM

The code:
const int transistorbase = 9;
void setup() {
  //set the base as digital output:
  pinMode(transistorbase, OUTPUT);
}
void loop() {
  //read voltage at divider:
  int inputval=analogRead(A0);
  //map voltage to digital
  int outputval=map(inputval,0,1023,0,255);
  //control transistor:
  analogWrite(transistorbase,outputval);
}

tl;dr
Codewise, how do I control the digital output current to my needs? Am I seeing ghosts?

You should seriously consider using an FET for motor control rather than a bipolar or darlington transistor.  Most Arduion hobbyists use IC-based drivers, but the same concern applies there as it does to discretes - seek FET, avoid bipolar.

I just read up on them. Will that fix my worries about current because it has a stronger response to voltage (seeing as a strong output signal will nearly be 5V for a fast PWM frequency) i.e. it is a device controlled by electric field and not a current requirement? Would this be a suitable FET, I don't think I'll fry it at VGS of 20 V, and assuming the PWM wave gives an average above 2 V above the VGS(th), it'll close when the input signal is weak, right?

https://www.infineon.com/dgdl/irfz44npbf.pdf?fileId=5546d462533600a40153563b3a9f220d

No, the threshold voltage is too high, it will be only barely on when driven by an Arduino.  Most suitable parts are surface mount only but https://cdn-shop.adafruit.com/datasheets/irlb8721pbf.pdf might work to a degree

So the digital output is not nearly 5V? That's what I got from the PWM reading.

An FET's threshold voltage is where it just begins to turn on.  You want something much higher for good performance.  Try to find one with a threshold below 2v.

I would take a simple n-channel MOSFET like this one. At 5V on the gate it can drive up to 8A (so you have plenty of space to connect other motors as long as your power source can handle this) and because it is a MOSFET you don't have to draw much current from the Arduino (only enough to load the gate of the MOSFET). You can also hold the current under the critical value for your motor with a simple resistor (fit for the resulting power dissipation) in series.
Yes, the output of the PWM is 5V - the operation voltage of the Arduino. The whole point in PWM is to use only the digital values (here 0V and 5V) and varying so fast, that slow systems as the motor cannot follow this motion, but summing over the impulses. So the motor gets only very fast kicks. And for a normal motor you don't need fast PWM. This only increases the frequency response from the MOSFET.
The code seems for to me.

That is not a very good MOSFET to use with this, as its threshold voltage is high enough that an Arduino will only barely turn it on.  You want one with a lower threshold voltage so that a ~5v output can turn it more completely on.


text:
Why the program keeps applying what is in loop in first case and stops in the second one?
In the first program after removing hand from the button it keeps on, means it keeps applying what is in the loop:
int led = 13;
int button = 12;
void setup() {
  pinMode(led, OUTPUT);
  pinMode(button, INPUT);
             }
void loop() {
  if (digitalRead(button) == HIGH)
  {
    digitalWrite(led, HIGH);
  }
             }

while in the second one it needs to press the button every time in order to apply what is in the loop,means to flash in this case,
int led = 13;
int button = 12;
void setup() {
  pinMode(led, OUTPUT);
  pinMode(button, INPUT);
            }
void loop() {
  if (digitalRead(button) == HIGH)
  {
    digitalWrite(led, HIGH);
    delay(1000);
    digitalWrite(led, LOW);
    delay(1000);
  }
           }

Why different behavior although the same structure?
The problem is illustrated in this video :
https://www.youtube.com/watch?v=u5WGvKwJYFY&t=2s

Looks confusing to me -- setup() should only run once per power-on cycle, and so since value is only set in setup() and not ever changed in loop() the behavior should never change after the initial powerup.  Is your circuitry somehow resetting the arduino after each iteration?

Both of your sketches are missing a "closing bracket", so they won't compile. They do not match the sketches in the video you've provided. Could you tell us what it is you are trying to accomplish? What should the LED do when you press the button? Flash the LED? What happens if you press the button again? Does it turn the flashing LED off?

no the circuit works fine, i am not trying to accomplish something, it just happened  and i want to know why different in applying the program, i want to understand how  those programs are executed, i thought after pressing the button it should react the same way ,means either  both prorams should apply only when press the button then keep applying or both should stop applying after i press the button, because the both have the same programming structure ,

in the fist code if i press the button again it does nothing the led is already on and keeps on, in the second code sure if i press the button again it flashes again

The code you posted does not compile, but it looks like if it did, it will completely ignore changes to button/value in loop() and not produce the effect you show in the video.

@sumerfattoum, you do not understand ... the code that you posted is not the same as the code in the video

the code posted is the same as in video if you noticce, it wont apply just cus i didnt copy the end brackts

u dont understand the idea, in the fist one posted it just instead of just reading it, i just used the name value , i reposted the code exactly as in the video, how ever could you answer why it acts like that in the video ???

because digitalWrite(led, LOW) turns the led off. but if you don't see it, than stop trying to write programs

ok, you corrected the code. so, now it is the same as in the video .... the two programs do exactly what you programmed them to do .... the loop() function repeats over and over until you press the reset button, or until you turn off the power. ... go through the code step by step. add comments that explain what each command does. you will soon understand why the code works the way it does.

They are two different codes, i tried to understand step by step but i couldn't that's why I ask , to my knowledge they should react the same way when pressing the button because they are the same structure and the only difference is what the led should do..but they act differently when pressing the button which clearly i don't understand

You read value only once ... what do you expected?
In the first sketch, you put the LED ON and never turn it OFF, no matter what.
In the second sketch, you put the LED ON and one second later you turned it OFF. As the value doesn't change, it keeps repeating.
You mistake: you read the button in setup. You have to read in each loop iteration.
void loop() {
  value = digitalRead(button);
  if (value == HIGH)
  {
    digitalWrite(led, HIGH);
    delay(1000);
    digitalWrite(led, LOW);
    delay(1000);
  }

did you apply the codes you wrote or think ? i did that firstly , and now i reposted and reedited it so it will read the button in the loop , and still act the same as you see above

This iteration of your code is better.  Now, the difference in behavior is that nothing in the first code ever executes digitalWrite(led, LOW);, while each iteration though the second code does.  Therefore the LED remains on forever in code 1, and depends on the button press in code two.
If the behavior you desire is that the code remembers if the button has ever been pressed, latch that event in some state variable, and then in loop(), act on the value of the state variable:
int led = 13;
int button = 12;
int everHit = 0;
void setup() {
  pinMode(led, OUTPUT);
  pinMode(button, INPUT);
}

void loop() {
  if (digitalRead(button) == HIGH) everHit = 1;
  if (everHit) {
    digitalWrite(led, HIGH);
    delay(1000);
    digitalWrite(led, LOW);
    delay(1000);
  }
}


text:
EDB. Is it possible to create multiple tables with db.create()?
Good day! I seem to be having trouble creating multiple tables with EDB. I am using Arduino UNO and SD Card module to save my db.
Here is my Serial.

Here is my table declaration.
struct LogEvent {
  int id;
  String fname;
  float temperature;
}
logEvent;

struct SecondEvent {
  int id;
  String lastname;
}
secondEvent;

Here is my db.create() code.
db.create(0, TABLE_SIZE, (unsigned int)sizeof(logEvent));
db.create(0, TABLE_SIZE, (unsigned int)sizeof(secondEvent));

Now, when I try to retrieve, it is a whack. Here is my save and retrieve code.
void createRecords(int num_recs, float correctTemperature)
{
    Serial.print("Creating Records... ");
    for (int recno = 1; recno <= num_recs; recno++)
    {
      correctId++;
      logEvent.id = correctId;
      logEvent.fname = "Brix Nicholson";
      logEvent.temperature = correctTemperature;
      secondEvent.id = correctId;
      EDB_Status result = db.appendRec(EDB_REC logEvent);
      if (result != EDB_OK) printError(result);
    }
  Serial.println("DONE");
}

void createRecordSecondEvent()
 {
   correctId++;
   secondEvent.id = correctId;
   secondEvent.lastname = "Secretaria";
   EDB_Status result = db.appendRec(EDB_REC secondEvent);
   if (result != EDB_OK) printError(result);
 }

void selectLastRecord()
{
  int lastRecNum = db.count();
  EDB_Status result = db.readRec(lastRecNum, EDB_REC logEvent);
  if(result == EDB_OK)
   {
     Serial.print(" ID: ");
     Serial.print(logEvent.id);
     Serial.print(" Name: ");
     Serial.print(logEvent.fname);
     Serial.print(" Temp: ");
     Serial.println(logEvent.temperature);
   }
   else printError(result);
}

void selectLastSecondRecord()
{
 int lastRecNum = db.count();
 EDB_Status result = db.readRec(lastRecNum, EDB_REC secondEvent);
 if(result == EDB_OK)
  {
   Serial.print("Second Event ID: ");
   Serial.print(secondEvent.id);
   Serial.print("Last Name: ");
   Serial.print(secondEvent.lastname);
  }
  else printError(result);
}

What's the trouble?

I missed about the address, its all good now. Thank you!

I think I have found the answer to my problem. I forgot to increase the address of the EDB_header.
I wrote:
db.create(0, TABLE_SIZE, (unsigned int)sizeof(logEvent));
db.create(0, TABLE_SIZE, (unsigned int)sizeof(secondEvent));

Instead of:
db.create(0, TABLE_SIZE, (unsigned int)sizeof(logEvent));
db.create(1, TABLE_SIZE, (unsigned int)sizeof(secondEvent));

I think I have found the answer to my problem. I forgot to increase
  the address of the EDB_header.

you're right about increasing the address of EDB_header.
But the address is the position from where the library starting reading/writing.
if you have a look at
https://github.com/jwhiddon/EDB/blob/master/EDB.cpp#L66
and
https://github.com/jwhiddon/EDB/blob/master/EDB.cpp#L34
the library writes a fixed size of the header in the binary format
which includes

a magic byte to recognize the EDB header
the number of records currently present in the table which is 0 at of this time
size of your single record
the size of the table (max amount of memory that the table is allowed to consume)

and to write a new record
https://github.com/jwhiddon/EDB/blob/master/EDB.cpp#L93
so in
db.create(0, TABLE_SIZE, (unsigned int)sizeof(logEvent));
db.create(1, TABLE_SIZE, (unsigned int)sizeof(secondEvent));

the second statement will override the old header excluding the first byte (0'th position)
the solution to your problem will be
unsigned int FIRST_TABLE_HEADER_POSITION = 0;
db.create(FIRST_TABLE_HEADER_POSITION, FIRST_TABLE_SIZE, (unsigned int)sizeof(logEvent));

unsigned int SECOND_TABLE_HEADER_POSITION = FIRST_TABLE_HEADER_POSITION + (unsigned int)sizeof(EDB_Header) + FIRST_TABLE_SIZE;

db.create(SECOND_TABLE_HEADER_POSITION, SECOND_TABLE_SIZE, (unsigned int)sizeof(secondEvent));

now you can use
EDB_Status result = db.open(FIRST_TABLE_HEADER_POSITION );

and
db.close();
EDB_Status result = db.open(SECOND_TABLE_HEADER_POSITION );

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Using Arduino Uno as USB to serial converter
Can I use my Arduino Uno as a USB to serial converter to program my Raspberry pi 0 over serial communication?
My idea: Computer connects to Arduino via USB > Arduino connects with Raspberry pi 0 via GPIO pins.
How do I go about this?

Have you heard about SSH?

You probably can - but what are you trying to achieve? What's wrong with the normal methods which makes you want to do it this way?

I have the Raspberry pi 0 without WiFi, so SSH is no option for me. I would like to communicate with it over serial line. Since I have an Arduino anyway, I thought that might work to program the pi.

You may also put Arduino in a reset state then Rx & Tx lines of serial converter will be free.

If you load an empty program in your arduino, and make the folowing connections:
Pi  -->  Arduino
Pin 8 --> Pin 1
Pin 10 --> Pin 0
Gnd --> Gnd
than you should see your linux console in the arduino serial program is you set the baudrate to 115200.
This method will work for the raspberry pi models without wifi.
On the wifi models the pins on the pi will be different.
The Arduino uses FTDI usb-to serial converter. This converters uart side is connected to the AVR-chip via pin 0 and 1. If you load an empty program in your arduino, it wil not use these lines. Now you can connect directly to the FTDI chip thru this pins. The converter does not care if it is communicating with the arduino or the pi over these lines.

The Arduino uses FTDI usb-to serial converter. This converters uart side is connected to the AVR-chip via pin 0 and 1. If you load an empty program in your arduino, it wil not use these lines. Now you can connect directly to the FTDI chip thru this pins. The converter does not care if it is communicating with the arduino or the pi over these lines.

The Arduino uses FTDI usb-to serial converter. ... that is not true for UNO

They changed the FTDI with a compatible Atmel part between revisions, but the concept stays the same as with the FTDI.

In the arduino ide, go to file > examples > arduino as isp.
Might be a good starting point.
Seems like a lot of work though. If I were in that situation then I'd either use an ethernet cable and SSH, or, use a mobile phone as a WiFi hot-spot.


text:
Why can't my IF statement see a global?
I'm rather new to Arduino programming. I have a problem compiling the following bit of code:
const int relay1 = 10;  //Power Relay 1
const int relay2 = 11;  //Power Relay 2
const int relay3 = 12;  //Toggle Relay
const int button1 = 3;
const int button2 = 4;
const int button3 = 5;

//---Button States---\\
int button1State;   //Current state of Button 1
int button2State;   //Current state of Button 2
int button3State;   //Current state of Button 3
int button1State_prev = LOW;  //Previous state of Button 1
int button2State_prev = LOW;  //Previous state of Button 2
int button3State_prev = LOW;  //Previous state of Button 3

//---General Variables---\\
int userSelection = 0;
int interlockState = 0;
int platformState = 0;

//---Interval-Tracking Variables---\\
unsigned long lastTime_Debounce1 = 0;   //Button 1 debounce time
unsigned long lastTime_Debounce2 = 0;   //Button 2 debounce time

//---Activity Delays---\\
const unsigned int relayDelay = 10;           //Delay between relay actions (ms)
const unsigned int debounceDelay = 60;        //Delay for button de-bouncing (ms)

void setup() {
  //Configure Pins
  pinMode(relay1, OUTPUT);
  pinMode(relay2, OUTPUT);
  pinMode(relay3, OUTPUT);
  pinMode(button1, INPUT);
  pinMode(button2, INPUT);
  pinMode(button3, INPUT);

  digitalWrite(relay1, LOW);
  digitalWrite(relay2, LOW);
  digitalWrite(relay3, LOW);
}

void loop() {
  //Read value of each input pin
  int button1Reading = digitalRead(button1);  //Current reading of Button 1
  int button2Reading = digitalRead(button2);  //Current reading of Button 2
  int button3Reading = digitalRead(button3);  //Current reading of Button 3

  //Debounce Button1
  if (button1Reading != button1State_prev) {
    lastTime_Debounce1 = millis();
  }
  button1State_prev = button1Reading;
  if ((millis() - lastTime_Debounce1) > debounceDelay) {
    if (button1Reading != button1State) {
      button1State = button1Reading;
    }
  }

  //Debounce Button2
  if (button2Reading != button2State_prev) {
    lastTime_Debounce2 = millis();
  }
  button2State_prev = button2Reading;
  if ((millis() - lastTime_Debounce2) > debounceDelay) {
    if (button2Reading != button2State) {
      button2State = button2Reading;
    }
  }

For some reason, the compiler is convinced that the variable lastTime_Debounce1 in the second IF-statement, on Line 54, has not been declared in-scope. I don't understand how this is possible, since the variable in question is a defined and initialized global.
If I comment-out the first trio of IF-statements (handling Button 1), the second trio (handling button 2) has no problem compiling, even though it does exactly the same thing in exactly the same way.
I checked all the usual suspects: spelling, braces, semicolons, even commented-out blocks of code one at a time, but I can't find the source of the problem. I'm using the Arduino 1.8.2 IDE.
Can someone please point out the mistake I'm missing?

I tagged your question with the C++ tag to see if the syntax highlighting would make the problem more obvious, but unfortunately not.

The backslash in your comments are the problem. As per C++ language definitions, a \ at the end of the line is interpreted as a "line continuation". Thus, your comment gets continued in the next line and your variable declaration and initialization is commented out.
This is apparent when opening your code with a good syntax highlighting program, like Notepad++.

Removing all \\ from the end of the comment line solves your problem.
Side note: For more info, look at https://stackoverflow.com/a/30290133/5296568. Backslashes at the end of a line are actually useful when used in multi-line macro definitions.

I'm surprised the code highlighter here doesn't catch that.

@WernerCD Stack Exchange code markup tries to intelligently detect what language is being used in the code block, but sometimes it fails to do so and thinks it's something it isn't. you can fix it by specifying  before the snippet.

@Nzall see NickGammon comment above; even the StackOverflow syntax highlighter, when put in C/C++ mode (by adding C++ tag), doesn't highlight it correctly.

Why does that even work? Shouldn't the first \ demask the second one and thus not comment out the new line?

I am not aware of a \  in a comment being able to escape the next character as if it the \\ was placed in a character string.


text:
Issue programming breadboarded Arduino via FTDI chip
I am trying to upload the Blink sketch to my ATmega chip which is now on a breadboard connected via an FTDI chip.
My clock is running, power is OK. I connected the reset pin via a 100 kohm to the vcc and have a 0.1 uF capacitor between the reset pin and the DTR pin of my FTDI chip.

Connections to the PCB with the FTDI chip:

Does anybody know what I am doing incorrectly?
On a side note, I am running Ubuntu 16.04
All this seems correct to me, yet when I try to program the controller I get this exact:
/home/yalishanda/Downloads/arduino-1.8.5/arduino-builder -dump-prefs -logger=machine -hardware /home/yalishanda        /Downloads/arduino-1.8.5/hardware -tools /home/yalishanda/Downloads/arduino-1.8.5/tools-builder -tools /home/yalishanda    /Downloads/arduino-1.8.5/hardware/tools/avr -built-in-libraries /home/yalishanda/Downloads/arduino-1.8.5/libraries -libraries     /root/Arduino/libraries -fqbn=arduino:avr:uno -ide-version=10805 -build-path /tmp/arduino_build_476404 -warnings=none -build-        cache /tmp/arduino_cache_889393 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arduinoOTA.path=/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr -prefs=runtime.tools.avrdude.path=/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr -prefs=runtime.tools.avr-gcc.path=/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr -verbose /home/yalishanda/Downloads/arduino-1.8.5/examples/01.Basics/Blink/Blink.ino
/home/yalishanda/Downloads/arduino-1.8.5/arduino-builder -compile -logger=machine -hardware /home/yalishanda/Downloads/arduino-1.8.5/hardware -tools /home/yalishanda/Downloads/arduino-1.8.5/tools-builder -tools /home/yalishanda    /Downloads/arduino-1.8.5/hardware/tools/avr -built-in-libraries /home/yalishanda/Downloads/arduino-1.8.5/libraries -libraries /root/Arduino/libraries -fqbn=arduino:avr:uno -ide-version=10805 -build-path /tmp/arduino_build_476404 -warnings=none -build-cache /tmp/arduino_cache_889393 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arduinoOTA.path=/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr -prefs=runtime.tools.avrdude.path=/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr -prefs=runtime.tools.avr-gcc.path=/home/yalishanda/Downloads/arduino-1.8.5/hardware    /tools/avr -verbose /home/yalishanda/Downloads/arduino-1.8.5/examples/01.Basics/Blink/Blink.ino
Using board 'uno' from platform in folder: /home/yalishanda/Downloads/arduino-1.8.5/hardware/arduino/avr
Using core 'arduino' from platform in folder: /home/yalishanda/Downloads/arduino-1.8.5/hardware/arduino/avr
Detecting libraries used...
"/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10805 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-I/home/yalishanda/Downloads/arduino-1.8.5/hardware/arduino/avr/cores/arduino" "-I/home/yalishanda/Downloads/arduino-1.8.5/hardware/arduino/avr/variants/standard" "/tmp/arduino_build_476404/sketch/Blink.ino.cpp" -o "/dev/null"
Generating function prototypes...
"/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10805 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-I/home/yalishanda/Downloads/arduino-1.8.5/hardware/arduino/avr/cores/arduino" "-I/home/yalishanda/Downloads/arduino-1.8.5/hardware/arduino/avr/variants/standard" "/tmp/arduino_build_476404/sketch/Blink.ino.cpp" -o "/tmp/arduino_build_476404/preproc/ctags_target_for_gcc_minus_e.cpp"
"/home/yalishanda/Downloads/arduino-1.8.5/tools-builder/ctags/5.8-arduino11/ctags" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives "/tmp/arduino_build_476404/preproc/ctags_target_for_gcc_minus_e.cpp"
Compiling sketch...
"/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10805 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-I/home/yalishanda/Downloads/arduino-1.8.5/hardware/arduino/avr/cores/arduino" "-I/home/yalishanda/Downloads/arduino-1.8.5/hardware/arduino/avr/variants/standard" "/tmp/arduino_build_476404/sketch/Blink.ino.cpp" -o "/tmp/arduino_build_476404/sketch/Blink.ino.cpp.o"
Compiling libraries...
Compiling core...
Using previously compiled file: /tmp/arduino_build_476404/core/wiring_pulse.S.o
Using previously compiled file: /tmp/arduino_build_476404/core/WInterrupts.c.o
Using previously compiled file: /tmp/arduino_build_476404/core/hooks.c.o
Using previously compiled file: /tmp/arduino_build_476404/core/wiring.c.o
Using previously compiled file: /tmp/arduino_build_476404/core/wiring_analog.c.o
Using previously compiled file: /tmp/arduino_build_476404/core/wiring_digital.c.o
Using previously compiled file: /tmp/arduino_build_476404/core/wiring_pulse.c.o
Using previously compiled file: /tmp/arduino_build_476404/core/wiring_shift.c.o
Using previously compiled file: /tmp/arduino_build_476404/core/CDC.cpp.o
Using previously compiled file: /tmp/arduino_build_476404/core/HardwareSerial.cpp.o
Using previously compiled file: /tmp/arduino_build_476404/core/HardwareSerial0.cpp.o
Using previously compiled file: /tmp/arduino_build_476404/core/HardwareSerial1.cpp.o
Using previously compiled file: /tmp/arduino_build_476404/core/HardwareSerial2.cpp.o
Using previously compiled file: /tmp/arduino_build_476404/core/HardwareSerial3.cpp.o
Using previously compiled file: /tmp/arduino_build_476404/core/IPAddress.cpp.o
Using previously compiled file: /tmp/arduino_build_476404/core/PluggableUSB.cpp.o
Using previously compiled file: /tmp/arduino_build_476404/core/Print.cpp.o
Using previously compiled file: /tmp/arduino_build_476404/core/Stream.cpp.o
Using previously compiled file: /tmp/arduino_build_476404/core/Tone.cpp.o
Using previously compiled file: /tmp/arduino_build_476404/core/USBCore.cpp.o
Using previously compiled file: /tmp/arduino_build_476404/core/WMath.cpp.o
Using previously compiled file: /tmp/arduino_build_476404/core/WString.cpp.o
Using previously compiled file: /tmp/arduino_build_476404/core/abi.cpp.o
Using previously compiled file: /tmp/arduino_build_476404/core/main.cpp.o
Using previously compiled file: /tmp/arduino_build_476404/core/new.cpp.o
Using previously compiled file: /tmp/arduino_build_476404/core/core.a
Archiving built core (caching) in: /tmp/arduino_cache_889393    /core/core_arduino_avr_uno_fbfa3aa7d5698fed1dc5326dc32eae8f.a
Linking everything together...
"/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr/bin/avr-gcc" -w -Os -g -flto -fuse-linker-plugin -Wl,--gc-sections -mmcu=atmega328p  -o "/tmp/arduino_build_476404/Blink.ino.elf" "/tmp/arduino_build_476404/sketch/Blink.ino.cpp.o"     "/tmp/arduino_build_476404/core/core.a" "-L/tmp/arduino_build_476404" -lm
"/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr/bin/avr-objcopy" -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0  "/tmp/arduino_build_476404/Blink.ino.elf"     "/tmp/arduino_build_476404/Blink.ino.eep"
"/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr/bin/avr-objcopy" -O ihex -R .eeprom      "/tmp/arduino_build_476404/Blink.ino.elf" "/tmp/arduino_build_476404/Blink.ino.hex"
Sketch uses 928 bytes (2%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.

/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr/bin/avrdude -C/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr/etc/avrdude.conf -v -patmega328p -cstk500v1 -P/dev/ttyUSB0 -Uflash:w:/tmp/arduino_build_476404/Blink.ino.hex:i

avrdude: Version 6.3, compiled on Jan 17 2017 at 11:00:16
     Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
     Copyright (c) 2007-2014 Joerg Wunsch

     System wide configuration file is "/home/yalishanda/Downloads/arduino-1.8.5/hardware/tools/avr/etc/avrdude.conf"
     User configuration file is "/home/yalishanda/.avrduderc"
     User configuration file does not exist or is not a regular file, skipping

     Using Port                    : /dev/ttyUSB0
     Using Programmer              : stk500v1
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
...

Start with connecting all power pins. You've left Vcc on pin 20 and GND on pin 22 unconnected.

@KIIV ok, did that although I was not sure whether that was really necessary. Unfortunately it still doesn't work

Why it's showing stk500v1 protocol instead of arduino for the avrdude?

@KIIV I don't know, I chose the following options in the arduino ide: "board: arduino/genuino UNO" "port:/dev/ttyUSB0" "programmer: AVR ISP" isn't that correct?

No, you should just upload the code. Just like it's UNO board.

@KIIV ok, I managed to upload it in a different way (upload it like if it were an arduino rather than going via sketch > upload using programmer): https://paste.ubuntu.com/26432421/
But that still doesn't work

And is that chip extracted from the UNO board or it's a new one (without the arduino bootloader)?

@KIIV it is a new one but it normally already should have a bootloader

@KIIV I can see the DTR line on the ftdi chip being low, for a short period being high and the low again. So I think the DTR line is doing its job. In other words the ATMEGA chip is I think correctly being reset.

Do you have a normal Arduino Uno board? You can swap out the chip there and see if you can program it. The board is guaranteed to have all the connections right. If it still fails, your ATMega328P has not been programmed with the Arduino Bootloader. You'll need another working Arduino or a ICSP programmer for that. Also: https://www.youtube.com/watch?v=5fvdxd0QhTw and https://www.baldengineer.com/diy-arduino-schematic-checklist.html might be good references for you.

@MaximilianGerhardt I can't do that because the arduino uno I have uses a mcu in an smd package not through hole

There are only 3 possibilities: Wrong wireup (use above reference to check that), no bootloader on your chip, or chip is straight out dead. After you compared the wireup, I would still try to burn the Arduino bootloader to the chip. You can't destroy it further with that anyways. Try to follow https://www.youtube.com/watch?v=VX0P8B3pk7g .

@MaximilianGerhardt I am able to get the board info (Tools > get board info). Can I infer from that that the chip is alive and wiring is OK? And I am maybe unable to upload code due to a corrupt bootloader?

if you disconnect the avr chip, do you still get board info? (leave ftdi connected)

@LandonZeKepitelOfGreytBritn How do you know the chip should have a bootloader when new? Did you specifically buy one with a bootloader installed? They don't come from the factory like that.

@Majenko yes I specifically bought one with a bootloader

Right now you don't have a bootloader on your chip that's the reason why it wouldn't be programmed via UART so to flash the bootloader you need an ISCP programmer and an arduino bootloader.hex file.

10K reset pullup.
Check your crystal caps, they should be 22pF.
The response does look like the chip does not have a bootloader tho.
Or Rx & Tx lines are swapped.


text:
HC-05 bridge using Arduino Nano and GNU Screen
I connect an HC-05 module to an Arduino nano with CH341 serial chip (voltage divider on RX pin). I am trying to make a bridge for a test, i.e. serial in, echo local and echo to Bluetooth and vice versa. I modified the echo code from here.
int incomingByte = 0;    // for incoming serial data

#include <SoftwareSerial.h>

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

void setup() {
    BTSerial.begin(38400);    // opens serial port, sets data rate to 9600 bps
    Serial.begin(9600);    // opens serial port, sets data rate to 9600 bps
}

void loop() {
  // send data only when you receive data:
  if (Serial.available() > 0) {

    // read the incoming byte:
    incomingByte = Serial.read();

    // say what you got:
    Serial.print((char)incomingByte);
    BTSerial.print((char)incomingByte);
  }

  if (BTSerial.available() > 0) {

    // read the incoming byte:
    incomingByte = Serial.read();

    // say what you got:
    Serial.print((char)incomingByte);
    BTSerial.print((char)incomingByte);
  }

under OSX I open two terminals. In the first terminal using screen /dev/cu.wchusbserial1410 9600 I see local echo as desired. But on the second terminal using screen /dev/cu.HC-05-SPPDev 38400 I see nothing after pairing. The only effect is that by typing the latter command, the module stops blinking rapidly and blinks only two times with long pause in between. Exiting the screen environment, then again blinks rapidly.
Appreciate any hints what I am doing wrong...
=====
intermediate success but not quite there yet:
I simplified the code and corrected the wrong connection. Local echo on serial works as usual, even between the two, characters are being transferred, but they are black question marks instead of why I typed.
/*
 * echo script
 */

byte incomingByte;

#include <SoftwareSerial.h>

SoftwareSerial BTSerial(3, 2); // RX | TX

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

void loop() {
  if (Serial.available()) {
    incomingByte = Serial.read();
    Serial.print((char)incomingByte);
    BTSerial.print((char)incomingByte);
  }

  if (BTSerial.available()) {
    incomingByte = BTSerial.read();
    Serial.print((char)incomingByte);
    BTSerial.print((char)incomingByte);
  }
}

Any ideas?
========
Edited the Buadrate to 9600. Now everything works.

Might want to check the sketch logic. "BTSerial.available() > 0" and then "incomingByte = Serial.read();". Hum, and then all the echo statements. Also comments say 9600 baud but code says 38400 (which is tough for softwareserial).

Make sure your RX and TX pins actually connect to the right pins. TX to RX and RX to TX.

thanks for both comments. Indeed the RX and TX pins were connected at the wrong position. I got a bit of success, but I am not quite there yet (see edited post).

As Mikael noted, 38400 baud is a challenge for SoftwareSerial to reach without errors. Try 9600.

yes now it works. both at 9600 baud works. But I wonder how to manage higher baud rates with HC-05, if software serial does not supper higher speeds?

Based on the above comments I provide here the full answer in the hope it will be useful in the future.
HC-05 has two modes. The Communication Mode and AT Command Mode. In the latter mode, HC-05 responds in kind of "config" way and many default settings of the communication mode can be change here. While the baud rate of the communication mode, and many other settings can be changed, the baud rate of the AT command mode is always fixed 38400 to avoid any confusions and mistakes. On the other hand, the default factory baud rate of the communication mode, i.e. before any change, is set to 9600. So the solution to my problem was to set the baud-rate to 9600 on my newly purchased HC-05 and I was able to make an echo bridge between HC-05 Bluetooth and serial. Here is the code:
/*
 * echo script
 */

byte incomingByte;

#include <SoftwareSerial.h>

SoftwareSerial BTSerial(3, 2); // RX | TX

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

void loop() {
  if (Serial.available()) {
    incomingByte = Serial.read();
    BTSerial.print((char)incomingByte);
  }

  if (BTSerial.available()) {
    incomingByte = BTSerial.read();
    Serial.print((char)incomingByte);
  }
}

After pairing HC-05 with OSX, I was able to open two OSX Terminals with one of these commands in the first terminal:
screen /dev/cu.wchusbserial1410 9600

and in the other:
screen /dev/cu.HC-05-SPPDev 9600

Everything worked properly, i.e. typing in one terminal produced characters in the other and vice versa. For changing the default baud-rate in the communication mode, I found a very good tutorial which can be found here.

This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - From Review

To make this question and answer useful in the "Stack Exchange" way, can you please change your answer to summarize what the problem was. As it is it reads like "I had a problem" and "I solved it" which doesn't really help anyone else.

@LookAlterno It is not possible to "accept" a comment, whereas the solution was in the comment. So I had to answer the question myself. It does not even allow me to like a comment, the like buttons are off.

@NickGammon I have already edited the OP. The answer was in the comments others left, so I had to create an answer so that it can be accepted. Or how do you do this the "Stack Exchange" way?

@MichelKeijzers I have updated the answer to include the full description.

Your amended answer is much better, thank you. It will hopefully help other people in the future who have a similar problem. :)


text:
strcmp() returns 0 when chars are different
I am trying to build a sketch that reads a single number from the Serial Monitor and uses it to light a 7 segment display with this number.
I need to compare the input with the known values, stored in a char array, to know which character was typed in and associate the matching binary combination to light the 7 segment display.
I have made a sample code extracted from the sketch, just to test if I am able to pass a char and get the correct result back:
char nums[] = "0123456789."; // The characters we will check against

/* Tried also these, same results
      char nums[12] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', '\0'};
      char nums[] = "456789.0123";
*/

void setup() {
  Serial.begin(9600);
  Serial.println("Write a single character"); Serial.println(" ");
}

void loop() {
  if (Serial.available() > 0) {
    char text = Serial.read(); // Read a single char from serial
    Serial.print("Character provided is: "); Serial.println(text);
    char c = parseChar(text); // Evaluate the char
    Serial.print("Character returned is: "); Serial.println (c);
    if (strcmp(c, text) == 0) { // Check if the returned char is the same
      Serial.print("      CORRECT character returned");
    } else {
      Serial.print("      WRONG character returned");
    }
    Serial.println(" ");
  }
}

char parseChar(char c) {
  int comp = 0;
  Serial.println("----- parseChar() START-----");
  Serial.print("  Parameter 'c' is: "); Serial.println(c);
  for (int i = 0; i < sizeof(nums) ; i++) { // Check the values of the array one by one
    comp = strcmp(c, nums[i]); // Compare the chars
    Serial.print("  Compare to nums["); Serial.print(i); Serial.print("] = "); Serial.print(nums[i]); Serial.print(" --> Result: "); Serial.println(comp);

    /* If the check matches, return the character at that index.
       For simplicity, it just returns the matching char of the array,
       that should be the same as the one sent in to the function.
    */
    if (comp == 0) {
      Serial.println("----- parseChar() END (found) -----");
      return nums[i];
    }
  }
  Serial.println("----- parseChar() END (not found)-----");
  return 0;
}

The function works well for all numbers from 0 to 6. However, for any number over 6, or any other character, the strcmp() function returns always 0, so the returned character is the index 0 of the array, regardless of the character typed.
This is the Serial Monitor output for different characters:
Write a single character

Character provided is: 3
----- parseChar() START-----
  Parameter 'c' is: 3
  Compare to nums[0] = 0 --> Result: 1
  Compare to nums[1] = 1 --> Result: 1
  Compare to nums[2] = 2 --> Result: 1
  Compare to nums[3] = 3 --> Result: 0
----- parseChar() END (found) -----
Character returned is: 3
      CORRECT character returned

Character provided is: 6
----- parseChar() START-----
  Parameter 'c' is: 6
  Compare to nums[0] = 0 --> Result: -6
  Compare to nums[1] = 1 --> Result: 1
  Compare to nums[2] = 2 --> Result: 1
  Compare to nums[3] = 3 --> Result: 1
  Compare to nums[4] = 4 --> Result: 1
  Compare to nums[5] = 5 --> Result: 1
  Compare to nums[6] = 6 --> Result: 0
----- parseChar() END (found) -----
Character returned is: 6
      CORRECT character returned

Character provided is: 7
----- parseChar() START-----
  Parameter 'c' is: 7
  Compare to nums[0] = 0 --> Result: 0
----- parseChar() END (found) -----
Character returned is: 0
      WRONG character returned

Character provided is: g
----- parseChar() START-----
  Parameter 'c' is: g
  Compare to nums[0] = 0 --> Result: 0
----- parseChar() END (found) -----
Character returned is: 0
      WRONG character returned

As you can see, the parseChar() function never returns a "not found" result, even for chars that are not in the array. In fact, it never loops through the array, as the first comparison returns 0 always.
I can't figure out why the strcmp() function returns 0 when the chars are different. Am I missing something?

Change "comp = strcmp(c, nums[i]);" to "comp = (c - nums[i]);" might do the trick. Nick explains why.

strcmp is not for comparing a single character like your c parameter. It is for comparing a null-terminated string. I'm a little surprised you didn't get a compiler error, but there it is.
If you want to compare individual characters, just compare them with ==.

Thanks @nick, seems to work. Just to clarify, == should be used when comparing char,and strcmp() when comparing char[]?

Generally speaking, you use == to compare two simple things of the same type (like numbers, characters, floats, etc.) strcmp is specifically for comparing a null-terminated string of characters.


text:
Purposely create compile error to fail the upload
I would like to create a compile error so sketch does not upload in certain cases.
I have written a library with a function that adds pins being used to an array. If the same pin is used twice I want to fail the compilation (preferably with an error that explains why). Is this possible?
void CheckPinNum(int newPinNum){
  for (int i=0; i <= PinArrayLength; i++){
    if (newPinNum == PinArray[i])
      failCompilation("You entered same pin twice!");
  }
}

Do you know the difference between compile time and execution time?

I'm voting to close this question as off-topic because it contains fundamental errors about compiling and executing programs.

@LookAlterno If you vote that way, please be kind enough to explain to me how I should ask the question to get where I want.

It's not how you asked it, but what you asked for. You want a compiler that can pre-evaluate something that will be unknow until execution time. That's is impossible in general (see Turing's Halting Problem). And, how do you pretend to tell the compiler about your particular restrictions imposed over the data? Where do you intend to put that info?

@LookAlterno So in that case you can write an answer like "This is not possible because a compiler can't pre-evaluate the variables written in the sketch". Or suggest someway that can work. Thanks anyway.

Or you pass your Programming 101 course. This about Arduino, not a programming school.

@LookAlterno Are you not aware that many people using Arduino may have never taken any course and they learn as they go? Anyway, the "Be Kind 101" course is a lot more fundamental.

How could this be done? What fundamental mechanisms are available in C++? Actually there is. It is called static_assert http://en.cppreference.com/w/cpp/language/static_assert. To use it in this case the compiler must be able to evaluate the function at compile-time. This requires the pin number vector to be const but then adding a pin makes no sense (as a compile-time error:). An example of using static_assert can be found here https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/Queue.hh#L36

@bets. Learning to program with Arduino is bad idea: you chose the hardest programming language posible (C++), with subpar IDEs, skinny documentation, and no debugging capabilities at all. I'm sorry not being kind enough for you.

@bets. The question has been answered but I want to point out that C++ is not the hardest language to learn. A major factor in assessing the difficulty of learning a language is the order in which you learn them. For example, If you want to go the C/C++ route then learning assembly first makes learning C easy, especially when dealing with pointers which is the hardest thing for many novices. Secondly, Arduino is a great way to get into programming (and electronics) Just about anything you can think of has been done with them and there is a huge community out there willing to help.

It's impossible to check dynamic behavior compile time.
However, the best 'alternative' I can think of, is during the setup set all pin numbers (if that is possible).
And if something is wrong, let the 'user' or client know something is wrong. In extreme cases, just by putting the Arduino in an endless loop, in best cases, send a serial line, blink a light or whatever feedback.
You can do the same later on (when CheckPinNumber needs to be called in the loop, so not at setup), but the sooner you can do these checks, the better.

To answer the question asked in the title:
#if some_condition
# error Some error message
#endif

But note that this technique only works at compile time, which
probably makes it useless for you.

Thanks! "compile time" is good for me. I'm not sure I totally understand this answer. But I will try to figure out how to check the vars entered in the sketch this way.

Pay attention that the some_condition must be a constant integer expression (not using any variable or function call) computable at compile time.


text:
Running multiple programs with one Arduino
Is it a problem to use multiple softwares to read the data that came from the same USB port simultaneously?
I have a board connected to a PC by USB, which is read by an application developed in C#. I display the data from the board in a table form.
Now I have to plot the data. The problem is that both the board and the software are deployed and can't be modified. So I have to create another program to do that, but the user should be able to run both softwares simultaneously.
Thank you!

If you are running Linux you can do this in a few lines of shell script; https://stackoverflow.com/questions/38361531/how-to-duplicate-dev-ttyusb0-stream

The question is not so much about Arduino, but about PC serial ports. There are programs/drivers out there that allow a user to "split" a serial port into two or more virtual serial ports, each of which can be opened by separate Windows applications, such as your C# programs.
Some of these programs or drivers are commercial and not free, and some are free.
https://www.fabulatech.com/serial-port-splitter-help/serial-port-splitting.html
http://www.eterlogic.com/help/vspe/UsageSplitPage.html
http://www.aggsoft.com/tcp-com/tcp-com-com-splitting.htm