Arduino clock needed to print the time a button is pressed while continuing to count the time? I'm making a clock using an arduino uno and a compatible freetronics screen. So far it can count the time in a 24 hour loop after which it repeats and counts again. The screen had a number of buttons built onto it and I want to get it so that when one of the buttons on the screen is pressed it prints the time that it was pressed on the top line of the screen while continuing to count and print the time on the second line of the screen.

How can I edit my code below to do this when a button is pressed? What sort of command do I need to add?

#include <Wire.h>
#include <LiquidCrystal.h>

#define MILLIS_OVERFLOW 34359738

/**
* Clock Variables
*/
unsigned long currentMillis, previousMillis, elapsedMillis;
int seconds = 0, minutes = 0, hours = 8;

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

void setup()
{
  Serial.begin(9600);
    lcd.begin( 16, 2 );

}

void loop()
{
setClock();

/**
 * After set clock now you have 3 int variables with the current time
 */
 //seconds
 //minutes
 //hours
 lcd.setCursor ( 0, 1);
 lcd.print(hours);
 lcd.print(":");
 lcd.print(minutes);
 lcd.print(":");
 lcd.print(seconds);
 lcd.print(":");
 lcd.print(elapsedMillis);

}

void setClock()
{
currentMillis = millis();
/**
 * The only moment when currentMillis will be smaller than previousMillis
 * will be when millis() oveflows
 */
if (currentMillis < previousMillis){
    elapsedMillis += MILLIS_OVERFLOW - previousMillis + currentMillis;
} else {
    elapsedMillis += currentMillis - previousMillis;
}

/**
 * If we use equals 1000 its possible that because of the mentioned loop limitation
 * you check the difference when its value is (999) and on the next loop its value is (1001)
 */
if (elapsedMillis > 999){
    seconds++;
    elapsedMillis = elapsedMillis - 1000;
}

if (seconds == 60){
    minutes++;
    seconds = 0;
}
if (minutes == 60){
    hours++;
    minutes = 0;
}
if (hours == 24){
    hours = 0;
}

previousMillis = currentMillis;
}

Any help will be greatly appreciated, thanks

Since you will have to deal with two different times, I suggest
writing a small class for representing those times in broken-down form.
This is a reduced version of the classical strcut tm. Times are made
Printable so you can just print() them to the LCD. I included an
increment() method to add one second to this time.

class BrokenDownTime : public Printable {
    uint8_t hours;
    uint8_t minutes;
    uint8_t seconds;
public:
    void increment();
    size_t printTo(Print &p) const;
};

/* Increment the time by one second. */
void BrokenDownTime::increment()
{
    if (++seconds >= 60) {
        seconds = 0;
        if (++minutes >= 60) {
            minutes = 0;
            if (++hours >= 24)
                hours = 0;
        }
    }
}

/*
 * Print to anything that inherits from the Print class (Serial,
 * LiquidCrystal, etc.). This makes times `Printable'.
 */
size_t BrokenDownTime::printTo(Print &p) const
{
    p.print(hours/10);
    p.print(hours%10);
    p.write(':');
    p.print(minutes/10);
    p.print(minutes%10);
    p.write(':');
    p.print(seconds/10);
    p.print(seconds%10);
    return 8;  // 8 bytes written
}

The main program checks in loop() for the button being pressed. When
this happens, it saves the current time as lastPress. If the button
was ever pressed (variable button_was_pressed), the recorded time is
displayed on the first line:

#include <LiquidCrystal.h>

#define BUTTON_ADC_PIN A0

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
BrokenDownTime now;

/* Detect a press on `left', change the thresholds for other buttons. */
bool buttonPressed()
{
    int reading = analogRead(BUTTON_ADC_PIN);
    return reading > 405 && reading < 605;
}

/* Update `now'. */
void updateTime()
{
    static unsigned long last;
    if (millis() - last >= 1000) {
        now.increment();
        last += 1000;
    }
}

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

void loop()
{
    static BrokenDownTime lastPress;
    static bool button_was_pressed;

    updateTime();

    /* Record the time of the button press. */
    if (buttonPressed()) {
        lastPress = now;
        button_was_pressed = true;
    }

    /* Display the recorded time on the first line. */
    if (button_was_pressed) {
        lcd.setCursor(0, 0);
        lcd.print(lastPress);
    }

    /* Display the current time on the second line. */
    lcd.setCursor(0, 1);
    lcd.print(now);
}

I did not test the program, but I hope you get the idea.


Asymmetric encryption on a Teensy? I want to monitor an input and then send the information in an encrypted way that can't be easily unlocked even if a malicious actor gets access to the device itself. I'm new to using the Teensy although I have done a few simple things with Arduino microcontrollers. I was hoping to find out if anyone has implemented RSA or other asymmetrical encryption on a Teensy or to figure out if it has enough processing power to make it feasible. I would also accept using other Arduinos (I have an MKR1000 as well), for this but I assume because the Teensy has much better performance it's more likely to be able to do computationally expensive encryption.
This won't need to decrypt anything, it will only be sending data encrypted using the public key of the receiving user.

Teensy4.1 has 55 digital IO (serial) pins at up to 200MHz. The USB port supports 480mbps, and ethernet is 10/100mbps. You're limited to 32 DMA channels, though (complicated but these are used to access onboard peripherals/memory). You don't have much contiguous ram, either.
Now, you haven't explained what you're doing with this data. This matters because even though the CPU is running at 600MHz, asymmetric encryption is slow. Are you trying to perform real-time encrypted communication? Are you just sending or receiving data as well?
Nothing stopping you from asymmetrically encrypting on a Teensy. You can find the source code for the OpenSSL functions RSA_public_encrypt and RSA_private_decrypt.
This question goes into calculating how many CPU cycles are needed to encrypt X bytes of data.
However, asymmetric encryption has problems: Like I said, it's slow - specifically RSA, and the size of the data you can encrypt depends on the size of your key and padding.
If you want to communicate in something resembling real-time, you want to use hybrid encryption. You should read about how TLS works; the short version is that an asymmetric handshake occurs where the two parties agree on a symmetric key. Once you decide what your data actually is, you can quantize it (eg. TLS 'chunks' are up to 16KB which are then sent as multiple TCP packets) then both parties use the symmetric key to send/receive - which can encrypt large data chunks without issue.


Feasibility of project with 50 leds working independently I don't have much knowledge in Arduino and I'm about to start a new project which I believe can be done with it.

There will be 50 boxes with a led in top of each one. The user will type a number in a keyboard (1 to 5 for example), and then based on a table, the leds according to that number should light up.

It will have some overlaps, for example, Number 1 would light led 1, 2 and 3, while Number 2 would light leds 1, 2, 3 and 4.

Could I build such a project with arduino? Or are there too many inputs/outputs (keyboard, 50 leds)? I was thinking to buy an Arduino Uno to start learning, but first I'd like to know if it's feasible.

Thanks already

depending on how you want to control your LED's there are several options.
firstly to be clear you could not feasibly connect that many LEDs to an arduino that could all be turned on at once (if that was needed) without damaging the arduino.
if all you need is on/off level of control then you could look at shift registers or if you have pre built arrays of LEDS in a grid type layout you could look at the MAX7219/MAX7221
if you also wanted to be able to control the brightness individually then you could look at the TLC5940
if we look at the pros and cons of each approach:
74HC595
pros:

cheap to buy
simple to use

cons:

each LED needs its own resistor
cannot vary brightness
if not using the hardware SPI pins can be slow for large numbers of outputs

MAX7219/MAX7221
pros:

lower current draw than 74HC595
only needs one resistor per IC which can drive 64 LEDs

cons:

actually flashes LED's really fast to look like they are always on
costs more than 74HC595

TLC5940
pros:

can vary brightness with a high number of steps (4096 steps from fully off to fully on)

cons:

uses more output pins than either of the above methods
requires resistor per LED
costs more for the IC than 74HC595

so to sum up, each method has its merits. if you are driving individual LEDs the the 74HC595 is probably the best/simplest route, if you are driving an array then the MAX7219/MAX7221 is best, and if you need variable brightness then the TLC5940 is probably best.


Could not read ID via SWD with Arduino So I'm trying to read a bit of data via SWD. I've tried two chips as target - LPC1110 and STM32F030F4 (the first of them I used for other schematic, but I've reset the flash to make sure the pins are not configured improperly).

I use Arduino as a host. I wire D3 to SWCLK and D4 to SWDIO (with pull-up to 3.3V line). I fail miserably with both chips - i.e. when I expect some ACK be read - it only shows HIGH state on the line all the time.

Here is my code. Could anyone have a look and tell where I went wrong:

int swdck = 3;
int swdio = 4;

void setup() {
  pinMode(swdck, OUTPUT);
  digitalWrite(swdck, HIGH);
  pinMode(swdio, INPUT);
  digitalWrite(swdio, HIGH);
  Serial.begin(9600);
}

// write some bits from X (least significant first) to SWD
void clockOut(int x, int bits) {
  pinMode(swdio, OUTPUT);
  while (bits > 0) {
    digitalWrite(swdck, LOW);
    digitalWrite(swdio, (x & 1) ? HIGH : LOW);
    delay(1);
    digitalWrite(swdck, HIGH);
    delay(1);
    bits--;
    x >>= 1;
  }
  pinMode(swdio, INPUT);
  digitalWrite(swdio, HIGH);
}

// read some bits from SWD, least significant first
int clockIn(int bits) {
  pinMode(swdio, INPUT);
  digitalWrite(swdio, HIGH);
  int i, res;
  res = 0;
  for (i = 0; i < bits; i++) {
    digitalWrite(swdck, LOW);
    delay(1);
    if (digitalRead(swdio) == HIGH) {
      res += (1 << i);
    }
    digitalWrite(swdck, HIGH);
    delay(1);
  }
  return res;
}

void loop() {
  int x;
  // unlock sequence though it probably is not needed
  clockIn(26); clockIn(26); // more than 50 clocks
  clockOut(0xE79E, 16); // command to switch to SWD
  clockIn(26); clockIn(26);

  clockOut(0x25, 7); // 0b0100101 - request to read Debug-port-0, i.e. ID
  x = clockIn(5); // there should be ACK bits somewhere... but I get 0x1111
  clockIn(26); clockIn(26); // perform more readings for case anything is returned
  Serial.println(x);
  delay(1000);
}

I am not a SWD expert; it is several years since I read the spec. So I apologise if you are way ahead of me.

I believe ARM's SWD documentation, e.g. "ARM® Debug Interface v5 Architecture Specification" (ARM IHI 0031A) says that transfers are fixed length, starting with an 8 bits request.

The code:

void clockOut(int x, int bits) {
  pinMode(swdio, OUTPUT);
  while (bits > 0) {
    ...
    bits--;
    ...
  }
  ...
}

is invoked with clockOut(0xE79E, 16)

A packet request is 8 bits, followed by a response from the target. So this doesn't appear to follow the protocol.

Similarly clockOut(0x25, 7) appears to send 7 bits, which also looks wrong, and may explain why the read fails.

Further, there should be a 'turnaround bit' after sending the packet.

This code:

void clockOut(int x, int bits) {
  pinMode(swdio, OUTPUT);
  ...
  pinMode(swdio, INPUT);
  digitalWrite(swdio, HIGH);
}

looks like it is setting up to do that, however, it also needs to signal another clock pulse, e.g.:

void clockOut(int x, int bits) {
  pinMode(swdio, OUTPUT);
  ...
  pinMode(swdio, INPUT);
  digitalWrite(swdio, HIGH);
  /* signal a clock pulse */
  digitalWrite(swdck, LOW);
  delay(1);
  digitalWrite(swdck, HIGH);
  delay(1);
 }

A SWD read should return 33 bits, so x = clockIn(5); looks a bit fragile.

Even so, it should get the three ACK bits. It should leave another pile of bits unread, which is what I mean by fragile.

However, x = clockIn(5); might be incorrect because of the short clockOut(0x25, 7) and lack of a turnaround bit.

Small points:

I'd change that clockOut while loop to be a for loop like clockIn to make it clear that it is running for a specific 'count' (bits) of bits to be transferred.
delay(1) seems to be a long time between bits. I don't remember any
timing restrictions. However, I would expect the transfers to run
10-100x faster.
IMHO clockIn(26); clockIn(26); seems to be an unnecessarily obscure way
to generate the 50 cycle connection/reset sequence. I'd probably have
a slightly simpler function than clockIn which only generates the
connection/reset sequence.

Edit:
The statement res += (1 << i); in clockIn works.

However, I had to read it a couple of times to recognise that it is assembling a binary value, and not doing some tricky arithmetic. It is more common to use bitwise operators to assemble a binary value. It is only a small point of style, however res |= (1 << i); might be more clearly constructing a binary value, than res += (1 << i); because it can only ever effect one bit, and never many bits.


Is it possible to connect many (20+) SPI sensors to an Arduino Mega? I am making a system for measuring whether or not there is vacuum present in big steel containers. They are located up to 100 meters from the control cabinet.

The question is, how many SPI sensors can I successfully use at the same time with an Arduino Mega?

I have two main concerns, and there are probably more things I didn't think about.

Signal strength
The shared lines for CLK, MOSI and MISO will need to be split up at several junction boxes and led to the different sensors. Since the voltage out from the Arduino is fixed, I'm fearing instability because the signal is weaker for some sensors, has someone done something similar? What is the greatest acceptable voltage loss for these lines to an ordinary sensor?

Processing
Will the SPI library be fine coping with this many sensors?

The refresh rate can be set to extremely low, thinking 0.3Hz.

The alternative to all this is to go for 4-20mA sensors and have a 0-5V converter circuit for each sensor, near the controller.

Any inputs would be greatly appreciated!

You can control as many SPI devices as you can set the CS line for. You can even control all the CS lines from a SPI device. A SIPO register will help a lot there.

However you are probably better off using a proxy board to actually connect to the sensors and then connecting the mega to the proxy to communicate the measurements using a connection that is more robust over long distances.


Connecting Saleae Logic 8 to MISO (pin 12) on Uno 3 w/ NRF24L01+ halts program I have an NRF24L01+ with the base module (regulates voltage) connected to an Arduino Uno 3.  I'm using the tmrh20 NRF24 library and am running one of the example programs.  I'm trying to sniff the SPI bus so I have a Saleae Logic 8 hooked up.  As soon as I connect the clip to the MISO pin the Arduino program stops executing.  I'm able to reproduce this 100% of the time.  It seems it is only the MISO pin that is causing the problem.  For the library I am using MISO uses pin 12 on the Uno 3.

Anybody know what is going on?  It seems as if the Saleae is grounding pin 12 when I hook it up.  Not sure why it is only pin 12 that is an issue though.

I can reproduce the same problem when I manually connecting pin 12 straight to GND as well.

I can collect samples without MISO just fine but that of course only tells me half the story.

Any suggestions?

EDIT:
Here are some links and resources for more information.

I'm basically following the instructions from this article:
http://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo

The breakout board
http://www.addicore.com/1x-nRF24L01-Adapter-p/ad279.htm

And it's schematic:

Link to the datasheet for the radio itself:
http://www.nordicsemi.com/eng/Products/2.4GHz-RF/nRF24L01

And some photos of how I have it wired up:

It would appear from your description that the leads on your logic analyzer distort of the SPI MISO waveform and the Arduino does not read incoming data correctly.

To avoid this, you could place an digital isolator between the Arduino and the Logic 8.

Any decent oscilloscope should also allow you to read the SPI bus.


How to toggle LED on button press? I want to have a LED turn on when I push a button and go off when I push the button a second time.

This code doesn't work:

const int buttonPin = 4;
const int motorPin =  10;
const int ledPin = 6;
 int x = 1;
// variables will change:
int buttonState = 0;

void setup() {
  // initialize the LED pin as an output:
  pinMode(motorPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);
}

void loop(){
  buttonState = digitalRead(buttonPin);
  if (buttonState == HIGH && x==1) {
     digitalWrite(motorPin , 1);
     x=0;
    }
  if (buttonState == HIGH && x==0){
    digitalWrite(motorPin, 0);
    x=1;
  }
  delay(1);
}

What could be wrong?

At the moment, you've got two main problems. Firstly, both your if statements are being triggered one after the other. This is because the first if statement sets x to 0, which is part of the condition the second if statement looks for.

The second problem is that you're not monitoring the previous state of the button. buttonState will appear HIGH every time round loop, even if the button has been held down for several seconds. The result is that the output pin will be quickly getting turned on and off all the time.

What you need to do is store the last known state of the button. On every iteration of the main loop, only respond to the button if it's currently HIGH, and if it was LOW last time round the loop. You also need to make sure your two if statements are mutually exclusive; i.e. if you trigger one then don't trigger the other by mistake too, or it will cancel it out.

Something like this should work better:

// This will store the last known state of the button
int oldButtonState = LOW;

void loop()
{
  // Get the current state of the button
  int newButtonState = digitalRead(buttonPin);

  // Has the button gone high since we last read it?
  if (newButtonState == HIGH && oldButtonState == LOW) {

    if (x == 0) {
      // Toggle on
      digitalWrite(ledPin, HIGH);
      x = 1;

    } else {
      // Toggle off
      digitalWrite(ledPin, LOW);
      x = 0;
    }
  }

  // Store the button's state so we can tell if it's changed next time round
  oldButtonState = newButtonState;
}

As noted elsewhere, you still need to debounce the button, otherwise you're likely to get some false-positives. That can be done in hardware or software. A really simple way to get around it temporarily is to put in a delay of several milliseconds every time you detect the button changing state. It's not perfect, but it might be enough to get you started.


Arduino Web Server: Receiving response from web form I am using an Arduino Mega and I have a basic webpage built using EthernetServer for the connection and EthernetClient to write the HTML to the client. I have a simple web form:

client.println("<form method=get>");
client.println("<input type=text name=data>");
client.println("<input type=submit value=Submit>");
client.println("</form>");

I'd like to receive any input from the form and check it against values in order to do stuff on the back end (e.g. reset certain data). How do I get the data from the web page?

Your form method is set to GET. In this case, when Submit is clicked, the client/browser sends request with values in URI:

GET /index.html?data=user_value&default_name_of_button=Submit HTTP/1.1
...more lines to follow...

These HTTP header lines will be available on your EthernetClient instance, retrieve them line-by-line using connected(), available(), read() methods. Then parse the line, find the user_value.

Please note that browser retrieves your page (to display it) using GET method too, in that case URI will be like:

GET /index.html HTTP/1.1
...more lines to follow...

It is recommended to use POST method to submit form values. Example content section (before content, server must send HTTP header - check Arduino Web Server example)

<form method="POST" action="foo.php">

First Name: <input type="text" name="first_name" />

Last Name: <input type="text" name="last_name" />

<input type="submit" name="action" value="Submit" />

</form>

In this case the values are returned in content section:

POST /foo.php HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 (.NET CLR 3.5.30729)
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://localhost/test.php
Content-Type: application/x-www-form-urlencoded
Content-Length: 43

first_name=John&last_name=Doe&action=Submit

Tutorial on HTTP headers:

https://code.tutsplus.com/tutorials/http-headers-for-dummies--net-8039


Iterating an array of relays Bear with me as I'm fairly adept at C# but I am having a problem understanding how to get an array iterated.

I am writing a program to test relay boards, it will eventually have an input mechanism to select the number of relays on the board. For now, i just need to get an array iterated to move on with the code.

The biggest relay board I've seen has 16 relays, so....

#define Relay1  2  // Arduino Digital I/O pin numbers for UNO R3
#define Relay2  3
#define Relay3  4
#define Relay4  5
#define Relay5  7
#define Relay6  8
#define Relay7  9
#define Relay8  10
#define Relay9  11
#define Relay10  12
#define Relay11  13
#define Relay12  A0
#define Relay13  A1
#define Relay14  A2
#define Relay15  A3
#define Relay16  A4

int relays[]{ Relay1,Relay2,Relay3,Relay4,
    Relay5,Relay6,Relay7,Relay8 };
int maxRelayCount = 8;
char rx_byte = 0;

void setup()   //Initializes all variables and settings
{
  Serial.begin(9600);
 // create an input for the amount of relays on the board
//hardcoded for now

//Set pins to OFF & declare pins as OUTPUTS
 for(int i = 0; i < maxRelayCount; i++)
 {
   digitalWrite(relays[i], RELAY_OFF);
   pinMode(relays[i], OUTPUT);
   //How to convert i to a string in c++?
   //Serial.print("Relay " +[i] + " set HIGH and as OUTPUTS");
 }

 //Check that all relays are inactive at Reset
 delay(4000);

}

So there are two issues. If I remove the loop and just hard code 8 times to set HIGH and OUTPUT it works fine, but the loop does not and won't upload to the Arduino, thus the reason I believe it is wrong. Secondary question is how to convert the counter i to a string to concatenate the message

the loop does not and won't upload to the Arduino

Most likely because RELAY_OFF has never been defined anywhere. Change that to HIGH (if that is what your relays need to turn off), or define it somewhere.

Also there is no loop() function - is that just you being economical with the paste?

  Secondary question is how to convert the counter i to a string to concatenate the message.

Simple: don't.  There's no need.

Serial.print("Relay ");
Serial.print(i);
Serial.println(" set HIGH and as OUTPUT");


I want to know how to record and play radio waves? I want to make a universal remote.I have an ir receiver and transmiter. I.I can use it to control my tv and other equipment.I want to also control my dish network in the US. I checked and think that the dish uses 395mhz but i am not sure.How can i replicate a dish remote radio signal.I know it is radio signal and not ir. What part do I need for the arduino?

This is only a partial answer, but should be enough to get you started.

The parts are:

Build a receiver http://www.somerset.net/arm/fm_only_lowtech.html
Tune it to the right frequency
Use it to detect the codes sent from your remote
Build a transmitter http://makezine.com/projects/super-simple-fm-transmitter/
Tune it to the right frequency
Transmit the codes
Success!

Step 3 is probably best done with a scope - you should find someone who has one, who can operate it, because they can be damaged.


WDT & Software RESET in ESP8266 + Arduino IDE I am working on ESP8266 in Arduino IDE. I want to know how to Software RESET the ESP8266. Any sketch/example would be useful. Moreover, how to initialise WDT in ESP8266.

Kindly help!

Software reset in ESP8266 is achieved using ESP.reset()

as per WDT, the other answer has info on that, i.e. software WDT is cleared using yield() - hardware WDT is not accessible through software


Avoiding false rising and falling edge when using demultiplexer I have 8 sets of 8 push buttons. There is a Teensy and a demultiplexer. The demultiplexer has 8 outputs. When an output is selected it is pulled low. Each output is connected to a group of 8 push buttons. The 8 push buttons are then connected to 8 pullup inputs on the Teensy.

Each group of 8 push buttons is connected to a unique demultiplexer output, but all the push buttons are connected to the same 8 inputs on the Teensy. That is, push button #1 in group 1 shares a Teensy input with push button #1 in group 2. The push buttons are isolated from each other with diodes.

I'm using bounce.h for debouncing. It looks for rising and falling edges.

The problem is this:

Push button #1 in group #1 is pressed, pulling that input low, causing a falling edge to be detected. This is good.
The demultiplexer shifts to group #2, where the #1 button hasn't been pressed, and thus is high.
Because both #1 buttons in group #1 and #2 share the same input line, the Teensy sees this change as a rising edge. This is undesired.

What is the better approach to this?

Thanks,

Dan

To do multiplexing with bounce.h you will need one bounce object per button. That's 64 bounce objects for an 8x8 matrix.

Then you only want to update the bounce objects for the group you currently have active.

That is:

Switch to group 1.
Update objects 1-8
Switch to group 2
Update objects 9-16
... etc ...

You need one object per button so that the internal data can track the state of that specific button, and you only update the 8 objects for the currently selected group otherwise the objects that aren't associated with that group will get confused by incorrect data.


No data sent over serial port in linux c++ TL;DR - I am attempting serial communication with Arduino with code that I found here and nothing gets sent over (Arduino programmed to respond, and I checked that it does with its serial monitor)

Hi there,
I was looking for a way to send information over to an Arduino Mega (2560) unit over linux serial port by C++.

I came across the following solution: Solution
I'm using this guy's code for write (I'm able to read data from the arduino) and use the same parameters (they work, as I'm able to receive data from the Ardunio).
I programmed my Arduino to send "Hi" over serial whenever it sees at least 1 bit of information, and checked it worked through the Arduino IDE Serial Monitor.

Yet when running the C++ code, the arduino doesn't respond. Do anyone might have idea why?

Full disclosure - I inserted @Lunatic999's code to a class so I can make an instance of it for my needs of the code.

fd = open(portNameC, O_RDWR | O_NOCTTY | O_SYNC); //open port ("opens file")

Serial Parameters:

struct termios tty;
struct termios tty_old;
memset (&tty, 0, sizeof tty);

/* Error Handling */
if ( tcgetattr ( fd, &tty ) != 0 ) {
   std::cout << "Error " << errno << " from tcgetattr: " << strerror(errno) << std::endl;
}

/* Save old tty parameters */
tty_old = tty;

/* Set Baud Rate */
cfsetospeed (&tty, (speed_t)B9600);
cfsetispeed (&tty, (speed_t)B9600);

/* Setting other Port Stuff */
tty.c_cflag     &=  ~PARENB;            // Make 8n1
tty.c_cflag     &=  ~CSTOPB;
tty.c_cflag     &=  ~CSIZE;
tty.c_cflag     |=  CS8;

tty.c_cflag     &=  ~CRTSCTS;           // no flow control
tty.c_cc[VMIN]   =  1;                  // read doesn't block
tty.c_cc[VTIME]  =  5;                  // 0.5 seconds read timeout
tty.c_cflag     |=  CREAD | CLOCAL;     // turn on READ & ignore ctrl lines

/* Make raw */
cfmakeraw(&tty);

/* Flush Port, then applies attributes */
tcflush( fd, TCIFLUSH );
if ( tcsetattr ( fd, TCSANOW, &tty ) != 0) {
   std::cout << "Error " << errno << " from tcsetattr" << std::endl;
}

Write (this code I put inside a function which I call)

unsigned char cmd[] = "INIT \r";
int n_written = 0,
    spot = 0;

do {
    n_written = write( fd, &cmd[spot], 1 );
    spot += n_written;
} while (cmd[spot-1] != '\r' && n_written > 0);

Arduino code:

bool dataRecieved = false;
int ledpin = 13;

void setup() {
pinMode(ledpin, OUTPUT);
digitalWrite(ledpin, HIGH);
Serial.begin(19200);
}

void loop() {
  while(!dataRecieved)
  {
   digitalWrite(ledpin,HIGH);
   if (Serial.available() > 0)
   {
     dataRecieved = true;
   }
  }
  digitalWrite(ledpin,LOW);
  delay(1000);
  digitalWrite(ledpin,HIGH);
  delay(1000);
  Serial.println("hi");
}

The Arduino resets the moment you open the serial port.  Once reset the bootloader executes, which consumes (and discards since it's invalid) any serial data for a second or so before your sketch runs.

Because of this anything you send immediately after opening the serial port is ignored.

There are two commonly accepted "fixes" for this:

Delay for a pre-defined period after opening the serial port, and
Have the Arduino send a "READY" signal before doing anything else which your program waits for before sending.


How do I know if a board fits my requirements? I'm new to Arduino and I saw on their website that there are many different kinds of boards.
What are the differences, or to be more specific, how would I know which board meets my requirements? I understand that the shields can be connected to the board, but are some boards that do not support certain shields?

Another thing, is it possible to connect external sensors to an Arduino board or there are special sensors that can communicate with the board? I want to use weight sensors.

Things to consider when picking an Arduino board:

Do I want native keyboard/mouse support? If yes: you'll need the Leonardo (or it's breadboard mountable equivalent) or the TRE (not released, dual MCU board).
Do I want a small form factor and/or have it breadboard mountable? If yes, choose a board like the Mini/Micro/Nano/etc.

If you want to make it even smaller, either get a board without USB built in or try using an ATTiny

Am I computing large numbers with it? If yes: use the Due, Galileo, or TRE (not released yet)
Do I want video/audio? If yes: TRE is the only way to go as of now (but it's not released yet).
Do I need a USB host (and not want to have an external shield)?  If yes, use the Mega ADK (limited support), Yun, TRE (again, not released yet), or Galileo.
Do I need WiFi/ethernet built in? If yes; use the Yun, TRE (still, not released yet), Ethernet board, or Galileo.
How many pins do I need (and how many of each type)?

Digital: simple ON or OFF. Use these for buttons, simple lights, some communication, etc.

Stay away from the Due if you don't want to mess with 3.3V logic. Most other boards are 5V. You can work around this with either voltage dividers (doesn't always work) or level shifters. As far as I know, you can't really do much if a sensor provides max 5V; level shifters AFAIK only work with digital signals.

UART Pins: these are the pins that you can use the serial library on. (Note: this doesn't include the software-serial library). One of these on most boards is connected to a USB chip.
SPI Pins: These are pins which are used by a form of communication (like on the Ethernet shield).
Inturupt Pins: These can trigger an event when the signal getting sent to the board changes. There are a couple of different settings, but this can be used for near-instant response time when low latency is critical.
PWM Pins: pins that go on and off to simulate a lower voltage. It does this by turning it on and off very rapidly. This is used often for dimming LEDs and controling the speed of a motor.
Analog pins: pins that can read a voltage and convert it into a number.

The Arduino Due has a much higher precision rate, as it has more possible values and it has less voltage, thus much more accuracy.

All of these types of pins can act as a digital pin. All of these, except the analog pins, are under the "digital pin" section of your Arduino board. I didn't go into the technical aspects of the pins; I explained then in the simplest way I could.

I left a lot of boards out of this list, but this should give you some things to think about when choosing a board. There's a lot of weird quirks with this list, so it's incomplete, especially with the types of pins. You'll just have to do research and figure out what you need and if a board can meet your needs. Just make sure to not plan two things on the same pin, especially when mixing different shields and sensors! Shields do take up pins.

Shields: they are pretty much compatible with every board except for if the board is 3.3V (newer shields can adapt automatically) OR if it's a breadboard mounted board, like the Nano. There are ways to work around this problem, but it's very difficult.


Arduino and USB power, what to choose I am a beginner at Arduino. I want to power the Arduino through the USB cable that is usually plugged in the USB of the laptop, but plugged in the wall instead of the laptop.

Here are my questions:

Can I use a phone charger that has a USB (in which the end of the USB
cable will go instead of the USB of the PC)?
What should I look for written on the charger so it is best
compatible?
Is it ok to be done that way?
Will it be the same as means of power like when it is plugged in the
PC (for example when later on I connect LCD display, diodes, etc.)?

I did my research, but it got confusing, so I wanted to ask my own question. Thanks in advance.

Yes, you can power the Arduino using a USB phone charger.

The Arduino Uno draws less than 100mA when connected by itself. So ideally you would want the USB phone charger to provide at least 100mA. All of the USB chargers I have come across to date provide more than 400mA. Most of the modern USB chargers provide upwards of 1A for fast charging of your phone.

A USB(2) port of a laptop can provide up to 700mA to the Arduino (500mA continuous).

In terms of the overall current draw, it really depends on what you have connected to the Arduino. LEDs generally draw 20mA or less per LED. Some screens can draw anything from <100mA to a couple of amps. Most of the screens I have come across draw less than 1A. It really depends on the devices you want to connect.

For the most part, a USB charger will be sufficient.


Should a delay be expected to cause deadlock? I have made a simple program using the int main() {} function. It has a delay in it. It is evident the code before the delay is running, but the delay never seems to time out and let the next instructions through. Is this by design?

If I rename the method and call it exactly once from the loop() {} function though, it does work.

Edit:

The code borrowed the 'main()' function and I suppose redefined it:

int main() {
    Forward();
    delay(3000);
    Reverse();
}

void Forward() {
    //...
}

void Reverse() {
    //...
}

I can see this redefinition of main() could cause some serious issues based on the answer below.

You don't seem to use standard Arduino stuff since you defined your own main() which is normally avoided when programming Arduino.

If you take a look at Arduino provided main() (in hardware/cores/arduino/main.cpp), you'll see how it is defined:

#include <Arduino.h>

int main(void)
{
    init();

#if defined(USBCON)
    USBDevice.attach();
#endif

    setup();

    for (;;) {
        loop();
        if (serialEventRun) serialEventRun();
    }

    return 0;
}

Did you notice the init() function call at the beginning?

Its code is defined in hardware/cores/arduino/wiring.c; what it does is setup all timers used by Arduino functions, in particular a timer that is needed by delay().

In the same wiring.c file, you can also find the definition of delay():

void delay(unsigned long ms)
{
    uint16_t start = (uint16_t)micros();

    while (ms > 0) {
        if (((uint16_t)micros() - start) >= 1000) {
            ms--;
            start += 1000;
        }
    }
}

This will turn into an infinite loop if micros() always return the same value, and it does so if init() has never been called before.

This is what happens with your code.


File.read() always returns -1 I'm trying to print a txt file from an SD card to a SSD1306 using the u8x8 library.
Here's the current code:
#include <SD.h>

#include <Arduino.h>
#include <U8x8lib.h>

#ifdef U8X8_HAVE_HW_SPI
#include <SPI.h>
#endif
#ifdef U8X8_HAVE_HW_I2C
#include <Wire.h>
#endif

  U8X8_SSD1306_128X64_NONAME_HW_I2C u8x8(/* reset=*/ U8X8_PIN_NONE);

/*
  This example will probably not work with the SSD1606, because of the
  internal buffer swapping
*/
#define maxChar  128
#define rows 8
#define cols 16

File myFile;
int x = 0;
int y = 0;
char c;

void setup()
{
  /*Serial.begin(9600);
  Serial.print("Initializing SD... ");
  if (!SD.begin(10)) {
    Serial.println("initialization failed!");
    while (1);
  }
  Serial.println("initialization done.");*/

  u8x8.begin();
  delay(500);
  u8x8.setFont(u8x8_font_amstrad_cpc_extended_f);

  myFile = SD.open("target.txt", FILE_READ);
  u8x8.clear();
  u8x8.print("ciao");
  u8x8.print(myFile.read());
  delay(2000);
  printNewSet();
}
void loop()
{

}

void printNewSet()
{
  u8x8.clear();
  x = 0;
  y = 0;
  while (myFile.available() && y<rows)
  {
    c = (char) myFile.read();
    if (c == '\n') c = 'a';
    u8x8.print(c);
    stepCoords();
  }
}

void stepCoords()
{
  x++;
  if (x >= cols) newLine();
}
void newLine()
{
  u8x8.print('\n');
  x = 0;
  y++;
}

The function printNewSet() is supposed to print a batch of characters until either the file ends or the display limit is reached.
The file displayed correctly until i switched from while(myFile.available()) u8x8.print( (char) myFile.read()); to printNewSet(), at which point myFile.read() only returns -1 and myFile.available() is always false.
What is going wrong?
EDIT: While debugging i discovered that myFile fails to be initialized. Am I running out of memory?

I had accidentally commented out the SD initialization along with the serial initialization. After uncommenting it it works correctly


MKR GSM 1400 Works only when connected to computer My MKR GSM 1400 works fine when connected to a computer (powered USB) and after opening a serial connection to it.  It does not when I plug it into a power supply. My power supply is a 5V 3A with a USB adapter.

If your sketch on an Arduino with native USB doesn't run if not connected to USB, always first check if you didn't forget the while (!Serial) {} in setup().


Connect my arduino with ethernet shield to new router I just changed the router for my webserver and I'm having trouble to connect my arduino with the LAN.
I'm using a router which uses Zhone technology, and I've been working with NetGear for a while without problems.
The procedure I've done so far is:

Connect the arduino with the ethernet and run the DhcpAdressPrinter example
Once I got the adress, in my case 192.168.1.125 I run the WebServer example, using the IP assigned by the DHCP.
In the serial monitor, I see it has started the program with the correct IP.

Problem: WHEN PUTTING THE IP INTO A BROWSER, NOTHING CHARGES

More info:

In my router page (192.168.1.1) I can see that each ethernet port has
assigned a MAC adress, I don't really understand why.
I also can see that the arduino has been successfully added to the DHCP with the IP assigned and the MAC adress that I wrote on the code
Finally, add that I've read in another website that sometimes the problem is due to the fact that the router just let the access to some specific MAC adress, but i'm not sure.

Any help will be apreciated! Thanks!

Finally, I was capable to solve it by just creating a port forwarding with the IP that was assigned by the DCHP.
It looks like my router for security reasons don't let you comunicate with other devices within the lan, so it's necessary to open a port and access the device through it!


Why is my variable not getting updated? I have the following snippet of code:

const unsigned long fiveMinutes = 5 * 60 * 1000UL;
unsigned long lastCheck = 0 - fiveMinutes;
unsigned long now = 0;

void loop() {
  now = millis();
  if ( now - lastCheck >= fiveMinutes ) {
    doStuff();
    lastCheck = now;
  }
}

The doStuff() routine is getting called on every loop() iteration, because the value of lastCheck isn't getting updated. I thought Icould update global variables inside subroutines, but the behavior I'm seeing says otherwise. What am I doing wrong? (doStuff() is defined and works correctly, I'm not posting it here for brevity.)

I modified your code to produce a working example:

const unsigned long fiveMinutes = 20 * 1000UL;
unsigned long lastCheck = 0 - fiveMinutes;
unsigned long now = 0;

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  Serial.println ("Starting.");
  Serial.println (fiveMinutes);
  }  // end of setup

void doStuff ()
  {
  Serial.println ("Doing stuff");
  }

void loop() {
  now = millis();
  if ( now - lastCheck >= fiveMinutes ) {
    doStuff();
    lastCheck = now;
  }
}

I reduced the interval to 20 seconds, and Ignacio Vazquez-Abrams is correct about the initial test, however apart from that, I see "Doing stuff" every 20 seconds.

  I thought I could update global variables inside subroutines ...

You can.

Are you sure you didn't have:

void loop() {
  unsigned long lastCheck;
...


Problem sending string with Python to Arduino through serial port I want to send string 50 to Arduino through serial port, the Arduino UNO seems it communicates with port COM25 but it doesnt receive the string properly:

import serial # if you have not already done so

ser = serial.Serial('COM25')
ser.baudrate = 9600
ser.write(b'50')
ser.close()

Btw Arduino code is correct I checked it with other serial com programs. How can I fix the above code?

The AVR Arduinos (Uno, Nano, Mega) have auto-reset function. At opening of USB connection the circuit around USB resets the MCU. After reset the bootloader waits a second for a new upload. If the upload doesn't happen the bootloader starts the current sketch.

The serial.Serial() command in python opens the USB connection. With that the Arduino is reset and waits in bootloader while you send the data. The data doesn't arrive in your sketch. Add a two seconds wait time after Python's serial.Serial().


Clamping 9-volt input to 8-volt? Have a DFRobot Arduino Pro Mini.

Seems odd to me, but according to their specs the voltage regulator on board cannot handle more than 8-volt input. I can find no documentation, or have they answered me concerning what specific regulator they use on the board.

I would like to be able to run this board from a 9-volt battery. What is the best / most eloquent way to do this, keeping the smallest component footprint for a home etched board ?

An additional regulator ?? Could a diode clamp the voltage down ?

Many thanks in advance.

I would make sure first that their claim ofb8v max is right. Look up the datasheet for the regulator and go from there.

If you have to go with 8v max, put a diode or two, or an led in serial should work most of the time.

For those where such an approach doesn't work, wire up an external regulator.


Is there a constant for the Maximum Unsigned Long value in an Arduino compiler? I am writing a timer function that uses the micros() function which generates a unsigned long value.  To compensate for a roll over condition, I would like to use the maximum value for that variable type.  I have a number, 4,294,967,295, but was expecting that to be a constant somewhere.

Is there a MAX_UNSIGNED_LONG constant in the Arduino compiler files somewhere?

I have tried that name and know it probably isn't that.  Still poking around.

Various limits.h files in the avr-gcc hierarchy define ULONG_MAX, which may be the value you want.  For example, on my system such files have paths ending with hardware/tools/avr/lib/gcc/avr/4.8.1/include-fixed/limits.h or with hardware/tools/avr/lib/gcc/avr/4.8.1/install-tools/include/limits.h and contain definitions like the following.

/* Maximum value an `unsigned long int' can hold.  (Minimum is 0).  */
#undef ULONG_MAX
#define ULONG_MAX (LONG_MAX * 2UL + 1UL)

Note, LONG_MAX also is defined in limits.h.

Note, arithmetic done in a form like

timeDelta = micros() - prevTime;

will be correct (regardless of whether micros() overflowed) for elapsed times up to 2³² microseconds, or about 4295 seconds.


MPU 6050 stuck on same values I'm having a problem with my MPU6050. I'm using PID to speed up a motor with the MPU values. What could the problem be?

Here is a link to a previous question that I asked concerning a problem with pid: PID not working correctly

These are the values that I'm getting, which repeat forever. The values are:

motor speed;
the value that changes the motor speed;
the MPU value;
the change that PID made.

0.00
0
10900
4800

0.00
0
10900
4800

Here is the code itself.

int16_t ax, ay, az;

double Setpoint, Input, Output;
//Specify the links and initial tuning parameters
double Kp=2, Ki=5, Kd=1;
PID myPID(&Input, &Output, &Setpoint, Kp,Ki,Kd, DIRECT);

void setup() {
 Input = analogRead(ax);
  Setpoint = 100;
  //turn the PID on
   myPID.SetMode(AUTOMATIC);
}

void loop() {
 accelgyro.getAcceleration(&ax, &ay, &az);
  int a=ax+10900;
//Here I set the used variable to around 0. ax is actually around -10900
//This is always true, this won't be in the final code. This is just making        it work.

if(1) {
 int val;
  val = map(a, -1300, 1300, 0, 1023);
   Input = val;
    myPID.Compute();
     Serial.println(Output);

digitalWrite(motorPin2, HIGH);
Serial.print("\t");
Serial.println(ax);
Serial.print("\t");
Serial.println(a);
Serial.print("\t");
Serial.println(val);
     }
}

Let's deconstruct this down to a simple example which we can test without the MPU6050:

#include <PID_v1.h>

double Setpoint, Input, Output;
//Specify the links and initial tuning parameters
double Kp = 2, Ki = 5, Kd = 1;
PID myPID(&Input, &Output, &Setpoint, Kp, Ki, Kd, DIRECT);

void setup() {
  Setpoint = 100;
  //turn the PID on
  myPID.SetMode(AUTOMATIC);
  Serial.begin (115200);
  Serial.println (F("\n\nStarting\n\n"));
}

void loop() {
  int a = 0;
  int val = map(a, -1300, 1300, 0, 1023);
  Input = val;
  myPID.Compute();
  Serial.print (F("Input = "));
  Serial.println(Input);
  Serial.print (F("Setpoint = "));
  Serial.println(Setpoint);
  Serial.print (F("Output = "));
  Serial.println(Output);
  Serial.println();
  delay (300);
}

Output:

Starting

Input = 511.00
Setpoint = 100.00
Output = 0.00

Input = 511.00
Setpoint = 100.00
Output = 0.00

Input = 511.00
Setpoint = 100.00
Output = 0.00

Input = 511.00
Setpoint = 100.00
Output = 0.00

Indeed it isn't changing. Let's analyze why:

The input is 511
The setpoint is 100
Therefore the error is 100 - 511 = -411
Disregarding (for the moment) the integral and differential terms, you have a proportional term of 2 (Kp) so the algorithm tries to output 2 * Error
Output would be 2 * -411 = -822
However the maximum and minimum limits default to 0 to 255, and thus the output is clamped to 0.
The algorithm outputs 0.
And the next time it does the same thing.

There is a function SetOutputLimits which can be used to change the default minimum and maximum output values.

The Ki and Kd values might eventually have an impact, but you won't notice anything with the output clamped to zero.

For example, adding this line in setup gives different results:

  myPID.SetOutputLimits (-5000, 5000);

Result:

Starting

Input = 511.00
Setpoint = 100.00
Output = -5000.00

Input = 511.00
Setpoint = 100.00
Output = -1233.00

Input = 511.00
Setpoint = 100.00
Output = -1438.50

Input = 511.00
Setpoint = 100.00
Output = -1644.00

Input = 511.00
Setpoint = 100.00
Output = -1849.50

Input = 511.00
Setpoint = 100.00
Output = -2055.00

Input = 511.00
Setpoint = 100.00
Output = -2260.50

Input = 511.00
Setpoint = 100.00
Output = -2466.00

Whether they are valid limits depend on what you are attempting to do exactly.


How to delegate code compilation to a remote machine? Sometime I write Arduino code on a slow Windows laptop that I use for controlling hardware projects and 3D printing.

My main Windows computer and also my Linux home server are located somewhere else but are much faster and I would like to use those for compilation.

Remote Desktop or equivalent are not practical due to different screen resolutions. Also, my main Windows machine is not always on, only the server is, but it has no GUI installed.

The sources are already located on a shared network folder and I use an external editor for the code. Arduino IDE just does compilation and sometimes upload (which often I could do via OTA).

How to delegate compilation of Arduino projects to a remote machine?

If you don't have a GUI, you can still compile and upload sketches by using the Arduino CLI. With it you can do most things, that you can do with the Arduino IDE. I'm using this myself to upload new code to a Nano, that is connected to a Raspberry Pi in a project in use.

You can connect via ssh to the remote server and let it compile/upload the sketch. I wrote a simple bash script to first copy the source to the server (since you are using a network share, this is not necessary for you) and invoke the compilation and upload.

Note: Before you can actually compile with the Arduino CLI, you have to download the correct core for your chip. This is described in the README of the linked github project.


Arduino String: use a non-null-terminated char array? I'm using a library that takes a String as it's parameter (https://github.com/gmag11/painlessMesh)

I want to pass char arrays that is binary (UTF-8) data that also contains null-bytes (0x00). Right now, the resulting String is cut off at the first null-byte as expected. I know the full length of the char array, is it possible to construct an Arduino String while passing the arbitrary length, so that the full String also contains the null-bytes including the data that follows after, up until the pre-set length?

I had this problem before and then I solved it by converting the UTF-8 data to hex and then add a null-byte. I was hoping there is a more elegant way, since this forces me to double the data-size.

Thanks!

Assuming you are talking about the function

bool painlessMesh::sendBroadcast( String &msg, bool includeSelf = false)

Then you'll see that ultimately, the library passes msg into the function buildMeshPackage where it constructs a JSON message (see here)

String ICACHE_FLASH_ATTR painlessMesh::buildMeshPackage(uint32_t destId, uint32_t fromId, meshPackageType type, String &msg) {
    debugMsg(GENERAL, "In buildMeshPackage(): msg=%s\n", msg.c_str());

    DynamicJsonBuffer jsonBuffer;
    JsonObject& root = jsonBuffer.createObject();
    root["dest"] = destId;
    //root["from"] = _nodeId;
    root["from"] = fromId;
    root["type"] = (uint8_t)type;

    switch (type) {
    case NODE_SYNC_REQUEST:
    case NODE_SYNC_REPLY:
    {
        JsonArray& subs = jsonBuffer.parseArray(msg);
        if (!subs.success()) {
            debugMsg(GENERAL, "buildMeshPackage(): subs = jsonBuffer.parseArray( msg ) failed!");
        }
        root["subs"] = subs;
        break;
    }
    case TIME_SYNC:
        root["msg"] = jsonBuffer.parseObject(msg);
        break;
    default:
        root["msg"] = msg;
    }

    String ret;
    root.printTo(ret);
    return ret;
}

Even if you did construct a String with null terminators in it, the moment it gets put into the JSON string it destroys everything. JSON by default doesn't support binary data strings (reference).

So, the library is a problem because it happily passes data as JSON messages, and that's bad if you want binary data transported. You could use Base64 or the more efficient http://base91.sourceforge.net/ encoding though to mitigate this a little bit, or search for a different lib.


Idenitifying pins in my code. which pin is which? I'm new to arduino and knnow nothing about electronics.
How do I idenitify which pin is which in the coding?
eg- I have a pin on my esp8266 "D3"... how would I reference that in the code?

If you select the right board in Tools menu, you can use constants corresponding to labels.

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


LM393 Speed sensor - Counting pulses I'm trying to calculate de rotation speed of a dc motor.

I'm using the sensor shown in the picture and a slotted disk attached to the motor. The results I was getting made no sense and after several tests I realised the following:

Most of the times I manually blocked or unblocked the sensor, two pulses were counted. That would mean that for each tooth of the slotted disk, up to four pulses were counted instead of one.

Bellow is a test code. I count pulses on the interrupt handler and reset the counter when calculating the motor speed.

Am I doing something wrong or is the sensor suffering from bouncing signals?

int encoderCounter = 0;
int encoderDiscSlots = 21;

int encoderPin = 19;

void encoderIncrementISR()
{
  encoderCounter++;
}

double calculateMotorSpeed(int interval)
{
  Serial.print("enc ");
  Serial.println(encoderCounter);
  double rpm = (encoderCounter*1.0/encoderDiscSlots)*60000/interval;

  encoderCounter = 0;
  return rpm;
}

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

  pinMode(encoderPin, INPUT_PULLUP);

  attachInterrupt(digitalPinToInterrupt(encoderPin), encoderIncrementISR, RISING);
}

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

  delay(1000);
  double rpm = calculateMotorSpeed(1000);
  Serial.print("rpm ");
  Serial.println(rpm);
}

The sensor uses the LM393 IC from TI, a spec sheet can be found here

I've done some more search on the interwebs and found someone (in Spanish) describing the same problem. That person owns an oscilloscope and could confirm that there is some bouncing on the data signal both going up and down.

The hardware solution presented is to place a 100 nF capacitor between the signal pin and ground.

I've tried it and it works.


Is there something I can use to control Arduinos easily over Ethernet with .NET? I'm wondering if there's anything out there that maybe works pretty similarly to Firmata, runs on Unos or Megas, and can be controlled over Ethernet. I am writing a home automation system with .NET, and I see some options for supporting Firmata with .NET, but I want to be able to connect my devices over Ethernet.

I don't use .net but I have done this using php website to control a door lock over ethernet.

My solution was to use the ethernet to recieve commands and be able to use them on the arduino through http calls. And when it was done send a http call back to the server with some data. I was doing a door lock program for example. Please ignore anything talking about doors, locking, unlocking, or other requirements to certain calls, I am just providing examples about how it COULD be used, not that you need to include my door lock code in your project to get it to work.

As far as how that works out with .net that's up to you, however I can give you a hand getting your messages back and forth.

first you want to create the ethernet connection to your router. put this in your header section.

#include <UIPEthernet.h>
// assign a MAC address for the ethernet controller.
// fill in your address here:
byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};

// fill in an available IP address on your network here,
// for manual configuration:
IPAddress ip(127, 0, 0, 1);

// initialize the library instance:
EthernetClient client;

char server[] = "www.example.com";
//IPAddress server(127,0,0,1);  // numeric IP for www.example.com (no DNS)

int waitTime = 3L;

unsigned long lastConnectionTime = 0;             // last time you connected to the server, in milliseconds
const unsigned long postingInterval = waitTime * 1000L; // delay between updates, in milliseconds
// the "L" is needed to use long type numbers

throw this in your main loop so it doesn't constantly make http requests spamming a server.

// if ten seconds have passed since your last connection,
// then connect again and send data:
if (millis() - lastConnectionTime > postingInterval || buttonState == 0) {
  httpRequest();
}

Create a method to handle httpRequest because shoving everything under the main is kinda sloppy.

Alright so there will be quite a bit here because http headers are kinda lengthy.

// this method makes a HTTP connection to the server:
void httpRequest() {
  // close any connection before send a new request.
  // This will free the socket on the WiFi shield
  client.stop();
  // if there's a successful connection:
  if (client.connect(server, 80)) {
    Serial.println("connecting...");
    // send the HTTP PUT request:
  Serial.println("String is " + readString);
  if(readString == "Ready" || readString == ""){
    client.println("GET /command.txt HTTP/1.1");
    where = "web";
    waitTime = 5L;
  }
  else{
    // here is the basic format of sending a get command
    //this specific request is so that I can tell where the command came from. I had a web client / mobile app that could control the door AND you could also control it from a physical buttom. The door would have to reply either way to the web server (READ: .net application) in order to have the correct status always show up on the web end.

    client.print("GET /update.php?where=Arduino&command=Ready&status=");
    if(readString == "Reset"){
      client.print("Reset");
    }
    else if(isLocked){
      client.print("Locked");
    }
    else{
      client.print("Unlocked");
    }
    client.println(" HTTP/1.1");
    waitTime = 1L;
  }
  client.println("Host: www.example.com");
  client.println("User-Agent: arduino-ethernet");
  client.println("Connection: close");
  client.println();

    // note the time that the connection was made:
    lastConnectionTime = millis();
  }
  else {
    // if you couldn't make a connection:
    Serial.println("connection failed");
  }
}

TL;DR if you wanna use ethernet you need to use all of ethernet.
Start by creating your connection to the router statically (watch for conflicts).

Then create a method of watching for incoming data or waiting for a command if there isn't one. (server call).

Then create A FULL HTTP REQUEST in order to pass your request through. Shorting any parts of this last part and you will either end up with bad request errors or will simply fail.

Let me know if you need anything else or if this was useful to you!


I would like to know the ATMEGA wiring to Arduino I would like to know which pins are connected to the output of the Arduino.

For example:

PC6 is digital 12
PB5 is analog 13
etc...

Image searching for the term "arduino uno pinout" reveals a better pinout diagram.


Reading analog signal from digital pin #6 Is it possible to use digital pin 6 (PD6_PCINT22/AIN0) to read an analog voltage with analogRead()?

According to the ATMega datasheet, this should be possible.

If yes how is it done ? (pin configuration)

That is not possible. AIN0 is an input to the analog comparator, not the analog-to-digital converter. Only ADC0 through ADC8 (connected to the internal temperature sensor), the 1.1V reference, and ground can be connected to the ADC.


Receiving serial data in groups instead of individually I have two different Vernier science probes connected to a Vernier shield that connects to an Arduino Uno. I have the Uno connected to an ESP8266 via the Tx.

Here is my Uno code:

String sensor1 ="Conductivity Probe ";
float interceptSensor1 = 0.0;
float slopeSensor1 = 960;
String sensor2 ="pH Probe ";
float interceptSensor2 = 13.720;
float slopeSensor2 = -3.838;
int timeBetweenReadings = 2000; // in ms

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

void loop() {
  float analogSensor1 = analogRead(A0);
  float voltageSensor1 = analogSensor1 / 1023 * 5.0;
  // convert from count to raw voltage
  float sensor1Reading= interceptSensor1 + voltageSensor1 * slopeSensor1;
  //converts voltage to sensor reading
  String sensor1Output = sensor1 + sensor1Reading;
  Serial.println(sensor1Output);
  delay(timeBetweenReadings);
  // delay in between reads for stability
  float analogSensor2 = analogRead(A1);
  float voltageSensor2 = analogSensor2 / 1023 * 5.0;
  // convert from count to raw voltage
  float sensor2Reading= interceptSensor2 + voltageSensor2 * slopeSensor2; //converts voltage to sensor reading
  String sensor2Output = sensor2 + sensor2Reading;
  Serial.println(sensor2Output);
  delay(timeBetweenReadings);
  // delay in between reads for stability
}

On the serial monitor every two seconds I get one line of output and it alternates back and forth between the sensors:

Conductivity Probe 807.04

pH Probe 4.12

Conductivity Probe 802.35

pH Probe 4.13

Conductivity Probe 802.35

pH Probe 4.12

Since I've only got a simple serial line to work with but I need to send multiple, different types of data to the ESP8266, my strategy is to send one line (ex. Conductivity Probe 807.04) and use logic on the ESP8226 to parse the string, isolate the float number (807.04), and  use Conductivity Probe to determine how that number gets further used (in my case, to publish to an MQTT feed called ElectroConductivity).

The Tx of the Uno + sensors is wired to the Rx of the ESP8266, and here's the ESP8266 code:

  while (Serial.available() == 0) {
  }
  sensorReading = Serial.readString();
  Serial.println(sensorReading);

The data comes in large groups instead of line by line:

pH Probe 4.12
Conductivity Probe 807.04
pH Probe 4.12
Conductivity Probe 807.04

I'm new to serial comms and Arduino in general. I'm guessing that there's an issue with how serial is read by the ESP8266.

EDIT

When I use sensorReading = Serial.readStringUntil('\n'); instead my output looks like this:

Conductivity PrpH Probe 4.12

Conductivity Probe 816.42

pH Probe 4.12

Conductivity Probe 825.8Conductivity Probe 821.11

Conductivity Probe 821.11

pH Probe pH Probe 4.12

ConductivitypH Probe 4.12

readString() will keep reading until it times out. Instead try readStringUntil('\n') to read until you get a new line character.


Interleave disassembly + source with avr-objdump I have a C program for the attiny85, that I want to disassemble and display with interleaved source code.

Here's my program:
test.c

#include <avr/io.h>
int main() {
    for(int i=0; i<100; i++) {
        PORTB=i;
    }
}

Here's how I compile it: avr-gcc -g -O0 -mmcu=attiny85 -o test.elf test.c

Finally, I generate the disassembly with interleaved source-code with the command: avr-objdump -S -D test.elf

The disassembly of the text section shows the following disassembly without interleaved source code:

00000030 <main>:
  30:   cf 93           push    r28
  32:   df 93           push    r29
  34:   00 d0           rcall   .+0             ; 0x36 <main+0x6>
  36:   cd b7           in      r28, 0x3d       ; 61
  38:   de b7           in      r29, 0x3e       ; 62
  3a:   1a 82           std     Y+2, r1 ; 0x02
  3c:   19 82           std     Y+1, r1 ; 0x01
  3e:   0a c0           rjmp    .+20            ; 0x54 <__SREG__+0x15>
  40:   88 e3           ldi     r24, 0x38       ; 56
  42:   90 e0           ldi     r25, 0x00       ; 0
  44:   29 81           ldd     r18, Y+1        ; 0x01
  46:   fc 01           movw    r30, r24
  48:   20 83           st      Z, r18
  4a:   89 81           ldd     r24, Y+1        ; 0x01
  4c:   9a 81           ldd     r25, Y+2        ; 0x02
  4e:   01 96           adiw    r24, 0x01       ; 1
  50:   9a 83           std     Y+2, r25        ; 0x02
  52:   89 83           std     Y+1, r24        ; 0x01
  54:   89 81           ldd     r24, Y+1        ; 0x01
  56:   9a 81           ldd     r25, Y+2        ; 0x02
  58:   84 36           cpi     r24, 0x64       ; 100
  5a:   91 05           cpc     r25, r1
  5c:   8c f3           brlt    .-30            ; 0x40 <__SREG__+0x1>
  5e:   80 e0           ldi     r24, 0x00       ; 0
  60:   90 e0           ldi     r25, 0x00       ; 0
  62:   0f 90           pop     r0
  64:   0f 90           pop     r0
  66:   df 91           pop     r29
  68:   cf 91           pop     r28
  6a:   08 95           ret

The disassembly makes somewhat sense, only that I miss the interleaved source code.

Interestingly enough, the output also includes a stab section, where I also find the main segment disassembled:

#include <avr/io.h>

int main() {
  30:   20 00           .word   0x0020  ; ????
  32:   00 00           nop
  34:   80 00           .word   0x0080  ; ????
  36:   00 00           nop
  38:   00 00           nop
    for(int i=0; i<100; i++) {
  3a:   00 00           nop
  3c:   40 00           .word   0x0040  ; ????
  3e:   00 00           nop
        PORTB=i;
  40:   80 00           .word   0x0080  ; ????
  42:   00 00           nop
  44:   00 00           nop
  46:   00 00           nop
  48:   5a 00           .word   0x005a  ; ????
    for(int i=0; i<100; i++) {
  4a:   00 00           nop
  4c:   80 00           .word   0x0080  ; ????
  4e:   00 00           nop
  50:   00 00           nop
  52:   00 00           nop
  54:   91 00           .word   0x0091  ; ????
  56:   00 00           nop
  58:   80 00           .word   0x0080  ; ????
  5a:   00 00           nop
  5c:   00 00           nop
  5e:   00 00           nop
  60:   b7 00           .word   0x00b7  ; ????
    }

}

Now the output includes source code, but the disassembly is wrong.

How do I get an output were both is correct: the disassembled instructions and the interleaved source-code?

(avr-gcc (GCC) 9.3.0. Interleave Assembly and Source for avr-objdump does not seem to have the problem, although he's using the same compiler flags...)

The .stabs section contains debugging info, not actual code. There is no
point in trying to “disassemble” it. The -D option of avr-objdump
means “disassemble everything, whether or not you believe it's machine
code”. Not what you want. For your purpose, -S should be enough.

I do not know why your main() is displayed without source code. I
tried your exact same program with the exact same commands and I do see
the source interleaved with the assembly. I am using avr-gcc 5.4.0 and
avr-objdump 2.26.20160125 as shipped on Ubuntu Eoan.


Cannot convert 'String' to 'uint8_t {aka unsigned char}' in initialization Hey all I am trying to convert a string into a uint8_t with the following code:

String data = "#255101987";
String tmp1 = data.substring(1, 3);

uint8_t first  = (String)tmp1;

I am getting the error of:

  cannot convert 'String' to 'uint8_t {aka unsigned char}' in initialization

Any help would be great as I thought adding (String) in front of the varible would solve the issue but it hasn't as you can tell.

uint8_t first  = atoi (tmp1.substring(1, 3).c_str ());

Or even:

String data = "#255101987";
uint8_t first  = atoi (data.substring(1, 3).c_str ());


wire.h multiple slave addresses Is it possible to use wire.h on an Arduino Uno to act as a slave for more than one address?  For example I'd like it to emulate two different devices, one at I2C address 23 and the other at address 57.

I'm either looking for a way to do this directly, or to run multiple instances (each would need a different onReceive handler).

Is it possible to use wire.h on an Arduino Uno to act as a slave for more than one address?

The quick answer is: No!

The ATmega328 2-Wire Serial Interface has a special register for the address match in slave mode. This only allows a single address to be matched.

  22.5.4   Address Match Unit

  The Address Match unit checks if received address bytes match the seven-bit address in the TWI Address
  Register (TWAR). If the TWI General  Call Recognition Enable (TWGCE)
  bit in  the TWAR is written to one, all  incoming address bits will
  also be compared against the General Call address. Upon  an address
  match, the  Control Unit is informed, allowing correct action to be
  taken. The TWI may or may not acknowledge its address,  depending on
  settings in the TWCR. The Address Match  unit is able to compare
  addresses even when the AVR  MCU is in sleep mode, enabling the MCU to
  wake up if addressed by a Master. Reference, pp. 213

On an ATtiny with USI it is actually possible to implement multiple address matching as this is controlled by software.

Last, a pure software approach could be used, i.e. implement the I2C protocol with external interrupt pin and fast pin access. See Amtel Application Note AVR154. The code for this app-note can be found on github. This could be modified to allow multiple slave addresses.

Cheers!


Can a ESP8266 and a HC-SR04 be friends? I have some existing code that I've been using with an Uno and a HC-SR04. In order to make my project less expensive, I'm trying to port everything over to a ESP8266-01.

The last hang up I've been running into is that it appears that the ESP8266 doesn't support the pulseIn function.

duration = pulseIn(echoPin, HIGH);

Any idea on how I can change the pulseIn function with interrupts or something else?

Lastly I've done a lot of searching for using a HC-SR04 with a ESP8266 and while there are a couple examples out there, I haven't seen anyone do it with Arduino code...

pulseIn() is actually a very simple function.  As long as there is a microseconds counter of some form available you can easily enough roll your own.

Also, I don't know which implementation of the ESP8266 plugin you are using, but the one I use has pulseIn available.


What is this PIND command I have a code that reads the value of a sensor and because it needs to be very fast it does not use digitalRead but a strange form of reading. In the top of the code it shows:

#define IRSENSOR PIND
int irpin = 2;

I have no idea why this PIND referes to my arduino pin 2, but it only work if my sensor is in pin 2. If I want to change to pin 9 and only change the irpin varialbe it does not work. Why?

To read the sensor I use this code:

while (IRSENSOR & (1 << irpin )) {

Have no idea why this work. Does anyone know this kind of programming with arduino?

PIND refers to the arduino's IO register for input in port D

Without arduino, one has to refer to pins by specific bits in 3 different sets of registers for each port (PIN*, DDR*, and PORT*; B,C, and D).

The arduino code makes it simpler to pick out a single pin by hiding all of this, but it does make reading a pin take much longer.

In the code, the specific pin is being selected by masking off all but the "irpin" bit in PIND, so changing irpin will pick a different bit and thus a different pin.

Pin 9 is actually bit 1 of port B, not D, so see if this works:

#define IRSENSOR PINB
int irpin = 1;

alternatly, using a reference instead of define,

volatile uint8_t& IRSENSOR = PINB;
int irpin = 1;


How to remove the sketch for the LCD and retaining the sketch for the MPU6050? I just got this from the internet and I only want to use the sketch for the MPU6050. Can someone help me to remove the code for the LCD? I'm sorry, I'm just noob when it comes to programming.

Here is my source: Earthquake Detector using Arduino and MPU-6050

Here is the sketch:

#include <LiquidCrystal.h>

#include <Wire.h>

#include <MPU6050.h>

#define minval -5

#define maxval 3

MPU6050 mpu;

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup()

{   lcd.begin(16, 2);

Serial.begin(115200);

pinMode(7,OUTPUT);

pinMode(8,OUTPUT);

lcd.print("   EarthQuake ");

lcd.setCursor(0, 1);

lcd.print("   Detector");

delay (2000);

lcd.clear();

// Initialize MPU6050

Serial.println("Initialize MPU6050");

while(!mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G))

{ Serial.println("Could not find a valid MPU6050 sensor, check wiring!");

delay(500);}

mpu.setThreshold(3);

// Check settings

checkSettings();

}

void checkSettings()

{

Serial.println();

Serial.print(" * Sleep Mode:        ");

Serial.println(mpu.getSleepEnabled() ? "Enabled" : "Disabled");

Serial.print(" * Clock Source:      ");

switch(mpu.getClockSource())

{case MPU6050_CLOCK_KEEP_RESET:     Serial.println("Stops the clock and
keeps the timing generator in reset"); break;

case MPU6050_CLOCK_EXTERNAL_19MHZ: Serial.println("PLL with external
19.2MHz reference"); break;

case MPU6050_CLOCK_EXTERNAL_32KHZ: Serial.println("PLL with external
32.768kHz reference"); break;

case MPU6050_CLOCK_PLL_ZGYRO:      Serial.println("PLL with Z axis
gyroscope reference"); break;

case MPU6050_CLOCK_PLL_YGYRO:      Serial.println("PLL with Y axis
gyroscope reference"); break;

case MPU6050_CLOCK_PLL_XGYRO:      Serial.println("PLL with X axis
gyroscope reference"); break;

case MPU6050_CLOCK_INTERNAL_8MHZ:  Serial.println("Internal 8MHz
oscillator"); break;

}

Serial.print(" * Gyroscope:         ");

switch(mpu.getScale())

{case MPU6050_SCALE_2000DPS:        Serial.println("2000 dps"); break;

case MPU6050_SCALE_1000DPS:        Serial.println("1000 dps"); break;

case MPU6050_SCALE_500DPS:         Serial.println("500 dps"); break;

case MPU6050_SCALE_250DPS:         Serial.println("250 dps"); break:}

Serial.print(" * Gyroscope offsets: ");

Serial.print(mpu.getGyroOffsetX());

Serial.print(" / ");

Serial.print(mpu.getGyroOffsetY());

Serial.print(" / ");

Serial.println(mpu.getGyroOffsetZ());

Serial.println();}

void loop()

{   Vector rawGyro = mpu.readRawGyro();

Vector normGyro = mpu.readNormalizeGyro();

Serial.print(" Xraw = ");

Serial.print(rawGyro.XAxis);

Serial.print(" Yraw = ");

Serial.print(rawGyro.YAxis);

Serial.print(" Zraw = ");

Serial.println(rawGyro.ZAxis);

if(normGyro.XAxis > maxval || normGyro.XAxis < minval && normGyro.YAxis >
maxval || normGyro.YAxis  < minval && normGyro.ZAxis > maxval ||
normGyro.ZAxis  < minval)

{ digitalWrite(7,HIGH);

digitalWrite(8,HIGH);

delay(300);

digitalWrite(7,HIGH);

digitalWrite(8,HIGH);

delay(300);

lcd.clear();

lcd.print("***EarthQuake***");

delay (1000);

lcd.clear();}

else{digitalWrite(7,LOW);

digitalWrite(8,LOW);}

Serial.print(" Xnorm = ");

Serial.print(normGyro.XAxis);

Serial.print(" Ynorm = ");

Serial.print(normGyro.YAxis);

Serial.print(" Znorm = ");

Serial.println(normGyro.ZAxis);

delay(10);}

As Majenko states, carefully remove all lines with the lcd object in them. Due to the extremely poor formatting and indentation of the code, if you aren't careful you could lose some important syntax, such as the { and }.

Also, there is no need for the LiquidCrystal header file.

In addition, there is a typo in the posted code (it is beyond me why the author would post uncompilable (and hence untested) code), in this line:

case MPU6050_SCALE_250DPS:         Serial.println("250 dps"); break:}

Here is the code with the lcd related lines stripped out, correctly formatted and indented, with the typo fixed:

#include <Wire.h>
#include <MPU6050.h>

#define minval -5
#define maxval 3

MPU6050 mpu;

void setup()
{
  Serial.begin(115200);
  pinMode(7,OUTPUT);
  pinMode(8,OUTPUT);

  delay (2000);

  // Initialize MPU6050
  Serial.println("Initialize MPU6050");

  while(!mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G))
  {
    Serial.println("Could not find a valid MPU6050 sensor, check wiring!");
    delay(500);
  }

  mpu.setThreshold(3);
  // Check settings
  checkSettings();
}

void checkSettings()
{
  Serial.println();
  Serial.print(" * Sleep Mode:        ");
  Serial.println(mpu.getSleepEnabled() ? "Enabled" : "Disabled");
  Serial.print(" * Clock Source:      ");
  switch(mpu.getClockSource())
  {
    case MPU6050_CLOCK_KEEP_RESET:
      Serial.println("Stops the clock and keeps the timing generator in reset");
      break;
    case MPU6050_CLOCK_EXTERNAL_19MHZ:
      Serial.println("PLL with external 19.2MHz reference");
      break;
    case MPU6050_CLOCK_EXTERNAL_32KHZ:
      Serial.println("PLL with external 32.768kHz reference");
      break;
    case MPU6050_CLOCK_PLL_ZGYRO:
      Serial.println("PLL with Z axis gyroscope reference");
      break;
    case MPU6050_CLOCK_PLL_YGYRO:
      Serial.println("PLL with Y axis gyroscope reference");
      break;
    case MPU6050_CLOCK_PLL_XGYRO:
      Serial.println("PLL with X axis gyroscope reference");
      break;
    case MPU6050_CLOCK_INTERNAL_8MHZ:
      Serial.println("Internal 8MHz oscillator");
      break;
  }

  Serial.print(" * Gyroscope:         ");
  switch(mpu.getScale())
  {
    case MPU6050_SCALE_2000DPS:
      Serial.println("2000 dps");
      break;
    case MPU6050_SCALE_1000DPS:
      Serial.println("1000 dps");
      break;
    case MPU6050_SCALE_500DPS:
       Serial.println("500 dps");
       break;
    case MPU6050_SCALE_250DPS:
       Serial.println("250 dps");
       break;
  }

  Serial.print(" * Gyroscope offsets: ");
  Serial.print(mpu.getGyroOffsetX());
  Serial.print(" / ");
  Serial.print(mpu.getGyroOffsetY());
  Serial.print(" / ");
  Serial.println(mpu.getGyroOffsetZ());
  Serial.println();
}

void loop()
{
  Vector rawGyro = mpu.readRawGyro();
  Vector normGyro = mpu.readNormalizeGyro();
  Serial.print(" Xraw = ");
  Serial.print(rawGyro.XAxis);
  Serial.print(" Yraw = ");
  Serial.print(rawGyro.YAxis);
  Serial.print(" Zraw = ");
  Serial.println(rawGyro.ZAxis);

  if (normGyro.XAxis > maxval ||
      normGyro.XAxis < minval &&
      normGyro.YAxis > maxval ||
      normGyro.YAxis < minval &&
      normGyro.ZAxis > maxval ||
      normGyro.ZAxis < minval)
  {
    digitalWrite(7,HIGH);
    digitalWrite(8,HIGH);
    delay(300);
    digitalWrite(7,HIGH);
    digitalWrite(8,HIGH);
    delay(300);
    delay (1000);
  }
  else
  {
    digitalWrite(7,LOW);
    digitalWrite(8,LOW);
  }
  Serial.print(" Xnorm = ");
  Serial.print(normGyro.XAxis);
  Serial.print(" Ynorm = ");
  Serial.print(normGyro.YAxis);
  Serial.print(" Znorm = ");
  Serial.println(normGyro.ZAxis);
  delay(10);
}

The page that you got your code from does not specify which MPU6050 library to use. It is not the library by Jeff Rowberg, as linked to from the Arduino Playground, MPU-6050 Accelerometer + Gyro. It is in fact this library, MPU6050 Triple Axis Gyroscope & Accelerometer Arduino Library.


Is it possible to program Arduino UNO with USB/TTL adapter withouth connection Vcc For some strange reason my Arduino UNO clone board occasionally cause my Mac to reset, when I connect the usb cable. Possibly a power problem in Arduino or the USB hub.

Is it possible to program Arduino UNO with USB/TTL adaptor withouth conncecting the Vcc and GND pins (RX/TX and DTR only.)

Is it possible to program Arduino UNO with USB/TTL adaptor without connecting the Vcc and GND pins (RX/TX and DTR only.)

No.
As a minimum you need to add ground as well - even if the Mac is battery powered.  Serial port signals are ground referenced so removing the ground would prevent operation.

Operation is possible without deriving Vcc from the USB port, but you will then need to derive Vcc from some other source.

If connecting ground alone causes your Mac to reset you have a serious system problem which may damage your Mac and which possibly may be dangerous to you.

Presumably you are NOT using an external power supply for the UNO.
In case you are: If the power supply for the UNO is AC mains powered it should be connected to the same mains outlet as the Mac. If the programmer powerpack is intended to be grounded but is not powered from a grounded socket AND using a 3 wire mains lead (ie with a ground pin and wire) then it s possible in some cases for the programmer to float at half mains voltage with a high impedance capacitive connection to mains. This is not usually dangerous to people but can cause minor nuisance shocks. It can destroy equipment (ask me how I know :-( .)
If you have a DMM (digital multimeter) set it to an AC voltage range greater than your local mains voltage and measure the AC voltage from a known ground (such as a water tap in most cases) and the programmer power supply (either wire or jack terminal). If you measure a voltage of about 50VAC with 100 VAC mains or about 115 VAC with 230 VAC mains then the power supply MUST be operated with a 3 wire mains cord and grounded power socket OR a ground lead from mains ground to power supply output ground.

If the Mac is battery powered and you have reset problems then something is wrong with connections or signal levels. You may be feeding voltage back onto the USB lines or loading the too heavily or ... ?


What are the main differences between the Arduino Tre and the Intel Galileo? I'm looking to find a suitable board for a robot I'm developing (it'll involve computer vision, else I'd be using my Arduino Micro) and I've come across two possibilities: The Intel Galileo and the Arduino Tre.

Now as I understand it, the Intel Galileo has a 400MHz Quark processor, whilst the Arduino Tre has 2 processors, an onboard 16MHz standard ATmega32u4 with the Arduino bootloader and then another 1GHz TI processor with Linux installed on it.

However, I'm not sure of the differences between both products, as price estimates appear to place them at approximately the same price (around $70) and the Intel Galileo doesn't appear to have any real advantage over the Arduino Tre (except for a full x86 instruction set).

Does anyone have any information on comparison of the two boards so I can make a better informed decision?

Biggest difference IMHO: Tre hasn't been released yet!

Besides that, there are a few different things that you should compare. Not much is available about the Tre as of now, but I'll update this post when it's released.

Basic Specs: [First sub-bullet is TRE, second Galileo; better spec in bold]

Microcontroller:

Texas Instrument Sitara AM3359AZCZ100 (ARM Cortex-A8) (1 GHz, 32 bit), Atmel ATmega32u4 (16 MHz, Secondary, found on Leonardo)
Intel® Quark SoC X1000 (400 MHz, 32 bit)

RAM:

512 MB SRAM (2.5 KB ATmega32u4)
512 MB SRAM

Pins

14 Digital 5V, 7 of which are PWM, 6 analog 5V (additional 6 multiplexed) (32u4); 12 Digital 3.3V, 4 of those are PWM (Sitara)
14 5V digital, 6 of those are PWM, 6 analog 5V

Networking:

Ethernet 10/100
Ethernet 10/100

USB port:

1 USB as slave, 4 USB host ports
Up to 128 devices as host, 1 USB slave

Video

HDMI (1920x1080), LCD header
None that I can find

Audio

HDMI, stereo analog audio input and output
None that I can find

MicroSD card

Yes
Yes

PCIe Slot

No
Yes

Sources (I combined a bunch of data for this): Galileo & Tre

Conclusion: If you need a board before the Tre comes out, which seems to be soon (Spring 2014), Galileo is your only option. Other than that, the Tre seems to be better all around in most aspects, minus the PCIe slot. I can't comment on power, but it seems like the Tre will be able to supply 4x the power per pin than the Galileo. The Galileo is getting older, and it doesn't seem like the Galileo can provide full Linux support like the Tre will.

Personally, I'd wait for the Tre. The only thing I can think that the Galileo would be better for would be either a.) lower power usage or b.) the PCIe slot for a WiFi adapter that works decently. The second one could be solved by doing a common WiFi router hack.

If you need a lot of processing power without the need of low latency, you should conciser sending data to a computer to process.

Source

Source


How do I send multiple variables via stream to Unity? So I currently have this for arduino.ino:

Serial.println(Variable1);

that does this in Unity:

string variable1 = stream.ReadLine();
float x = float.Parse(variable1);
transform.Rotate (0, -x/1000, 0);

My question is; How would I send 3 variables from the Arduino to Unity so I can put each value into the transform.Rotate function at once?

For example in pseudocode:

Arduino.ino
send(Variable1, Variable2, Variable3);

Unity
transform.Rotate(Variable1,Variable2,Variable3);

I hope this makes sense.
Thank you.

What you need to do is define a communication scheme/protocol. You appear to be using the Serial UART via USB.

Your first example has a simple scheme its simply the ASCII representation of the variable followed by a newline. i.e. :

float x = 123.45;
Serial.println(x);

this simply outputs

"123.45\n"

you could continue this pattern

float x, y, z,
... // assume x, y and z have values in them
Serial.print(x);
Serial.print(' ');
Serial.print(y);
Serial.print(' ');
Serial.println(z);

this outputs something like:

"123.43 23.34, 42.24\n"

then your receiving code will do do something like

string line = stream.ReadLine();
string[] parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries)
float x = float.Parse(parts[0]);
float y = float.Parse(parts[1]);
float z = float.Parse(parts[2]);

but this is very inefficient, since the arduino needs to convert the float to an ASCII string, then transmit that over the serial port, where its read on the other side, then parsed back into a float. One doesn't need to do this, you can do in binary, it won't be human readable, but it will use much less transmission space.

float x, y, z; // assume these are valid
Serial.write(&x, sizeof(float));
Serial.write(&y, sizeof(float));
Serial.write(&z, sizeof(float));
// n.b. one should write an end of message here or something else to frame the data

and on the other side

byte[] data = new byte[12];
stream.Read(data, 0, 12);

float x = BitConverter.ToSingle(data, 0);
float y = BitConverter.ToSingle(data, 4);
float z = BitConverter.ToSingle(data, 8);

You will generally also want some way to frame the data, so you might want to start with a simple message header, i.e.:

struct head
{
  int length;
  int code;
};

and you write it like:

head header; //assume this is valid
Serial.write(&header, sizeof(header));

then you can write you message.

You might also want to implement some sort of checksum, so you can verify that you got the data correctly.

You can create multiple message structures this way, i.e.

struct vect3d
{
  head header;
  float x;
  float y;
  float z;
}

just fill and send

vect3d v3;
v3.head.length = sizeof(vect3d); // one could subtract sizeof(head) off so the reader can always read the first 8 bytes and read the rest of the message from there
v3.head.code = VECT3D; // assume this is defined somewhere
v3.x = 123.5;
v3.y = 23.4;
v3.z = 42.24;

Serial.write(&v3, sizeof(v3));

On the other side one would read in the first 8 bytes, then read in the rest of the message based on the length, and parse it based on the code.


Don't Print After decimal point in In my code, I have  float Hz = 0.00; I want to display values to my user in RPM as

Serial.print("Speed = ");
Serial.print(round(Hz*60);
Serial.println(" RPM);

The only hangup is that this displays as Speed = XX.00 RPM is there an easy way to get the Arduino to only print out Speed = XX RPM?

From the documentation:

Serial.print(round(Hz*60), 0);


How can I pass an object as a parameter to a function? I am making a tiny game, and want to store high-scores. I made a Highscore-class in the top of the sketch file, like this:

class Highscore {
public:
  String name;
  int score;

  String toString() {
    return this->name + " - " + (String)score;
  }

  Highscore(String name, int score) {
    this->name = name;
    this->score = score;
  }
};

setup() { // etc

Now. Near the bottom of the sketch, I have a function I want to take a Highscore-object as a parameter, but the compiler will not let me. Example:

void writeHighscore(Highscore hs) {
  File f = SD.open("high.txt", FILE_WRITE);
  // Do stuff

The complation error is as follows:

  sketch.ino:19:21: error: variable or field ‘writeHighscore’ declared void
  sketch.ino:19:21: error: ‘Highscore’ was not declared in this scope
  sketch.ino: In function ‘void setup()’:
  sketch.ino:64:20: error: ‘writeHighscore’ was not declared in this scope

After changing parameter type to String, int or whatever, all the errors go away. I am able to create Highscore-objects INSIDE the writeHighscore() function, but how can I pass objects to it?

Edit 1 - Object creation

Highscore hs = Highscore("John", 975);
Serial.println(hs.toString()); // Prints "John - 975" as expected
writeHighscore(hs); // Error

You are doing everything right, but you need to move the class outside of your .ino file for this to work.  I'm not sure why the arduino IDE makes you do this  (see edit) , but it is something I've run into before.

I just tested this, and moving the class declaration outside the ino and into a header file in the project folder makes it compile correctly. Just remember to include the header you make in the ino and to #include "Arduino.h" in the header to get access to "String" again.

Technically, only a forward declaration of the class needs to be in a different file.

Edit:

I'm relatively sure what is happening is the IDE is generating forward declarations for all your functions but not the class, which are placed before your class definition.
This means that breaking the function regex the IDE uses with a dummy "throw()" fixes your problem. for example:

void writeHighscore(Highscore hs) throw() { ...

should work just fine (it worked for me)


How to repeat the code I want to make my biped robot keep walking, but it only move for twice, this biped robot project is important for my Capstone project. The code below is the code that I used

#include <Servo.h>

int HipR_Pin = 9;
int HipL_Pin = 10;

int KneeR_Pin = 5;
int KneeL_Pin = 6;

int AnkleR_Pin = 3;
int AnkleL_Pin = 11;

Servo HipR;
Servo HipL;

Servo KneeR;
Servo KneeL;

Servo AnkleR;
Servo AnkleL;

void setup() {
  HipR.attach(HipR_Pin);
  HipL.attach(HipL_Pin);
  KneeR.attach(KneeR_Pin);
  KneeL.attach(KneeL_Pin);
  AnkleR.attach(KneeR_Pin);
  AnkleL.attach(KneeL_Pin);
}

void loop() {

  for (int i=0; i < 7; i++)
  {
    RightStep1;
    LeftStep1;
    RightStep2;
    LeftStep2;
    RightStep3;
    LeftStep3;
    RightStep4;
    LeftStep4;
  }
  ;
}

void RightStep1()
{
  HipR.write(80);
  HipL.write(80);
  KneeR.write(100);
  KneeL.write(100);
  AnkleR.write(20);
  AnkleL.write(20);

}

void LeftStep1()
{
  HipR.write(90);
  HipL.write(90);
  KneeR.write(70);
  KneeL.write(70);
  AnkleR.write(20);
  AnkleL.write(20);

}

void RightStep2()
{
  HipR.write(70);
  HipL.write(70);
  KneeR.write(80);
  KneeL.write(80);
  AnkleR.write(10);
  AnkleL.write(10);

}

void LeftStep2()
{
  HipR.write(60);
  HipL.write(60);
  KneeR.write(90);
  KneeL.write(90);
  AnkleR.write(20);
  AnkleL.write(20);

}
void RightStep3()
{
  HipR.write(40);
  HipL.write(40);
  KneeR.write(60);
  KneeL.write(60);
  AnkleR.write(10);
  AnkleL.write(10);

}

void LeftStep3()
{
  HipR.write(50);
  HipL.write(50);
  KneeR.write(70);
  KneeL.write(70);
  AnkleR.write(20);
  AnkleL.write(20);

}
void RightStep4()
{
  HipR.write(60);
  HipL.write(60);
  KneeR.write(60);
  KneeL.write(60);
  AnkleR.write(10);
  AnkleL.write(10);

}

void LeftStep4()
{
  HipR.write(70);
  HipL.write(70);
  KneeR.write(50);
  KneeL.write(50);
  AnkleR.write(20);
  AnkleL.write(20);

}

This may not be a direct answer to your question but... when I see so
much code repetition, I cannot help but suggest you try to avoid
repeating yourself. All your Step() functions do exactly the same
actions, only with different data. You can then factor the actions
into a single function, and provide it different data as parameters.
There are many ways to achieve this in C++. I am going to show four of
them, in order from the most basic to the most esoteric.

The simplest one is to use a plain function and give it the angles as
parameters. This is basically what Michel Keijzers’ answer suggests. My
take on it would be

void Step(uint8_t hip, uint8_t knee, uint8_t ankle)
{
    HipR.write(hip);
    HipL.write(hip);
    KneeR.write(knee);
    KneeL.write(knee);
    AnkleR.write(ankle);
    AnkleL.write(ankle);
}

which you can then use in the main loop as

Step( 80, 100,  20);  // right 1
Step( 90,  70,  20);  // left 1
...

The next step in code modularity would be to group all the angles for a
single step into a compound data structure called a struct, then the
function to perform a step takes a single parameter which is this data
structure:

struct Step {
    uint8_t hip;
    uint8_t knee;
    uint8_t ankle;
};

void doStep(Step s)
{
    HipR.write(s.hip);
    HipL.write(s.hip);
    KneeR.write(s.knee);
    KneeL.write(s.knee);
    AnkleR.write(s.ankle);
    AnkleL.write(s.ankle);
}

These structs would be defined as

Step RightStep1 = { 80, 100,  20};
Step LeftStep1  = { 90,  70,  20};
...

and used in loop() as

doStep(RightStep1);
doStep(LeftStep1);
...

One step further, you can embed the function within the data structure.
The embedded function then becomes a “method” of the data structure
which is now called an “object”:

struct Step {
    uint8_t hip;
    uint8_t knee;
    uint8_t ankle;
    void perform() {
        HipR.write(hip);
        HipL.write(hip);
        KneeR.write(knee);
        KneeL.write(knee);
        AnkleR.write(ankle);
        AnkleL.write(ankle);
    }
};

The structs can be defined just as before, and used as

RightStep1.perform();
LeftStep1.perform();
...

One last technique involves making the objects themselves behave as
functions that can be called. This kind of callable object is called a
“functor”, and is kind of syntactic sugar over a method call. We just
have to rename the relevant method as operator():

struct Step {
    uint8_t hip;
    uint8_t knee;
    uint8_t ankle;
    void operator()() {
        HipR.write(hip);
        HipL.write(hip);
        KneeR.write(knee);
        KneeL.write(knee);
        AnkleR.write(ankle);
        AnkleL.write(ankle);
    }
};

The structs are still defined in the same way, but now they can be used
as if they were plain functions:

RightStep1();
LeftStep1();
...

I suggest you use whatever technique you feel the most comfortable with.
There is a logic progression though: the more you improve your C++
skills the more comfortable you will be with the latest ones.


Can I share the VCC (5V) on my Arduino Pro mini with multiple modules? Right now I am onto a new project where I am building an obstacle avoiding landrobot.

I use an arduino pro mini as my board and I have a few hc-sr04 sensors here at home. The problem I have right now is that many pins is occupied with other modules, motors and bluetooth.

So right now on my Pro Mini the VCC is occupied by my BLE device and I was wondering if there is a possibility to solder a few wires together so that my BLE device share the same VCC with 4 other hc-sr04 modules? I do this regularly with the GND where I solder multiple wires together and share the GND across different modules which works fine.

I have soldered a wire looking like this:

The idea is to power the arduino itself through the "RAW" pin. I have a power distribution board that connects to my battery/motor and the VIN pin of the PDB goes to the "RAW".

I try to avoid a breadboard to decrease the size as much as possible so if it were to be possible then that would be the optimal solution for this project.

Something I am also wondering is if it is possible to use these hc-sr04 on both the analog pins and also the digital pins. I do not have enough space to fit all the sensor cables on the digital pins but if I use the analog pins also then they all would fit. Is this possible? Each HC-sr04 has two cables that needs to be inserted (Trig and echo) and right now I have 3, 4 free and all the analog pins 0, 1, 2, 3, 4, 5 which is enough to fit them all.

Yes, you can do that as long as the total current draw of the modules you attach to VCC doesn't exceed the on-board regulator maximum current output.

The Arduino Pro Mini has a MIC5205 regulator capable of delivering up to 150 mA, which is quite low if you plan to attach many modules to its output. So you should look through your modules datasheets and find out the total current draw, including the Pro Mini board itself, and check that against the 150 mA limit.

According to the HC-SR04 datasheet, each module draws 15 mA. The Arduino Pro Mini itself draws about about 20 mA. The BLE module peak current consumption is 12.5 mA at active RX and 11 mA at active TX, so lets say 25 mA peak current draw for the BLE module.

Everything adds up to a worst case 105 mA peak current draw, within the maximum 150 mA limit. So it should be fine, but I would avoid connecting much more modules to that VCC rail.

ADDED according to your additional question:

If you run out of digital I/O pins, you can use the analog pins as digital pins if needed.

Additional note (thanks go to @jwpat7 for pointing this out in the comments):

However, this is true only of A0–A5 on most Uno and Nano Micro Arduinos, and not true of A6, A7 (except on -PB MCU models like ATmega168PB and ATmega328PB, where A6, A7 can be used as digital pins).


Can Ultimate GPS module use arduino micro instead of UNO? i am doing a Ultimate GPS module like this:

it works when i use arduino UNO board, but when I use arduino micro board it doesn't work, so could anyone tell me how to fix it?.By the way I use the example code in GPS library.

UNO: the data looks like messy code

Micro: didn't give me any time, date or fix

Your photo shows the GPS connected to pins 0 and 1 (RX and TX) on the UNO.  But you don't show the sketch you are running.  Do you have it set that way in the sketch?

It turns out the micro and UNO are different in the way those pins work.  From http://arduino.cc/en/Main/arduinoBoardMicro

  Serial: 0 (RX) and 1 (TX).  Used to receive (RX) and transmit (TX) TTL
  serial data using the ATmega32U4 hardware serial capability. Note that
  on the Micro, the Serial class refers to USB (CDC) communication; for
  TTL serial on pins 0 and 1, use the Serial1 class.

This suggests to me that you'd need to change the code to read pins 0 and 1.

Easier is probably to wire it up to pins 2 and 3 and use the defaults in the sketch

// If using software serial, keep this line enabled
// (you can change the pin numbers to match your wiring):
SoftwareSerial mySerial(3, 2);