text:
esp_partition_get_sha256() mismatches PHP's hash() function in HTTPUpdate
Disclaimer: It may be that this question belongs to a PHP forum instead of this one. However, this question is also very ESP32/Arduino related. Please correct me if this is the case.
The scenario:

Implementing self-update routines for my ESP32 project, using HTTPUpdate
Using a server-side PHP script to decide which binary image to serve to the device, or return HTTP 304 return code if no updates available.
Using the sketch's MD5 and SHA-256 hashes provided by the HTTPUpdate library as request headers, server-side, to check binary version.

The problem:

The MD5 hash contained in the request header "x-ESP32-sketch-md5" is the same as the MD5 hash calculated by a simple md5() call using the raw binary for the currently running version.
The SHA256 hash contained in the request header "x-ESP32-sketch-sha256" is not the same as the hash obtained by calling PHP's hash("sha256", $v) (where $v contains the same raw binary).

Example:

MD5 (HTTPUpdate): c93d814989b53a24a0164e561b6a8bf8
MD5 (PHP): c93d814989b53a24a0164e561b6a8bf8 (no difference)
SHA256 (HTTPUpdate): 5634674253E095600CD863A34287FCA742BCFCF9B5BF409870DD65AF0ADEF7A0
SHA256 (PHP): 1ECDDF3215520C79AAD13BBC1D116D9286910490DF316B9B203FCBFC89CBCCC2 (different)

Am I doing something wrong?
Note: The esp_partition_get_sha256() function is called internally by the update() method of the HTTPUpdate library.
PHP Code (for calculating the hashes):
<?php

$v = file_get_contents("fw.bin");

print("MD5: ". md5($v)."\r\n");
print("SHA256: ".hash("sha256", $v)."\r\n");

Arduino code (the relevant part):
// Called once or twice a day
void update_fw()
{
    Serial.println("Checking for updates...");

    t_httpUpdate_return ret = httpUpdate.update(client, "http://my_server/fw/check_fw.php");  // For now it only logs the headers and returns HTTP 304 code

    switch (ret)
    {
      case HTTP_UPDATE_FAILED:
        Serial.printf("HTTP_UPDATE_FAILED Error (%d): %s\n", httpUpdate.getLastError(), httpUpdate.getLastErrorString().c_str());
        break;

      case HTTP_UPDATE_NO_UPDATES:
        Serial.println("HTTP_UPDATE_NO_UPDATES");
        break;

      case HTTP_UPDATE_OK:
        Serial.println("HTTP_UPDATE_OK");
        break;
    }
}

PHP code (logs headers and returns HTTP 304 code):
<?php

$headers = getallheaders();

if (!file_exists("log.txt"))
{
    file_put_contents("log.txt", print_r($headers, true));
}

http_response_code(304);            // No updates.

exit;

Thanks in advance.

Your problem stems from a misunderstanding of what the functions are doing.
Your MD5 hashes are the hash of the binary file itself. And so they match.
Your PHP SHA256 is the hash of the binary file (like the MD5), but the ESP's SHA256 is not.
The file itself contains an SHA256 hash of the content of the file, not the whole file.  The function esp_partition_get_sha256 merely returns that SHA256 hash.
According to the SDK documentation:

For apps with SHA-256 appended to the app image, the result is the appended SHA-256 value for the app image content. The hash is verified before returning, if app content is invalid then the function returns ESP_ERR_IMAGE_INVALID. For apps without SHA-256 appended to the image, the result is the SHA-256 of all bytes in the app image. For other partition types, the result is the SHA-256 of the entire partition.

If you were to take the binary file and somehow strip off the extra sha256 information and then perform a hash of the results you should (theoretically) get the same hash, which would be the same has as is contained within the file itself.

True. I reached the same conclusion via a completely different way. Following a hunch, I opened the file in a hex editor and at once recognized familiar bytes at the end. Not something very scientific, but alas, there they were. While my research could've been more thorough, I partly blame it on the lack of in-code comments and documentation, and quite poor (not findable) documentation for the Arduino-ESP32 project. Maybe it's time for me to contribute more? Oh, and thank you.

To "somehow strip the extra SHA256": $image = substr($old_image,0, -32);.


text:
Opening a program in administrator with Arduino (DigiSpark/DigiSparkKeyboard)
I am quite new to Arduino and DigiSparkKeyboard so I don't know much about them. I am trying to get by DigiSpark to open CMD in administrator mode but it just doesn't work. I know that I need to get it to press control, shift and enter at the same time in order for it to run as administrator but it doesn't work.
At the moment my code looks like:
#include "DigiKeyboard.h"
#define MOD_SHIFT_LEFT      (1<<1)  //00000010
#define MOD_GUI_LEFT        (1<<3)  //00001000
#define MOD_CONTROL_LEFT    1
#define KEY_ENTER   40
#define KEY_C       6
#define KEY_M       16
#define KEY_D       7
void setup() {
  // put your setup code here, to run once:
  DigiKeyboard.update();
  DigiKeyboard.sendKeyStroke(0);
  DigiKeyboard.sendKeyStroke(0, MOD_GUI_LEFT);
  DigiKeyboard.delay(1000);
  DigiKeyboard.sendKeyStroke(KEY_C);
  DigiKeyboard.sendKeyStroke(KEY_M);
  DigiKeyboard.sendKeyStroke(KEY_D);
  DigiKeyboard.delay(1000);
  DigiKeyboard.sendKeyStroke(MOD_CONTROL_LEFT + MOD_SHIFT_LEFT + KEY_ENTER);
}

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

}

Looking at the code, the first argument should be the key, and the second the modifiers. So DigiKeyboard.sendKeyStroke(MOD_CONTROL_LEFT + MOD_SHIFT_LEFT + KEY_ENTER); should become:
DigiKeyboard.sendKeyStroke(KEY_ENTER, MOD_CONTROL_LEFT + MOD_SHIFT_LEFT);`

You can use this code :
Explanation of the code
Opens the side menu, then searches for CMD, then right-click on it to open it as administrator
A window will appear Open as administrator Yes or No
It will go to the Yes button
  DigiKeyboard.sendKeyStroke(0, MOD_GUI_LEFT);
  DigiKeyboard.delay(1500);
  DigiKeyboard.print("c;d");
  DigiKeyboard.delay(1500);
  DigiKeyboard.sendKeyStroke(KEY_ENTER, MOD_CONTROL_LEFT | MOD_SHIFT_LEFT);
  DigiKeyboard.delay(1000);
  DigiKeyboard.sendKeyStroke(0);
  DigiKeyboard.sendKeyStroke(KEY_ARROW_LEFT);
  DigiKeyboard.delay(500);
  DigiKeyboard.sendKeyStroke(KEY_ENTER);

Please enhance your answer: Correct the typo in "cmd". Add some words what is different to the existing code.

Please use DigiKeyboard.print(cmd);

And why do you think that will open CMD in administrator mode?

source: Stack Exchange

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

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

sort: votes


text:
Modify On board 4 pin switch to work with Arduino
I have a HDMI Switch module which switches Input signals. It has a 4 pin push button to switch inputs. ( - )
I want to modify the button in order to control it with an Arduino. (push via Arduino command) What should i do in order to achieve this ?
I am newbie in Arduino so please excuse my mistakes.
Thanks

Although it looks like 4 pins it's actually 2. You can see that they are connected together in pairs. This is identical to any other tactile switch of the kind used in many Arduino demos and examples.
All you need is some way of connecting the left pair of pins to the right pair of pins (in the underside image). The right pair are ground (you can tell because they are connected to the ground plane - the large copper area), so the input the left pair of pins are connected to must be active-low with a pullup resistor. That makes things simple enough.
If you can share the grounds between the switch circuit and the Arduino then it's possible to do it with just wires. However care must be taken:
Chances are this is a 3.3V based system (there's very few 5V systems around these days - the Arduino is pretty old technology from that perspective), so just setting an output HIGH or LOW and connecting it directly could damage the switch. Instead you need to emulate an open drain output. That means instead of setting a pin to OUTPUT and toggling it between HIGH and LOW to press the button you actually have to toggle the mode of the pin - that is, toggling between INPUT and OUTPUT + LOW.
For instance:
void press() {
    digitalWrite(BUTTON_PIN, LOW);
    pinMode(BUTTON_PIN, OUTPUT);
}

void release() {
    pinMode(BUTTON_PIN, INPUT);
}

You can, if you so choose, turn any GPIO pin into a real open drain output by using it to switch a transistor which in turn switches the button:

simulate this circuit – Schematic created using CircuitLab
Now it's just output a HIGH to turn the transistor ON and short the button, or LOW to turn the transistor OFF.
If you can't / don't want to share the grounds, then you can replace the transistor with an opto-isolator:

simulate this circuit
That is by far the safest option since it completely isolates (galvanic isolation) the Arduino and the switch box.

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


text:
Arduino UNO WiFi RestServer returning "not found"
I'm trying to run RestServer on my Arduino UNO WiFi, and I'm currently using the tutorial from Arduino: http://www.arduino.org/learning/tutorials/boards-tutorials/restserver-and-restclient
Everything works as expected, but whenever I change this:
  // is "digital" command?
  if (command == "digital") {
    digitalCommand(client);
  }

To this:
  // is "digital" command?
  if (command == "test") {
    digitalCommand(client);
  }

and go the the same URL but instead of "digital", user "test", I get a "not found" error.
(from http://url/arduino/digital/13/1 to http://url/arduino/test/13/1)
Am I doing something wrong? Or are the URLs in that example the only possible ones?

Try "/arduino/digital/test"...


text:
Arduino UNO WiFi "wifi shield not present"
I currently use the Arduino UNO WiFi, but when I try to use the WifiChatServer example, I keep getting the same error: wifi shield not present.
What am I doing wrong?

That example, and the library it comes with, are for the Arduino WiFi Shield. Not the Arduino Uno WiFi, which is an Arduino Uno with an ESP8266 strapped on the side through an I2C->UART converter chip.
You can't use that library, nor the examples that come with it. Instead you need to use the Uno WiFi library as stated in the FAQ for the board:

If you are using the Arduino 1.7.x then you need to use the ArduinoWiFi.h library that it is already included in the IDE.
  Instead you are using the Arduino 1.8.x then you need to download the UNOWiFiDev.Edition library from Library Manager.


text:
SoftwareSerial response is semi-gibberish using ESP8266
I have a working SoftwareSerial connection to my ESP8266 module on my Arduino UNO board. However, the response I get from the ESP8266 using the SoftwareSerial library is semi-gibberish.
So I do get the correct response, but some characters are changed.
For example when I ask the IP of the module, it sometimes returns the right IP, but most of the times just alters the IP, for example 092.168/123.5.
So what am I doing wrong?
This is the code I'm currently using:
#include <SoftwareSerial.h>

SoftwareSerial esp8266(10, 11);

void setup() {
  Serial.begin(115200);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.println("Started");
}

void loop() {
  if (esp8266.available()) {
    Serial.println(esp8266.readStringUntil("\n"));
  }
  if (Serial.available()) {
    esp8266.write(Serial.read());
  }
}

When I send the AT command, I sometimes get OK□ or some other extra random characters.
So how do I make the SoftwareSerial show (or receive) the correct response?

You never call begin on software serial.

How do you convert logic level Arduino UNO (5V) and ESP8266 (3.3V)?

@AltAir, I don't, the board accepts a logic level of 5V

Try lowering your baudrate to 9600.
https://blogs.msdn.microsoft.com/abhinaba/2016/01/23/esp8266-wifi-with-arduino-uno-and-nano/

Thank you, however I tried chaning the baudrate to 9600 by sending AT+IPR=9600 but I couldn't talk to it on rate 9600. I can't talk to it on any rate anymore... So what would the best way be to change that modules baud rate?

You need to send that command at the baud rate the ESP8266 is expecting. The default is 115200.

The command I used AT+IPR=9600 bricked the flash, but I tried it on a different ESP8266, used the AT+CIOBAUD=9600 and everything started to work! I can now read it without any gibberish, thanks!


text:
Wemos D1 & Relay shield
For one of my hobby projects I would like to use:

Wemos D1 mini pro (schematic)
Wemos D1 Relay Shield (schematic)

to control the 24V (19W) mist maker.
My current wiring is this:

As you can see the both grounds (12V and 5V) are attached to the com connector of the power supply.
I wonder whether grounds should be decoupled (for whatever reason) - i.e. to use separate power supplies? If the above wiring is OK I would really like to know in which circumstances (if any) a separate power supplies would be needed.
Thanks for all your answers in advance.

I am not sure, if a question about grounding should have been migrated here. D1 mini is not an Arduino and there aren't even any references to Arduino core firmware being used.

@gre_gor I understand what you mean but a Wemos D1 Is programmed through the Arduino IDE by default (that's what you mean by the core firmware?) So this is the right place for this board.  However I think this is really an electronics question, but ...


text:
Run Servo when detect object on OpenCV Python
I want to connect OpenCV (Python) with arduino Uno when it detects a tennis ball.
OpenCV code:
import numpy as np
import cv2
import serial
face_cascade = cv2.CascadeClassifier('tennisballdetect.xml')
cap = cv2.VideoCapture(0)
while 1:
ret, img = cap.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
print(faces)
    for (x, y, w, h) in faces:
    cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
detect=(x+y)/2
    print(detect)
cv2.imshow('img', img)
k = cv2.waitKey(30) & 0xff
if k == 27:
    break
cap.release()
cv2.destroyAllWindows()

# Module -2: Trigger Pyserial
if detect > 0:

     ser = serial.Serial('COM1', 9600)
     print(ser)
     ser.write('Y')
else:

   ser = serial.Serial('COM1', 9600)
   print(ser)
   ser.write('N')

My Arduino Code:
#include <Servo.h>
int servoPin = 3;
Servo Servo1;
char incomingBit;    // for incoming serial data

void setup() {
// We need to attach the servo to the used pin number
// Servo1.attach(servoPin);
pinMode(servoPin, OUTPUT);      // sets the digital pin as output
Serial.begin(9600);    // opens serial port, sets data rate to 9600 bps
}
void loop() {
if (Serial.available() > 0) {       // Serial.available(), which detects if
any data has been sent to the
                                   //serial port
 //  Serial.read() will read the incoming character and store it in
incomingBit
    incomingBit = Serial.read();
    Serial.print("I received:  ");
    //if the value of incomingBit is ‘Y’, we need to turn the LED ‘on’, else we turn it ‘off’. So,
    //in a nutshell,if detecting faces from a given image was successful, this will turn on the LED

            if(incomingBit == 'Y' || incomingBit == 'y') {

             // Make servo go to 0 degrees
  Servo1.write(0);
  delay(1000);
 // Make servo go to 90 degrees
   Servo1.write(90);
 delay(1000);
 // Make servo go to 180 degrees
 Servo1.write(180);
 delay(1000);
 //exit(0);
            }
            else {
              digitalWrite(servoPin, LOW);
            }
  }
}

Servo is correctly connected to Arduino and it is moving without serial communication. openCV is also working and detecting tennisball.
But when trying to connect OpenCV to arduino, servo is not moving.
Any kind of help is appreciated.

Put a serial.print incomingBit. Also serial.read returns a byte. Could be that your parse is failing.

Can you be a bit more specific? I am new to this and this is not very clear to me.Sorry for that.

Put Serial.println(incomingBit) after serial.read() to see if you get an incoming command

You need to debug the code. Is the message sent through the COM(serial communication), if so, is it recived on the other end? Anyway put ´Serial.print("I received:  "); Serial.println(incomingBit);´ to se if anything is recived on the other end. Then get back to me! =)

The "detect" value in Python code is >0 but still when I upload my arduino code , I get no value at arduino IDE. Is there any way to solve it? @sigma

If i understand you right, the python code is sending a massage but the Arduino isn't receiving it. It looks right on the arduino side. I cant help you with python code, its not my area. Could be that you are not sending it correctly, just a wild guess. :/


text:
Nano clone failure, how to prevent it from happening again?
I'd made an LED driver, and fed both the LEDs and nano clone from 12V. The 12V switched power supply is of dubious quality. The nano itself read a pot, and wrote PWM values on three pins. It has run on-off for 2-3 months. Not long. Now it's dead - my PC does register the serial device on the nano, and the power LED comes on. Apart from that, there's nothing that works.
Before I replace it, I'd like to know if the most likely culprit was my feeding 12V into VIN. Overheating voltage regulator? The LEDs got a bit hot, ~40°, and the nano was in a box with no airflow.

How did you connect the leds?

They were connected through 3 2N7000 MOSFETs, they didn't pull power from the nano. I have considered if they exceeded their rated current, but am unsure. IIRC, it's a 10V MOSFET, which I turned on with a 5V signal. The rated current is 200mA max. In any case, would a burnt MOSFET murder my nano? I've heard the act like shorts when they die. Please apply cluebat.

Did you put a resistor between the Arduino and the gate of the mosfet?

Yes, 220 ohms for good measure. I know the 2N7000 doesn't surge. I checked the MOSFETs, and all LED channels (R, G, B) work. It's just the nano that's dead.

You could try reflashing the boot loader using a separate Arduino. Have you measured the voltage of the power supply? Some are only 12V when under load, and can go as high as e.g. 18V when there is no or minimal load.

Also try measuring the 5V pin when you connect the 12v to Vin. It could be that the voltage regulator is broken.

I see a 5V signal on the 5V pin, but the program in flash is not running as far as I can tell. The PWM pins send out random values, and turning the potentiometer is not affecting these values. The power supply is at 12V, both unloaded and loaded. I use one of these for a small 10W drill. I'll look into flashing it on the RXD/TXD pins first, then I'll try reflashing the bootloader. Thanks. If you post the last comment below as an answer, I'll close this question.

Dyd you try to flash in a simple Blink using the onboard LED? You should go very basic when things start to fail like that. Also, disconnect the 12V power supply and power your nano from USB only when running this simple test: the voltage regulator should not be part of the circuit when powered from USB and you can start factoring things out.

Yes, I did that - the device is not responding. Rxd/Txd pins are dead as well. I'm putting this down to overheating voltage regulator inside an already toasty-hot closed compartment.


text:
RFID access system with PN532 reader
I have a PN532, so it's capable of both reading and writing. I've used it for a few perfectly functional things, but I want it to authenticate based on the contents (for example 1024 bytes) of a tag.
I'd generate some pseudorandom data, possibly on my PC, and write that into each card, and use a checksum of that as the key.
Should I just stick with the standard authentication of tokens, or is this a worthwhile alternative method? The UIDs of the tokens are not interesting for authentication.
If worthwhile, what checksumming algorithms should I use? If not, would someone care to explain how I can program the memory of tokens, and how to use that in addition to UID for auth?
Thanks in advance.

First off, you don't want to use a checksum for authentication.
A checksum can be thought of as a hash with a very small size. The smaller the size of a hash the less unique it is. The less unique it is the more likely it is that incorrect data will generate the same hash and authenticate someone it shouldn't.
For instance, a 32 bit checksum (hash) of 1kB data (8192 bits of information) is a 256-fold reduction in the uniqueness of the value. At 32 bits you get 232 unique values. With 8192 bits you get 28192 possible values. I can't calculate how many values that actually is, but as you can imagine there will be many billions of billions of combinations that would all equate to the same checksum.
If you must use a checksum then make it an actual recognised hash. For instance an MD5 (considered weak by today's standards) has 128 bits. SHA-256 has, as you would imagine, 256 bits.
However calculating these hashes on an Arduino is not a simple matter owing to a lack of memory. Not impossible, but not that easy.
If you're going as far as to use such large amounts of data for authentication and using heavy mathematical routines to create a hash you may as well go the whole hog and use a proper cryptographic key pair.
One method would be to encrypt the UUID of the card off-line and store the encrypted result on the card - that data would then be unique to that card and tied to it - you wouldn't be able to clone the card unless you could clone the UUID as well.
Then either the UUID is read by the Arduino and also encrypted using the same key and if the results match authentication succeeds. Or the encrypted value is decrypted by the Arduino and compared to the UUID to see if they match. Which you choose depends on if you have asymmetric or symmetric encryption (the former is more like a hash but requires the encryption key to replicate it whereas a hash doesn't).
You can also include other information with the UUID, such as the name of the card owner (for identification purposes), etc - as long as you are able to already know that data to create the cryptographic has to compare with what is on the card.

How should I go about reading the UUID, mangling it, and writing a new UUID to a token? A few google search phrases will suffice.

It is prudent to say that I used your uid-database-on-EEPROM idea, and it was excellent. Very sleek. Now you are the last hope for my precise control of the data on my RFID tags. You, gerben, gammon et al, but mostly you. Please answer:)


text:
Pro Mini atmega168 voltage woes
I have a fistful of Pro Mini clones with atmega168 ICs. Oddly they have 16MHz crystals. When I feed it nominal 3.7V (really 4V, but it will spend most time around 3.7) via the RAW pin, I see 2.6V on VCC and RST pins. Of course I’d like a bit more for my MOSFETs - what’s the cause of this? It’s a 1.4V drop, is this common for pro minis?
I can feed 3.3V to VCC with a regulator, but the 16MHz crystal is puzzling. Clocked for 16MHz?

Bypass the regulator, and connect the battery directly to the VCC pin. However, running at 16Mhz requires at least 3.8 Volts, according to the datasheet. Lower voltages may work, but aren't guarantied.

Yes, I did that, and it works as one might expect. The chinese have made many wonderful arduino clones; this is a collector’s item... (I also have a Nano with a 12MHz crystal). In any case my problem has been resolved.


text:
Simulate V1838B IR LED output
I have a HDMI switcher which uses a TL1338 IR LED that's connected via a 3.5mm audio jack. It has its own remote for switching between the inputs, but I want to use my TV remote.
In order to do that I want to connect the IR led to an ATTiny85 to receive the input and send the 'translated'code to the switcher.
When analysed with an oscilloscope it seemed that Arduino Libraries output a PWM signal, while the TL1838 outputs a digital signal. Is there a way to simulate a TL1838 signal?
Original situation:

Goal situation with ATTiny85.

What you want to do is send "unmodulated" IR Codes, but the library is trying to modulate them with a 38khz carrier. (The TL1838 device has a built-in demodulator.)
While your question is not a duplicate, this answer applies.

Thank you very much. Now that I have the term unmodulated I can research more in the right direction as well. It's also a very complete answer.


text:
Arduino - Getting error - 'TCCR2' was not declared in this scope
This code below:
void setup() {
  #if defined(__AVR_ATmega168__)
    // 62.5KHz PWM for the ATMega168 -> only on Arduino pins 9 and 10

    // set prescaler to 1
    // (sbi means "set bit register", cbi means "clear bit register")
    cbi(TCCR1B, CS12);
    cbi(TCCR1B, CS11);
    sbi(TCCR1B, CS10);

    // set fast PWM
    cbi(TCCR1B, WGM13);
    sbi(TCCR1B, WGM12);
    // with fast PWM, the frequency is (CLK/256*prescaler) = 16MHz/256 = 62.5KHz
    // with slow PWM, it is half that speed (31KHz)
  #else
    // 22KHz for the ATMega8 (this is a low frequency)
    TCCR2 = ((TCCR2 & ~0x07) | 0x01); //<ERROR POINTS HERE!
    TCCR1B = ((TCCR1B & ~0x07) | 0x01);
  #endif
}

when verify, generates an error:
In function 'void setup()':
pwm-control-1:185: error: 'TCCR2' was not declared in this scope
TCCR2 = ((TCCR2 & ~0x07) | 0x01);
^
exit status 1
'TCCR2' was not declared in this scope

So far i know this code generates pwm at pin 9 or 10, and designed for ATmega168 or ATmega8. The code came with a .pde extension and I opened it on 'Arduino: 1.8.3' and saved as an .ino file.
Can any one please tell me how to convert this code to work with 'ATmega328P-PU' and for the latest Arduino IDE. And also if there anything else to consider running with this code
I'm not an expert in pwm and timer/controls in micros... just started to learn..
Note: I've only shown the necessary part of the code

Since your problem is with the software delivered with Arduino, this question belongs on Arduino.SE

This issue can happen if you select the wrong board in the Arduino IDE.

Check the datasheet to see if there is a tccrb. Maybe for your device, it is tccra, tccrb, or teerc, ....

The problem is because TCCR2 is not declared, as there is no register with that name. Maybe you wanted to configure the timer 2, i.e. you meant TCCR2A or TCCR2B instead of TCCR2.
EDIT: analyzing your code, you should definitely write TCCR2B.


text:
serial.write if condition
I am trying to do a simple serial communication control via sending a char and using it as an if condition, the arduino part is below
char incomingchar;
void setup() {
    Serial.begin(9600);     // opens serial port, sets data rate to 9600 bps
//        Serial.write("g"); // does not work when I explicitly write here either as opposed to through python.
}

void loop() {
    if (Serial.available()) {
            // read the incoming char:
            incomingchar = Serial.read();
               if (incomingchar=="g"){
              Serial.println("hello world!");}
              else{
              Serial.println(incomingchar);
    }
}
}

And here is the Python code:
import serial;
ser=serial.Serial('COM3',9600,timeout=1)
ser.write(b'g')

When I run this, the python program returns a '1', and so does the arduino program in the serial monitor.
Note, if I directly set Serial.write('g'), it simply types out 'g' in the monitor and does nothing else from the loop.

With Char types you want to use the single-quote mark instead of double quotes.

Welcome to Arduino Stack Exchange.  Be sure to take the tour at https://arduino.stackexchange.com

I think @Mazaryk's answer is correct, but may a comment regarding your comment: the reason writing "g" to serial in your setup doesn't work is because that would be written to the output wire, and you're reading from the input wire.

hi Mark, thanks for your insight, could you explain a little more about output wire? I thought what I was doing was sending the 'g' to the arduino, what is the way to 'input' to the arduino then?

You declare incomingchar as a char. In your if you compare that char to a string (double quotes) incomingchar=="g". I think you want to compare it to a char (single quotes) like this:
if ( incomingchar == 'g' ) {
  // do something
}

Hi Mazaryk, I made the change, it works now (albeit in a different paradigm where serial monitor or Arduino IDE is not open) I think the issue was also that python can't access the port if you have arduino or serial monitor open, so it was preventing me from really testing it. If someone knows how to get over that, would be much appreciated.

authors: Михаил Силкин


text:
Library using another library
I'm writing library for smart home arduino DIY project.
i want to use another library(not written by me).
here is the code:
boiler.cpp
#include "Boiler.h"

Boiler::Boiler(int pin)
{
    _pin = pin;
    dev.setDevice(_pin);                    // Set Device Output (on/off)
    turnOff();
}

boiler.h
#ifndef BOILER_H_
#define BOILER_H_

// include RF24 libs
#include "RF24.h"
#include "RF24Network.h"
#include "RF24Mesh.h"
#include <SPI.h>

// SmartHome Lib Includes
#include "Device.h"
#include "TimerOne.h"
#include "timeSet.h"

class Boiler
{

    private:

        RF24 radio(7, 8);
        RF24Network network(radio);
        RF24Mesh mesh(radio, network);

        int _pin ;

        void timerIsr();
        void DrawSCR();
    public:
        .
        .
        .

        Boiler (int pin );
        void turnOn();
        void turnOff();
};

The problem is it's not compiling
the error I get is :
Boiler.h: 32:14: error: expected identifier before numeric constant
RF24 radio(7, 8)
What am i doing wrong?
Thanks,

I've always had to put the includes of all "sub-libraries" in the main sketch.

But i wish to use it in the library... i only declare the boiler and takes care of the communication ....

You already asked this on SO. Don't cross post.

I Have found the answer (by mistake)
i have added the includes to Boiler.cpp file
#include "RF24.h"
#include "RF24Network.h"
#include "RF24Mesh.h"
#include <SPI.h>
.
.
.
#include "Boiler.h"

RF24 radio(7, 8);                                   // Init RF24 Radio
RF24Network network(radio);                         // Init RF24 Network
RF24Mesh mesh(radio, network);                      // Init RF24 Mesh

Boiler::Boiler(int pin ,float Rev , String Last )
{
    _pin = pin;
    dev.setDevice(_pin);                    // Set Device Output (on/off)
    turnOff();
}

void Boiler::init( char nodeID)
{
    _nodeID = nodeID;
    // Connect to the mesh and set Node ID
    mesh.setNodeID(_nodeID);
    if (_DEBUG) Serial.println(F("Connecting to the mesh..."));
    mesh.begin();

    // init LCD and print init data on LCD
    myGLCD.InitLCD(60);                         // Init LCD 55 contrast
    myGLCD.setFont(SmallFont);                  // Set small font
    myGLCD.clrScr();                            // clr screen
    myGLCD.print("Boiler Device",0,0);          //Print init Data on screen
    myGLCD.print("Rev :" , 0 , 10);
    myGLCD.printNumF(_rev,1 ,35,10,'.',1,'0');
    myGLCD.print(_last,0,40);
    myGLCD.update();                            // Update display

    turnOff();
}

and now it compiles ;-)

What am i doing wrong?

without seeing those includes, it is hard to tell.
I can say is that your original code, with the includes in boiler.h, is the right approach.
the revised code, which doesn't give you the error message, it not the right approach.
the issue is likely that the associated .h and .cpp files are incorrectly coded. unfortunately, without the actual code, it is hard to tell how and what the fixes should be.

you can see the library here: https://github.com/danhajduk/SmartHome

is it posible to declare public variable from method constractor?


text:
Mega SPI communication changing between setup and loop
I am attempting to use an arduino MEGA 2560 to control a digital potentiometer (AD5206), but I am getting some strange behavior. I have attached the CLK and MOSI pins (52 and 51, respectively) to an oscilloscope, and have run the following code:
#include <SPI.h>
void setup() {
    SPI.begin();
    SPI.transfer(5);
    delay(500);
}

void loop() {
    SPI.transfer(5);
    delay(500);
}

When I look at the signal, the transfer in the setup() looks correct (5V x 00000011), but then the transfer in the loop() looks like it's shifted by -5V (-5V x 11111100). Has anyone ever run into this? Is it possible for the MEGA to output a negative voltage?

You are not controlling the chip properly. Read the datasheet, and learn how SPI communication works, then you will know what is blatantly missing from your code.

I realize that the above code is not sufficient to control the AD5206. I have only posted a small piece of code that demonstrates the issue that I am seeing. The problem is that the 8bit spi signal is being shifted by -5V in the loop (but not in the setup).

Except where is the start of the 8 bit SPI signal? Where is your chip select control that frames each transaction and tells the chip where the start of communication is?

In my actual code, I pull the SS low, send the pin address and the resistor value (2x8 bit signals). The code that I have posted is the most concise script that I can post that creates the issue that I am asking about. I am not concerned with the serial formatting for communicating with the AD5206. My question here is purely concerned with the Arduino serial signal being shifted by -5V in the loop.

Well, as it stands that code is invalid and doesn't demonstrate anything at all. With no synchronisation there is no clue what the different clock pulses mean.

Oh, and how are you determining that the output is wrong?

No, there is no problem with SPI on the Mega. If there were it would have been noticed by now.
Instead it's either the way you are measuring it or your method of generating the SPI signals that are at fault (and since you won't show us your real code we can't help you with that).
This is a trace of your provided "code" with the delays reduced to allow easier fitting on a single trace:

Clock goes low when SPI.begin() is called. Then there are the successive transfers - the first being in setup() and the rest in loop(). As you can see they are all identical.


text:
Multiplying the voltage output
I'm working on a project where my arduino is receiving a voltage 0-5V, I need the output to be 10V always. Is there a way to do that?

You get a power supply that gives 10V and switch it using the Arduino (just like you would with a relay or a motor). Or if you need analog between 0-10V you amplify it (again with a 10V or higher power supply) with an op-amp.

Hello and welcome. Could you please be more specific about your task? Unfortunately there are multiple interpretations of what you wrote so far. Is your input signal analog (0 to 5 V) or digital (just high and low)? If analog how is your intended relation of the output to the input (multiplication implies an analog relation, i.e. in 0V - out 0V, in 2V - out 4V, in 5V - out 10V) or do you mean that if the input is low (or if analog below a certain threshold) the output should be 0V and if the input is high (analog above threshold) the output should be 10V? [...]

[...] Do you want to drive a certain load with that 10V? If recommending a specific setup (i.e. transistor circuit) that might make a difference.

Assuming the 0-5 Volts is supposed to switch the output, in which case you want a program to control your output, then you will want to use a digital output pin to either switch a relay or a transistor that controls the 10 Volts put out to whatever it is that you are controlling.
Perhaps you want PWM which indicates a transistor circuit.  Hard to tell what you want from the way this is worded.
Taking your words literaly, "I need the output to be 10V always" then that simply means hard-wiring to a 10V power supply.   ;-)

authors: ΔΗΜΗΤΡΗΣ ΤΣΙΝΟΓΛΟΥ


text:
How to program Fio v3 without MicroUSB port
I got given a Fio V3 but unfortunately the MicroUSB port is missing, not sure why.  Is there any other way to program it?  I'm thinking perhaps those 6 pins under the microcontroller?

Also can I still power the board?  I notice it doesn't have a VCC or RAW pin like the Pro Micro version.  I'm not to worried about using a battery, can I plug any matching voltage into the battery plug?
I tried looking through the schematics and tutorials on Sparkfun but don't really know what I'm looking at.  Here are some relevant links anyhow:

Product page
Schematics
Datasheet

The board runs at 3.3V, so you can provide 3.3V directly into the 3.3V pin on the side. Also the black connector next to the USB socket is a battery connection for a Li-Ion battery or similar. It will take any voltage between 3.6V and 5V. Any higher and, according to the schematics, you need to remove the solder link that's just below the battery connector (silver blob). With that link removed you can theoretically go up to 20V on the battery input.
Yes, you can program through the 6-pin header below the main chip if you have a suitable hardware programmer (e.g., USBASP). That is a normal ICSP header like most Arduino boards have.

Ah cool thanks.  I also found these under the zigbee, I don't suppose I can solder a USB cable into them can I? https://www.dropbox.com/s/jv5r2c84saajrdv/IMG_20170505_013718.jpg?dl=0

@hamstar I have no idea what that is, but I don't see anything related to USB there.

Looking at the hook up guide might help.  https://learn.sparkfun.com/tutorials/pro-micro--fio-v3-hookup-guide
The "best" solution might be to try and get the connector replaced, if the pads are still OK.  But soldering those connectors is not an easy task.
The datasheet you linked to is the Lion charger, forget about that PDF.

Thanks, yea the pads are no good and I am not very accurate at soldering. I checked that guide but it has no mention what the 6 pins in the middle are.   I also found some pins under the Zigbee board labeled DTR and CTS with but it seems they may be the serial connection to the Zigbee (https://www.dropbox.com/s/jv5r2c84saajrdv/IMG_20170505_013718.jpg?dl=0).


text:
NRF24L01 only receiving zeros
I'm attempting to transmit very simple data across some NRF24l01 modules for testing purposes, and I've been following a YouTube guide.
Here is my code:
Trasmitter:
#include "RF24.h"
#include <SPI.h>

RF24 Radio (7, 8);
byte address[][6] = {"0"};
struct package{
   int on = 1;
};

typedef struct package Package;
Package data;

void setup() {
  Serial.begin(9600);
  delay(1000);
  Radio.begin();
  Radio.setChannel(118);
  Radio.setPALevel(RF24_PA_LOW);
  Radio.setDataRate(RF24_250KBPS);
  Radio.openWritingPipe(address[0]);
  delay(1000);
}

void loop() {
  Radio.write(&data, sizeof(data));

  Serial.println("Data sent:");
  Serial.println(data.on);
  delay(1000);
  }
}

Receiver:
 #include "RF24.h"
 #include <SPI.h>

 RF24 Radio (7, 8);
 byte address[][6] = {"0"};
 struct package{
    int on = 1;
 };

 typedef struct package Package;
 Package data;

 void setup() {
   Serial.begin(9600);
   pinMode(2, OUTPUT);
   delay(1000);
   Radio.begin();
   Radio.setChannel(118);
   Radio.setPALevel(RF24_PA_LOW);
   Radio.setDataRate(RF24_250KBPS);
   Radio.openReadingPipe(1, address[0]);
   Radio.startListening();
   delay(1000);
 }

 void loop() {
   while(Radio.available()){
     Radio.read(&data, sizeof(data));
     if(data.on == 1){
       digitalWrite(2, HIGH);
     }
     else if(data.on == 0){
       digitalWrite(2, HIGH);
     }
     else{
       digitalWrite(2, LOW);
     }
     Serial.println(data.on);
   }
   while(!Radio.available()){
     Serial.println("Error");
   }
   delay(1000);
 }

When I run the code on each respective unit, I receive only zeros on the receiver. Since I don't see where data.on could get set to zero in my code, I'm assuming there is a communication issue somehow between the two modules, even though Radio.available() is functioning properly.
Am I missing something obvious?

I would try it without the structs.

Are they both Unos? Could be a packing issue if one is a 32-bit MCU. You realize pin 2 is set whether data.on is 1 or 0?

@TisteAndii, Im transmitting with an orginal Uno and receiving with a knock-off Mega2560. Is that a cause for concern? Also, pin 2 is just an led that I was using for debugging. I am reading the serial port for the actual value.

Well, they're both 8-bit CPUs. So packing shouldn't be an issue. Still print the values of 'sizeof(data)' for each MCU to confirm they're the same. Also I'd advise that you add more characters to your address...remember reading the module has problems with 2 bytes or less.

@TisteAndii, sizeof(data) is the same on both ends, and changing the address to a larger number doesn't resolve the issue either. Another interesting note, Radia.available is returning true even when the sending module is not powered on...
Sorry for the delayed response, busy life

What new address did you use? Use 3 bytes at least.

@TisteAndii, I used 888. I would assume that would be 3 bytes, but I don't actually know how you determine byte length of a number.

@Wilson The amt of memory the number occupies depends on its type. It should take up at least 2 bytes assuming you assigned it to an integer type variable. Update your post to show how you used the new address. Or merely use "uint64_t address = 0xdeadbeef" so you get a 4-byte address.

@TisteAndii, I figured it out! thank you so much for your help, the issue turned out to be that the SPI pins on the MEGA are assigned differently than the UNO, and the code was actually working the whole time. I cant thank you enough for helping me, even if it turned out to be in vain.

@Wilson please add an answer stating how you fixed this and accept it: this way this is not anymore reported as an "unanswered question"


text:
Advanced I/O shifting bits
I wanted to tinker around more with the 8-bit shift register (74HC595) so I tried to make a simple LED display and after reading about some shift commands I got lost and didn't understand much...
Let's start simple...
from what I read -- you can send out Binary data 1s and 0s --- does the shift regsiter read it as on and off? the shift register I'm using which is probably the same thing with others but it has 8 pins that can be used as output --- how does it output the data? --- does it output (example) 10100110 which shifts to the right as if 00000000 -> 10000000 -> 11000000 -> 01100000 -> 00110000 -> 10011000 -> 0100110 -> 10100110 through the pins one by one? like pin 1 would get 0 first then 0 will move to pin 2 and pin 1 will get a 1? (still using 10100110 by example above ^ )
Also what would the code look like? how does shiftOut() and shiftIn() work exactly? does all of this have something to do with pulseIn()? what do the bitwise operators like >> and << or ~ to name a few exactly do?
let's say I made 8 leds hooked up to one of each output pin of the shift-register --- how do I give data to the register? what commands should I use to give data? --- from what I understood I can output 01011011 right? if so, how does the shift-register output it? and if (Assumingly) it does output it like on and off would it eventually turn out as if LED1 = OFF LED2 = ON LED3 = OFF LED4 = ON LED5 = ON LED6 = OFF LED7 = ON LED8 = ON as if I entered in 01011011?
tl;dr
how do 8-bit shift registers work and how do you make codes work with them xP

Voting to close as too broad. You should do some research yourself first. Start by reading a tutorial on the 74HC595 shift register: it should answer most of your questions. Then look at the source code of shiftOut(). If you still have doubts then, come back here with more specific questions.

I bolded out the questions I'd like answered most although I'd understand if you still find it too broad

Did you read the tutorial?

I read another thing about it but it doesn't address above questions or at least I didn't understand those

For the 74HC595 in combination with the Arduino, the best way to check is to use the default example by Arduino:
ShiftOut
With the ShiftOut you can shift the bits into the IC which will make the correct LEDs light up (or not).
Probably you can lit up a LED when passing a HIGH, but you will know very easily by trying the example and check some values/for loops to make them dynamically lighting.
Probably after playing with the example, it will give you much more insight than describing the details here.
Update:

Try first with 00000000 and 11111111 and 8 leds, so you know if 0 will be OFF and 1 will be ON.
Than try with eg 10101010 and 8 leds ... than you know if the first or the last will be on or off.
pulseIn is unrelated
The operators >> and << are so called bit shift operators. Like 1 << 3 gives 8, the binary value 0000001 is shifted 3 bits left resulting in 00001000 which has value 8.
~ is the not operator -> which reverses bits.
The shiftOut function can be used to send data to the 74HC595N.
And to be honest, how does it work ... does it really matter for now? First see what the result is, how to use it. Later you can get into details. Start simple first.

how do I give out 11111111? do I need to make a variable that has 255 to make all bits become 1? or is there another way? --- also the shiftOut works like this "shiftOut(-dataPin-, -clockPin-, MSBFIRST, -variable-)" right? is the dataPin the pin connected to the arduino?

Yes, 255 is 11111111 binary. You can also use a for loop and set each bit with << operator. Data and clock pin are explained in the example (just connect it to the correct pins of the 74HC595, LSBFIRST/MSBFIRST decide the order, the variable is the 255 number above). The data pin you have to connect to the Arduino, otherwise the 74HC595N cannot receive the value.

I see, I see --- I will test this out when I get home thanks for the answer :)


text:
About multiple void loops and functions
I'm still a beginner at Arduino coding -- I've been researching on how to make functions using void instead of doing goto because reasons...
one thing I've noticed about void is that it has this void loop() {...} parenthesis, what is it for? (and can you provide an example of using it?)
say I make a void function void function1() to call the function I have to use function1(); can I make a function that loops? like the ol' void loop() {...} command we all know and love or do all void functions loop? if not then what happens to a void function after it reaches the end of its function?

The void in front of the function definition just tells what type the function returns.  In the case of void it means the function returns nothing.  If the function returned an int then it would be defined with int instead of void.
eg:
int addNumbers(int num1, int num2){
    int retval = num1 + num2;
    return retval;
}

int sum = addNumbers(3, 4);
Serial.print(sum);  // prints 7

No, the loop only loops because main (see main.cpp in the core) is the "real" program that is running on your micro and it calls loop over and over.  It's not that the loop function on it's own repeats.  It is literally being called repeatedly by the main function.
That example also gets to what the parenthesis are for.  That's where the arguments that the function takes go.  In the function definition you tell it what types they'll be and give them names.  In the function call you put in whatever values you want to function to use.  In the case of void loop(), it takes no arguments so the parenthesis are empty.
I would suggest you look at a basic tutorial on C++.  There are many good ones on the web.  The concept of functions isn't something that you can reason your way through by doing.  Go read a little and you'll get it pretty quick.

Is there any way to run multiple void functions at the same time?

Not on an Arduino.  It has a single core.  It executes one instruction at a time.

PC's that are capable of multithreading can be running several instructions at the same time, so they could be running multiple functions at the same time.  But Arduino can't do that.

Also note, they're just called functions.  Not "void functions".  The void is the return type.  It just tells you what the function returns.

authors: Владимир Захарченко


text:
can I give the 9v input power for arduino mega 2560 using vin pin?
I am using Arduino mega 2560. I have some doubts about powering my microcontroller.
Can I use the 9v battery to power my arduino through the VIN terminal?
I have uploaded an image. Check whether it is a correct method or not?

you can, but it wastes expensive batteries. 4/9ths of the energy used will be heat. a DC-DC buck converter will only waste about 1/9th of the battery. That's like buy 2 get 1 free; not bad for less than $1 "investment".

Yes!

The board can operate on an external supply of 6 to 20 volts. If supplied with less than 7V, however, the 5V pin may supply less than five volts and the board may become unstable. If using more than 12V, the voltage regulator may overheat and damage the board. The recommended range is 7 to 12 volts.
The power pins are as follows:
  - Vin. The input voltage to the board when it's using an external power source (as opposed to 5 volts from the USB connection or other regulated power source). You can supply voltage through this pin, or, if supplying voltage via the power jack, access it through this pin.

https://www.arduino.cc/en/Main/ArduinoBoardMega2560
Vin is the same as the external positive power input.

Vin is the same as the external positive power input.; not exactly. The jack also has a diode, to protect against reverse polarity. Vin doesn't have this diode. But other than that, they are the same.

Gerben you are correct. Thanks for your clarification.

@Gerben/anyone: for the newbies, can you link to an example of the right kind of diode that protects against reverse polarity?  Is any old LED a valid diode for this functionality?

A standard 1N4004 or 1N4007 can be found almost anywhere that sells electronics.

Alternatively, you could get an adaptor that allows you plug straight into the barrel jack - hence removing the need for the diode. For example: https://www.jaycar.com.au/2-1mm-dc-plug-with-screw-terminals/p/PA3711

@misterbee The diode is only used for protection against reverse polarity. Connect it up the correct way and you won't need the diode. However, connect it up the wrong way and you could get smoke.

Thanks! Ah, that number is printed on the side of the "diode rectifier" included in the Eleglo Arduino kit.


text:
Split flash Arduino nano
I need to update the firmware over-the-air for Arduino nano. For that I need to split the flash into two so that one of the partition that contains the original code cannot be erased while re-flashing and the other partition will contain the segment in which the re-flashed program would appear.
The board reboots from the first partition before the flashing initiates, during flashing the code in the first partition would be active and the board reboots from the new code in the second partition after the flashing is complete.
I don't have any idea how to play around with the flash splitting in arduino and any help would be appreciated.

You'll need to look into creating your own bootloader. As only the bootloader can write to flash.

According to your plan it will be quite hard to do........ But infact you could do one thing that is change the arduino's bootloader a bit that is increasing the timeout of  the bootloader where it decides to whether go for flashing or go for proccessing the program.....


text:
Ethercard. Copying ip address into hisip
I've tried getting help from arduino.cc forum but they arent helping at all (more like being cryptic) i'm kinda a newb at this. And i'm seriously not getting help from there. 2 messages in 8 days from one person and they arent helping.
i have a project that does following
-connects to network
-Gets ip address
-finds UDP broadcaster
-Connections to a web server's hard coded ip address and grabs data
-displays it on a screen.
that works fine. but i been trying to get the UDP broadcaster's ip address into the http part of the code so it connects to the broadcaster without having to hard code the IP Address.
here is my code. i want to have the ip address thats is grabed by the udpSerialPrint stament and have it put into the ether.hisip and use it in the ether.browseUrl(PSTR("/arduino"), "", website, my_callback);
Hope you can help. Thank you.
#include "Arduino.h"
#include <Wire.h>
#include <EtherCard.h>
#include "NexText.h"
#include "NexPage.h"
#include <IPAddress.h>

// Present a "Will be back soon web page", as stand-in webserver.
// 2011-01-30 <jc@wippler.nl> http://opensource.org/licenses/mit-license.php

#define STATIC 0  // set to 1 to disable DHCP (adjust myip/gwip values below)

// ethernet mac address - must be unique on your network
static byte mymac[] = { 0x74,0x69,0x69,0x2D,0x30,0x31 };

byte Ethernet::buffer[700];
static uint32_t timer;

const int buzzer = 9; //buzzer to arduino pin 9

String ipaddy;
String CurrentTime;
String MainBroadcastIP;
String MainBroadcastIP2;
String Solarwatts;
String BatteryA;
String BatterySOC;
String Housewatts;
String Systemname;
String Updatetime;
String BatteryV;

NexText txtstartup = NexText(0,1,"txtstartup");
NexText txtsystemname = NexText(0,2,"txtsystem");
NexText txtsolarw = NexText(0,3,"txtsolar");
NexText txtbatterya = NexText(0,4,"txtbatterya");
NexText txthousew = NexText(0,5,"txthousew");
NexText txtbatterySOC = NexText(0,6,"txtbatterySOC");
NexText txtupdatetime = NexText(0,7,"txtupdate");
NexPage PageMain1 = NexPage(0,8,"Main1");

const char website[] PROGMEM = "192.168.15.3";

NexTouch *nexListenList[] =
{
    &txtstartup,
    &PageMain1,
    &txtsystemname,
    &txtsolarw,
    &txtbatterya,
    &txthousew,
    &txtbatterySOC,
    &txtupdatetime,
    &PageMain1,
    NULL
};

void setup(){
  dbSerial.begin(9600);
  nexInit();

  Serial.println("\n[AC-DC Power Monitor]");
  pinMode(buzzer, OUTPUT);
  txtstartup.setText("Welcome! System is Starting");
  delay(2000);
  txtstartup.setText("Attempting to Obtain an \r IP Address");
  delay(2000);

  Serial.println("Initialising the Ethernet controller");
  //Mega is ether.begin(sizeof Ethernet::buffer, mymac, 53)
  //Duo is ether.begin(sizeof Ethernet::buffer, mymac, 10)
    if (ether.begin(sizeof Ethernet::buffer, mymac, 53) == 0) {
        Serial.println("Ethernet controller NOT initialised");
        txtstartup.setText("Network Card not detected!");
        while (true);
    }

    Serial.println("Attempting to get an IP address using DHCP");
    if (ether.dhcpSetup()) {
        ether.udpServerListenOnPort(&udpSerialPrint, 8888);
        ether.printIp("Got an IP address using DHCP: ", ether.myip);
        char a1[10],a2[10],a3[10],a4[10];
        sprintf(a1,"%d",ether.myip[0]);
        sprintf(a2,"%d",ether.myip[1]);
        sprintf(a3,"%d",ether.myip[2]);
        sprintf(a4,"%d",ether.myip[3]);
        ipaddy = String(a1) + "." + a2 + "." + a3 + "." + a4;
        String msgtext = "Got IP: " + ipaddy;
        txtstartup.setText(msgtext.c_str());
        tone(buzzer, 1000); // Send 1KHz sound signal...
        delay(250);        // ...for 1 sec
        noTone(buzzer);     // Stop sound...
        delay(250);        // ...for 1 sec
        tone(buzzer, 1000); // Send 1KHz sound signal...
        delay(250);        // ...for 1 sec
        noTone(buzzer);     // Stop sound...

    } else {
        tone(buzzer, 400); // Send 0.4KHz sound signal...
        delay(500);        // ...for 1 sec
        noTone(buzzer);     // Stop sound...
        delay(500);        // ...for 1 sec
        tone(buzzer, 400); // Send 0.4KHz sound signal...
        delay(500);        // ...for 1 sec
        noTone(buzzer);     // Stop sound.
        exit(0);
    }

    #if 1
      // use DNS to resolve the website's IP address
      if (!ether.dnsLookup(website))
        Serial.println("DNS failed");
    #elif 2
      // if website is a string containing an IP address instead of a domain name,
      // then use it directly. Note: the string can not be in PROGMEM.
      char websiteIP[] = "192.168.1.1";
      ether.parseIp(ether.hisip, websiteIP);
    #else
      // or provide a numeric IP address instead of a string
      byte hisip[] = { 192,168,1,1 };
      ether.copyIp(ether.hisip, hisip);
    #endif

    delay(2000);
    PageMain1.show();
    ether.printIp("SRV: ", ether.hisip);
}

void loop(){
        ether.packetLoop(ether.packetReceive());

  if (millis() > timer) {
    timer = millis() + 1000;
    Serial.println();
    Serial.print("<<< REQ ");
    ether.hisport = 8181;
    ether.browseUrl(PSTR("/arduino"), "", website, my_callback);
  }

}

void checkserver()
{
    delay(1000);
    Serial.println();

}

void udpSerialPrint(word port, byte ip[4], const char *data, word len) {
IPAddress src(ip[0], ip[1], ip[2], ip[3]);
        char a1[10],a2[10],a3[10],a4[10];
        sprintf(a1,"%d",src[0]);
        sprintf(a2,"%d",src[1]);
        sprintf(a3,"%d",src[2]);
        sprintf(a4,"%d",src[3]);

        MainBroadcastIP = String(a1) + "." + a2 + "." + a3 + "." + a4;
      return;
}

String getValue(String data, char separator, int index)
{
    int found = 0;
    int strIndex[] = { 0, -1 };
    int maxIndex = data.length() - 1;

    for (int i = 0; i <= maxIndex && found <= index; i++) {
        if (data.charAt(i) == separator || i == maxIndex) {
            found++;
            strIndex[0] = strIndex[1] + 1;
            strIndex[1] = (i == maxIndex) ? i+1 : i;
        }
    }
    return found > index ? data.substring(strIndex[0], strIndex[1]) : "";
}

char* string2char(String command){
    if(command.length()!=0){
        char *p = const_cast<char*>(command.c_str());
        return p;
    }
}

static void my_callback (byte status, word off, word len) {
  Serial.println(">>>");
  Ethernet::buffer[off+300] = 0;
  String web = (const char*) Ethernet::buffer + off;
  Serial.println((const char*) Ethernet::buffer + off);
  int weblengh = web.length();
  String web2 = web.substring(131,weblengh);
  Serial.println("System Name: " + getValue(web2, ',', 0));
  Systemname = getValue(web2, ',', 0);
  Serial.println("Solar Watts: " + getValue(web2, ',', 1) + "W");
  Solarwatts = getValue(web2, ',', 1) + "W";
  Serial.println("House Watts: " + getValue(web2, ',', 2) + "W");
  Housewatts = getValue(web2, ',', 2) + "W";
  Serial.println("Battery SOC: " + getValue(web2, ',', 3) + "%");
  BatterySOC = getValue(web2, ',', 3) + "%";
  Serial.println("Battery Volts: " + getValue(web2, ',', 4) + "V");
  BatteryV = getValue(web2, ',', 4) + "V";
  Serial.println("Battery Amps: " + getValue(web2, ',', 5) + "A");
  BatteryA = getValue(web2, ',', 5) + "A";
  Serial.println("Battery Amps: " + getValue(web2, ',', 6));
  Serial.println("Battery Amps: " + getValue(web2, ',', 7));
  Serial.println("Time: " + getValue(web2, ',', 8));
  Updatetime = getValue(web2, ',', 8);

  txtsystemname.setText(Systemname.c_str());
  txtsolarw.setText(Solarwatts.c_str());
  txthousew.setText(Housewatts.c_str());
  txtbatterySOC.setText(BatterySOC.c_str());
  txtbatterya.setText(BatteryA.c_str());
  txtupdatetime.setText(Updatetime.c_str());

}

I would recommend isolating the issue and writing a small test sketch. It is very difficult for anybody to simply jump in and help.

Well, ether is global, so you can access it from your udpSerialPrint function. That function gets passed the IP address in the ip[4] array, so you can just use ether.copyIp(ether.hisip, ip); to set it.
I would also set a flag to say "I have got the IP address" and only attempt to do anything with the website when you know the IP address has been given to you.

I dont know what i;m doing wrong. but i have tried adding ether.copyIp(ether.hisip, ip) to the udpSerialPrint  statement and it didnt work.

Scratch that. i got it to work now., Thank you very much


text:
Arduino + L9637 K-Line reader - 10400 baud on SoftwareSerial?
I know this question has been asked many times before in different flavours, but all of the previous questions I have found seem to pre-date the current SoftwareSerial library, which afaik now (unlike when the previous questions were asked) allows any baud rate to be set as it calculates the values for the timings.
So I currently have the L9637 monolithic bus driver connected to pins D0 and D1 of my Arduino Uno. I am trying to create an ECU reader to communicate with my car over the KW1281 protocol, and from testing I have discovered I need to do the 5 baud init and then communicate at 10,400 baud.
First off I want to say I have successfully managed to run the 5 baud init. Now, I realise the pins (D0 & D1) are capable of hardware serial, however when trying to use the hardware serial I couldn't get any connection to the car. I think it's because the hardware serial doesn't like the pin modes to be changed after setup - however this is required to perform the 5 baud init. So I have decided to use the SoftwareSerial library for the following 10,400 baud communication.
With this library I successfully receive three (incorrect) response bytes from the ECU when setting a baud rate of 9600, however the response bytes - despite being correct in the number of them (3) - are wrong in terms of their value and seem to just be zero values.
Now as my car requires 10,400 baud communication, I instead setup the serial port to 10,400 baud. I know from experience that using 9600 baud will give incorrect response bytes and 10400 baud solves this. So I expected this would work and solve my problem, however it didn't. I still get 3 bytes containing 0. Just to be clear the three correct values should be: 55 01 8A
So I was wondering:

Am I right in assuming the SoftwareSerial library will work for any baud rate, even 10,400?
If yes to point 1, can anyone suggest why I might be getting data bytes containing 0 instead of the correct values?

As the full code is too long to post, the code for setting up the UART at 10,400, and then receiving the bytes is as follows:
#include <Wire.h>
#include <SoftwareSerial.h>

SoftwareSerial obd(pinKLineRX, pinKLineTX, false); // RX, TX, inverse logic
obd.begin(baudrate);

uint8_t data = 0;
int recvcount = 0;
char s[3];

while (obd.available())
{
   uint8_t data = obd.read();
   s[recvcount] = data;
   recvcount++;
}

And then to print the data I do the following:
#include <Adafruit_GFX.h>
#include <UTFTGLUE.h>

UTFTGLUE lcd(0x9488,A2,A1,A3,A4,A0);

char textout[30];
int xVal = 50;
cursorY = 10;
for (int i=0; i < size; i++)
{
  uint8_t data = s[i];

  sprintf(textout, "%i ", data);
  lcd.print(textout, xVal, cursorY);
  xVal += 10;
}

cursorY += 10;

The output on the LCD is

0 0 0

When it should be

55 01 8A

I don't have experience with your specific case... I tried to use MIDI over SoftwareSerial (31250 baud). And I missed some messages, especially when there are more messages sent in a shorter period. There are other SoftwareSerial libraries, but had similar problems. So I try to stay away from SoftwareSerial.

Thanks for your reply. Well I believe I cannot use hardware serial so I have no choice really... Although I did see that when using a lower baud and also receiving less messages then there should be less missed messages in the serial connection. Can you by any chance tell me if you had to edit the software serial library to calculate the correct timings for the custom baud rate? Or did you use the latest libraries where the library calculates the timings?

I used the midi library which I passed the baudrate to that library (MIDI library from 47effects). So I did not had to change the library. I will add some more in an answer (gives me some possibility to add bullets).

I've found 9600 baud to be the receive limit among standard baud rates (transmission can go faster). You're proposing an 8% increase over 9600 which sounds like it has a good chance of working but you'll need to experiment to find out.
You also asked why might your data (on the LCD) be wrong.
You'll do your sanity a big favor and do two separate experiments:

First, get known data (literal strings or terminal input) to display correctly on your LCD, before you try to use the LCD to confirm or debug your communications.
Second, get SoftwareSerial running (or find out that it doesn't...) at 10400 baud. In fact try to get up to, say, 12000 baud, or at least push the rate to find out where it starts to fail so you know how much head-room you'll have at 10,400. The simplest way would be to use two Arduinos if you have access to another one. Again, use your terminal or some literal strings on MCU 'A' to send to MCU 'B', MCU 'B' should receive a line and echo it back to 'A', who prints it on its terminal. Printing it on 'B's terminal wouldn't be a bad idea either.

You'll be in a lot better position to combine the two techniques once you have confidence that each one works; especially if you copy-and-paste known-working code segments.

Thanks for your answer, I think I may have not explained the situation very clearly in my original post though. I know for sure my LCD is displaying the correct data so there is no issue there. As for the SoftwareSerial running at 10,400 baud, I know that others have had it running on an Arduino Uno before but that was with the old library which used hardcoded timings. So I guess the take home for now is to as you say try and communicate with a PC running at 10,400 baud in order to reduce the unknowns and very that serial instance.begin(10400) works out of the box (or not if thats the case).

Also the Arduino library specifies the Uno can handle up to 57600 baud, so there shouldn't be a technical issue running 10,400.

Great! When I last tested it, I didn't find it to receive reliably at above 9600 baud. I guess it's time I check my library version & test again. I could sure use that 5x speedup!

I tried using MIDI data with the software library. However, I also got problems with missing and/or corrupted messages. MIDI has a fixed baudrate of 31,250 baud. As long as I did not sent too much, everything was ok, but sending continuous messages (within the 31,250 baud rate spec) I got into problems. It seems that the input buffer was too full and/or no time to process them.
The default buffer for the serial (software serial) buffer was 64 bytes. I increased it to 128, but saw no difference. Making the buffer higher probably just would delay the time until messages are corrupted.
What you can do is:

Use a non Arduino device with multiple UARTs (no experience with that)
There seems to exists a 328PB version of the Uno which has two UARTs (but it maybe a kind of niche device, possibly with support problems)
What I did was using a Mega, it has 4 UARTs.
Using multiple Uno's and/or Mega's connected to eachother, giving 1 resp. 4 UARTs


text:
I want to declare an array with variable size and also I want to ask from the user to enter it?
I'm using C++ language.
double coordinates [length][5];

What have you tried so far? Would you please show more of your code?Did you take a look at C++ new operator?

You can not declare an array of variable length unless you do dynamic memory allocation.  Dynamic memory allocation on an embedded platform is not a good idea, so it is better to fix the 'length' of the array to a sensible limit.

You'll have to dynamically allocate it.
int length;
double **coordinates;
cin >> length;
coordinates = new double*[length];
for (int i = 0; i < length; i ++ {
    coordinates[i] = new double[5];
}

so then I have to close it at the end of my code.

Indeed you will.

I'd love to say this will crash, but it won't compile.  cin doesn't exist on an Arduino unless you have got a port of the std lib.   The memory you allocate needs freeing. Finally allowing a user to enter an unrestricted value for length is asking for a crash.  Enter 1,000,000 if your doubt me :)

That's fair. But it was tagged c++, so that's how I answered. IMHO, this question should be migrated to Stack Overflow.


text:
Arduino LilyPad and nRF8001 module wiring
I am trying to wire up a nRF8001 BLE module with the LilyPad board, as the title says.
The problem is that if I wire them up I am not more able to see the nRF8001 module during the scan phase with the nRF UART 2.0 app ( https://play.google.com/store/apps/details?id=com.nordicsemi.nrfUARTv2&hl=it for Android). INstead, if I wire the nRF8001 up with the Arduino Uno rev3 I can correctly exchanging messages from the serial monior to the app and viceversa.
Since the LilyPad is quite equals the the Arduino in terms of processor and pinout, I am wondering what I am doing wrong.
The wirings is the following:
LilyPad   <--->   nRF8001
  +                 Vin
  -                 GND
pin #2              RDY
pin #9              RST
pin #10             REQ
pin #11             MOSI
pin #12             MISO
pin #13             SCK

Does anyone have any suggestion? Thanks in advance!
Filippo

How are you powering the LilyPad? Check the current and voltage levels.

Lilypad is powered via the FTDI USB adapter, so should be 5V, isn't it?

Should I use the 6-pins header (2x3) in the cebnter of the board near the processor for the SPI connection?


text:
Bluetooth Low Energy dropping data at 115200 baud?
I'm transmitting serial data from a sensor on my Arduino simultaneously to my laptop via USB and to a terminal app on my phone via a genuine HM-10 BLE module (onboard a Linksprite BLE Shield).
At 9600 baud, the BLE module was transmitting all of my data to the phone's terminal app without issue. I just figured out how to increase the HM-10 module's baud rate to 115200 (for reference, by sending it an AT+BAUD4 command at 9600 baud from the Arduino IDE console via USB, and then uploading a new sketch to the Arduino with both the USB serial and BLE serial baud rates set to 115200). The data is being received via USB serial flawlessly, but the data received by the terminal app on my phone via BLE appears to be missing chunks of data - and I have to try to connect to it 30+ times to get it to properly connect.
Is 115200 baud too fast to transmit data via BLE? Is there any way to make sure all of the data is properly sent via BLE without slowing the program down too much? 9600 baud is too slow for my application, unfortunately.
I should add that I am using an Arduino M0 pro and the BLE is connected via hardware serial (Serial1) and not SoftwareSerial as would need to be done on the Uno, if that makes a difference.

Well, I did some tests and was not able to reliably receive data at over 9600 baud, even with hardware flow control activated via the AT+FLOW1 command. And even then, if either the BLE module or the phone was moving, data was consistentlydropped.
I ended up implementing an SD data logger instead.

How quickly are you reading the data from the buffer?


text:
Seven-Segment Display doesn't work on two lights
This is my code:
void setup() {
    pinMode(2, OUTPUT);
}

void loop() {
    digitalWrite(2, HIGH);
}

This is my circuit:

Problem:

Light A and B doesn't work when I plug the red cable to 4 and 5.
All the other lights works just fine.

Did you try using a different part?

Do you mean to another 7-segment display ?
I don't have one right now but I can buy one tomorrow. I was hoping that I have any type of error. I don't have any error ?

You don't have enough code to have any fatal errors. You haven't proven that the pins are the correct ones though.

Be sure you have a current-limiting resistor in series with any LED segments that you light up, in either the ground side or the high side.  Do segments A or B light up when you apply 5 V instead of trying to drive them with an Arduino IO?

As jwpat7 states, you need a current-limiting resistor for each segment, between the data pin (on the Arduino) and the segment pin (on the display). Your Fritzing diagram only shows one resistor in the circuit, from the common cathode to GND on the Arduino.
You can not, or should not, share one resistor to ground (assuming that you have a common cathode seven segment display). You need a current-limiting resistor on each anode (again, (assuming that you have a common cathode seven segment display).
If you are sharing the current-limiting resistor between all segments, and then try to light more than more segment, at a time (which it sounds like you are doing ("when I plug the red cable to 4 and 5"), then the current through the current-limiting resistor will increase, and as a result, the voltage will change significantly enough, such that there is not sufficient voltage drop across the LED in order to make it light up.
Remember, 0.7 V is dropped across the LED.
Test each on the segments, one at a time, to make sure they all work, as Ignacio states in his comment.
Also, your sketch should be more complete, along the lines of:
void setup() {
    pinMode(2, OUTPUT);
    pinMode(3, OUTPUT);
    pinMode(4, OUTPUT);
    pinMode(5, OUTPUT);
    pinMode(6, OUTPUT);
    pinMode(7, OUTPUT);
    pinMode(8, OUTPUT);
}

void loop() {
    digitalWrite(2, HIGH);
    digitalWrite(3, HIGH);
    digitalWrite(4, HIGH);
    digitalWrite(5, HIGH);
    digitalWrite(6, HIGH);
    digitalWrite(7, HIGH);
    digitalWrite(8, HIGH);
}

Connect up all of the pins, using a current-limiting resistor on each anode, and then try it programmatically.
If your seven segment display is a common anode, then, again, you need a resistor between each cathode and the data pins, and bring the pins LOW to light the corresponding segment, i.e.
    digitalWrite(8, LOW);


text:
Source code for Arduino “firmware”?
I am wondering if anyone here knows where the source code for the Arduino "firmware" is available for reading? I think it must be more than the 'boot loader' but I am not sure. Thanks!
p.s. I assume this kind of question is ok here, even though it's not ok on StackOverflow?

The “firmware” is whatever program a microcontroller runs. On an
Arduino, it is typically the program you write and upload into the
microcontroller's flash memory.
If by “firmware” you mean the core library (the source code of
pinMode(), digitalRead() and so on), it is here:
https://github.com/arduino/ArduinoCore-avr
If by “firmware” you mean the bootloader (the small program that runs at
reset and will accept the upload of your firmware), is is here:
https://github.com/arduino/Arduino/tree/master/hardware/arduino/avr/bootloaders/optiboot
Note that this is valid for the AVR-based Arduinos.
The cores and bootloaders used in other architectures are stored is
separate repositories, e.g.
https://github.com/arduino/ArduinoCore-sam

If you are looking for the Flash Firmware, I think the github project documentation is pretty well developed, here:
https://github.com/arduino/Arduino
This is a good introduction to build and flash your Arduino UNO:
http://angryelectron.com/arduino-firmware/
And here a good start to build you own Arduino on a breadboard:
https://www.arduino.cc/en/main/standalone

Thanks. The arduino/arduino github repo looks like java so I think it's for their IDE. Thanks for the other links, I will followup.

@pitosalas: that GitHub repo also has the source of the AVR core and a few extra libraries.


text:
If statement comparing array to value list throws error
In my program I have the following lines of code:
if (invest == {0, 1, 0, 0})
   {
      //code
   }

However, upon attempting to compile the code, I receive the following error:
exit status 1
expected ';' before '}' token

"Invest" is a bool array originally defined with`
bool invest[] = {0, 0, 0, 0};

How can I prevent this error from ocurring?

You cannot compare like that... you have to do it one by one (and check the length of the array).
if ((sizeof(invest) / sizeof(bool) == 4) &&
    (invest[0] == 0) &&
    (invest[1] == 1) &&
    (invest[2] == 0) &&
    (invest[3] == 0))
{
     ...
}

If you need to do such a compare often (with possibly different values), you of course can always write a dedicated function passing the array, and the array to check against and check the length and use a loop for checking all values.
Note that if invest is a boolean array, it's best to use false and true instead 0 and 1.

:((((((((((((((

@Excelseo you are not happy with my answer?

Unfortunately you cannot do that.
In addition to Michel Keijzers, another possible way is to use binary manipulation of an integer.
Your declaration of the variable would look like this:
unsigned int invest = 0x00;    // B0000 or 0 would be acceptable also

(See https://www.arduino.cc/en/Reference/IntegerConstants for notation reference.)
So your if statement would be very close to what you had originally wrote.
if (invest == B0100)
{
   //code
}

Using this method you cannot reference each bit in the same way as an array (ie invest[3]). Instead to view the 4th bit:
result = (invest && 0x08) >> 3;

To set the 4th bit you would need to write:
invest |= 0x08;    // ie. B1000

And to clear the 4th bit:
invest &= 0x07;    // ie. B0111

Arduino has bitRead(x, n) and  bitWrite(x, n, b) macros.

@gre_gor, Even better!!! Thanks for your suggestion.

You have a syntax error in that code; in C99, you would need to declare the type of the anonymous array {0, 1, 0, 0}, for example via  (bool[]){0, 1, 0, 0}.  So the following code compiles ok in C:
int main() {
  char invest[] = {0, 1, 0, 0};
  if (invest == (char[]){0, 1, 0, 0})
    printf("Yes yes yes\n");
  else
    printf("No no no\n");
  return 0;
}

However, if you compile and run this code, it will output "No no no" rather than "Yes yes yes" because the logical test invest == (char[]){0, 1, 0, 0} says to compare the address of the invest array to the address of the anonymous array, and of course they differ.
Note, if you try to compile the above as a C++ program, the result will be “error: taking address of temporary array” due to different type checking.

All that said, the straightforward way to compare arrays of bytes or in some cases arrays in general is to use the memcmp() function.  From its man page:
SYNOPSIS
   #include <string.h>
   ...
   int memcmp(const void *s1, const void *s2, size_t n);
DESCRIPTION
   The  memcmp()  function compares the first n bytes (each
   interpreted as unsigned char) of the memory areas s1 and s2.
RETURN VALUE
   The memcmp() function returns an integer less than, equal to,
   or greater  than zero  if  the  first  n  bytes of s1 is found,
   respectively, to be less than, to match, or be greater than
   the first n bytes of s2.

The following code compiles ok both in C99 and C++ and prints out "Yes yes yes.".
#include <stdio.h>
#include <string.h>
int main() {
  char invest[] = {0, 1, 0, 0};
  char others[] = {0, 1, 0, 0};
  if (memcmp(invest, others, sizeof invest)==0)
    printf("Yes yes yes.\n");
  else
    printf("No no no.\n");
  return 0;
}

Note, when compiling code like this in the Arduino IDE, you may be able to leave out one or both of the #include statements.

I think this will not work if the length of others is longer than invest, than only the elements of invest are checked (or in other words: you should check also if the length of invest equals the length of others).


text:
LEDs on Arduino WiFi Shield
I would like to know the purpose of the LEDs on top of the Arduino WiFi Shield: L9/Link/Error/Data (left in the picture). What do they indicate?

The web page on the Arduino site for the board tells you in plain words what they mean:

On board indicators The shield contains a number of informational LEDs:

L9 (yellow) : this is tied to digital pin 9
LINK (green) : indicates a connection to a network
ERROR (red) : indicates when there is a communication error
DATA (blue) : indicates data being transmitted/received


text:
Communication over UDP between Dues with Arduino WiFi Shield
I'm using the Arduino WiFi Shield to make two Arduinos Due communicate using UDP. The first node to send a message (the Client) doesn't always receive a reply from the other node (the Server). The code for the Client:
#include <string.h>

#include <SPI.h>
#include <WiFi.h>
#include <WiFiUdp.h>

#define BUFSZ 90

// variables for WiFi connection
char ssid[] = "ssid";
char pass[] = "pwd";
int status = WL_IDLE_STATUS;

char sendBuffer[BUFSZ];
char recvBuffer[BUFSZ];

WiFiUDP Udp;
unsigned int localPort = 51515;

IPAddress server(192,168,88,251);
unsigned int serverPort = 12345;

void printWifiData()
{
    // print your WiFi shield's IP address:
    IPAddress ip = WiFi.localIP();
    Serial.print("IP Address: ");
    Serial.println(ip);

    // print your MAC address:
    byte mac[6];
    WiFi.macAddress(mac);
    Serial.print("MAC address: ");
    Serial.print(mac[5],HEX);
    Serial.print(":");
    Serial.print(mac[4],HEX);
    Serial.print(":");
    Serial.print(mac[3],HEX);
    Serial.print(":");
    Serial.print(mac[2],HEX);
    Serial.print(":");
    Serial.print(mac[1],HEX);
    Serial.print(":");
    Serial.println(mac[0],HEX);
}

void setup()
{
    Serial.begin(115200);
    while (!Serial); // wait for serial port to connect

    // connect to WiFi network
    while (status != WL_CONNECTED) {
        Serial.print("Attempting to connect to WPA SSID: ");
        Serial.println(ssid);
        status = WiFi.begin(ssid, pass);
        delay(10000);
    }

    // print connection details
    Serial.println("You're connected to the network");
    printWifiData();

    Udp.begin(localPort);
    strcpy(sendBuffer, "abcdefghijklmnopqrstuvwxyz123456789101112131415161718192021222324252627282930313233343536");
}

void loop()
{
    Udp.beginPacket(server, serverPort);
    int len = Udp.write(sendBuffer);
    Udp.endPacket();

    Serial.print("Sent ");
    Serial.print(len);
    Serial.println(" bytes.");

    delay(10);

    int packetSize = Udp.parsePacket();
    if (packetSize > 0) {
        Serial.print("\nReceived packet of size ");
        Serial.println(packetSize);

        Serial.print("From ");
        IPAddress remoteIp = Udp.remoteIP();
        Serial.print(remoteIp);
        Serial.print(", port ");
        Serial.println(Udp.remotePort());

        // read the packet into recvBuffer
        int len = Udp.read(recvBuffer, BUFSZ);
        if (len > 0) {
            Serial.println("Contents:");
            Serial.println(recvBuffer);
        }
        else {
            Serial.println("Read 0 bytes.");
        }
    }
    else {
        Serial.println("\nNo packets yet.");
    }
}

Server:
#include <SPI.h>
#include <WiFi.h>
#include <WiFiUdp.h>

#define BUFSZ 90

// variables for WiFi connection
char ssid[] = "ssid";
char pass[] = "pwd";
int status = WL_IDLE_STATUS;

char sendBuffer[BUFSZ];
char recvBuffer[] = "acknowledged";

WiFiUDP Udp;
unsigned int localPort = 12345;

void printWifiData()
{
    // print your WiFi shield's IP address:
    IPAddress ip = WiFi.localIP();
    Serial.print("IP Address: ");
    Serial.println(ip);

    // print your MAC address:
    byte mac[6];
    WiFi.macAddress(mac);
    Serial.print("MAC address: ");
    Serial.print(mac[5],HEX);
    Serial.print(":");
    Serial.print(mac[4],HEX);
    Serial.print(":");
    Serial.print(mac[3],HEX);
    Serial.print(":");
    Serial.print(mac[2],HEX);
    Serial.print(":");
    Serial.print(mac[1],HEX);
    Serial.print(":");
    Serial.println(mac[0],HEX);
}

void setup()
{
    Serial.begin(115200);
    while (!Serial); // wait for serial port to connect

    // connect to WiFi network
    while (status != WL_CONNECTED) {
        Serial.print("Attempting to connect to WPA SSID: ");
        Serial.println(ssid);
        status = WiFi.begin(ssid, pass);
        delay(10000);
    }

    // print connection details
    Serial.println("You're connected to the network");
    printWifiData();

    Udp.begin(localPort);
    Serial.println("Waiting...");
}

void loop()
{
    int packetSize = Udp.parsePacket();

    if (packetSize) {
        Serial.print("Received packet of size ");
        Serial.println(packetSize);

        Serial.print("From ");
        IPAddress remoteIp = Udp.remoteIP();
        Serial.print(remoteIp);
        Serial.print(", port ");
        Serial.println(Udp.remotePort());

        // read the packet into recvBuffer
        int len = Udp.read(recvBuffer, BUFSZ);
        if (len > 0) {
            Serial.println("\nContents:");
            Serial.println(recvBuffer);

            Udp.beginPacket(Udp.remoteIP(), 51515);
            Udp.write(sendBuffer);
            Udp.endPacket();
        }
        else {
            Serial.println("Read 0 bytes.");
        }
    }
}

I don't know if it's a timing problem... So I've tried to use delays after the Client send its message but the issue persists. So the Client sends many messages to the Server but receives few replies. I didn't want to put the part of the code in the Client when it's waiting for a response inside a loop in case the first message is lost (so the Client will never receive a response anyway). Did anyone have a simular problem or a suggestion to fix this issue?

duplicate of http://forum.arduino.cc/index.php?topic=525579

UDP is not a protocol that guarantees delivery

I was able to solve the problem. First of all, I needed a bigger delay between the send and receive parts in the Client.
So I'm using delay(35);. This is important so the Client can have enough time to receive the reply before sending another message.
Also, inside the Server, the buffers to send and receive a packet were inverted.
So, the correct would be:
char sendBuffer[] = "acknowledged";
char recvBuffer[BUFSZ];

I understand the messages can stil be lost because UDP does not guarantee delivery, but with a larger delay in an isolated WiFi network all of the messages from the Client got a reply.


text:
Including Arduino library in a Makefile for Due
I'm currently using a Makefile for the Arduino Due I've found on Github (with some modifications). It's useful to me cause it allows me to add a static library for cryptographic functions I need and I can't do it using the IDE. Now I need to include the WiFi library from Arduino but I don't know how. I've tried to put the path to the source (/usr/share/arduino/libraries/WiFi/src) but it gives me warnings saying that some classes are undefined. Does anyone know how to include that library?

Adding a library isn't as simple as just adding an include path.
You also have to identify each and every source file (or use wildcards as are used for the various sections of the core) and compile them into object files. It is then quite convenient to archive those into a library (.a) file which you can then link your sketch against (if you don't archive you will have to link all the objects files with your sketch in the linking phase).


text:
Adafruit Motor Shield steppers not turning
The Adafruit Motor Shield is connected to 2 steppers which are wired correctly and work when I just use the onestep function. I understand that I cannot drive both at once, so I am using a while loop with two if statements. The Motors were wired:
The left motor was wired:
Green -> m3+
White -> m3-
Red -> m4+
Blue -> m4-
The right motor was wired:
Red -> M2+
Blue -> M2-
Green -> M1+
Black -> M1-
Here is the code:
#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_MS_PWMServoDriver.h"

Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_StepperMotor *leftMotor = AFMS.getStepper(200, 2);
Adafruit_StepperMotor *rightMotor = AFMS.getStepper(200, 1);
//79 steps per half inch
//half inch is a coordinate
//declaring global variables for Hypotenuses (cord lengths)
int leftHyp;
int rightHyp;
int prevX = 0;
int prevY = 0;
//space from shaft to shaft is 30"
//calculating function
void CordCalc(int xCord, int yCord)
{
    Serial.begin(9600);
  //cords start at 0,0
    xCord = xCord - prevX;
    yCord = yCord - prevY;
    int xSquared = sq(xCord);
    int ySquared = sq(yCord);
    int addSquares = xSquared + ySquared;
    int leftHyp = sqrt(addSquares);
  //now for the right
    int rightX = 60 - xCord;
    int rightXsq = sq(rightX);
    int rightSquares = rightXsq + ySquared;
    int rightHyp = sqrt(rightSquares);
  //leftMotor->step(leftHyp * 79, FORWARD, MICROSTEP);
  //rightMotor->step(rightHyp * 79, FORWARD, MICROSTEP);
    int lStepsTaken = 0;
    int rStepsTaken = 0;
    leftHyp = leftHyp * 79;
    rightHyp = rightHyp * 79;
    bool stepsComplete = false;

  //This is the section for moving the Motors
    while(stepsComplete == false) {
        if(lStepsTaken <= leftHyp) {
            leftMotor->onestep(FORWARD,DOUBLE);
            lStepsTaken++;
            Serial.print("Left");
        }

        if(rStepsTaken < rightHyp) {
            rightMotor->onestep(FORWARD,DOUBLE);
            rStepsTaken++;
            Serial.print("Right!");
        }

        if(rStepsTaken >= leftHyp && lStepsTaken >= leftHyp) {
            stepsComplete = true;
        }
    }

    int prevY = yCord;
    int prevX = xCord;
    stepsComplete = false;
}

void setup()
{
// direction from project point of view
    int leftLength = 0;
    int rightLength = 0;
    leftMotor->setSpeed(122);
    rightMotor->setSpeed(122);
    Serial.begin(9600);

    CordCalc(15, 15);
}

void loop()
{
}

Loop is empty on purpose because only need to move to coordinates once.

you really need to format your code properly. ... correct indentation helps a lot when debugging code

The missing line was afms.begin(); which starts communication with the adafruit motor shield.


text:
What datatype is the names of the analog inputs?
I am writing a code for an automatic garden, and for this, I will use an array of sensors. I want to represent each plant as a class, and so one of the private variables will then be the sensorID, the name of the input on the analog inputs. But these are called 'A0' 'A1' and so forth, so I am wondering what datatype they are?
class Plant{
private:
String name;
??? sensorId;
...
public:
readSensor(??? sensorId);
...
};

I want to standardize this so I don't have to physically write 'A0' or 'A1' each time I need to read the sensor.

they are mapped to bytes in arduino

They're uint8_t:
static const uint8_t A0 = 14;
static const uint8_t A1 = 15;
static const uint8_t A2 = 16;
static const uint8_t A3 = 17;
static const uint8_t A4 = 18;
static const uint8_t A5 = 19;
static const uint8_t A6 = 20;
static const uint8_t A7 = 21;

Those are defined in the pins_arduino.h file in the board's variant folder.


text:
read CID of SD card with SD.h library
I would like to be able to read the serial numbers of SD cards using the SD.h library. Only reading the values is enough, I am not looking to modify the CID.
This should be possible but I do not have the programming skills to get it running.
I am using an esp8266 and already have the SD card running and working correctly. Only the chipselect needed to be modified for the SD library to work.
So far I have found this in Sd2Card.h
      /**
   * Read a cards CID register. The CID contains card identification
   * information such as Manufacturer ID, Product name, Product serial
   * number and Manufacturing date. */
  uint8_t readCID(cid_t* cid) {
    return readRegister(CMD10, cid);
  }
  /**

And in Sd2Card.cpp there is this:
/** read CID or CSR register */
uint8_t Sd2Card::readRegister(uint8_t cmd, void* buf) {
  uint8_t* dst = reinterpret_cast<uint8_t*>(buf);
  if (cardCommand(cmd, 0)) {
    error(SD_CARD_ERROR_READ_REG);
    goto fail;
  }
  if (!waitStartBlock()) goto fail;
  // transfer data
  for (uint16_t i = 0; i < 16; i++) dst[i] = spiRec();
  spiRec();  // get first crc byte
  spiRec();  // get second crc byte
  chipSelectHigh();
  return true;

 fail:
  chipSelectHigh();
  return false;
}

So it seems that the underlying code has been prepared in the library already, my question is how would I include it into a sketch like CardInfo.ino?

The method is visible from within your sketch. You just need to first create a cid_t struct like this in your sketch:
cid_t cid;  // at the top with the other globals

Then call readCID() anywhere in setup() after the card has been initialized.
card.readCID(&cid);
Serial.print("Serial number: "); Serial.println(cid.psn); // psn is the serial number field of the struct

Check out SdInfo.h for the other struct members.

Thank you, this is working for me and the explanation easy to follow. I tried additional information and can also read it. The SdInfo sketch is much better but it wouldn't run on my hardware, but I can see now how to use it as an example. Thanks again.


text:
Arduino micro not recognized
I have an Arduino micro for some time and everything always worked well. Today, when I was uploading a code on this board using Arduino IDE, I accidentally started the Arduino Board update and the upload failed. After a while I retried again and again and again but upload always failed. Now my PC doesn't recognize my board and, looking at Windows Device Manager, when I connect my board, appears this screen:

What should I do? Do I have to reflash bootloader?

You have a bad sketch installed. Press reset just before upload starts.

to expand on that, whats worked for me in the past is press and hold the reset button while the sketch compiles, and only release the reset button once the IDE is trying to upload. that way it should never get out of the bootloader, so should immediately upload the new sketch

I tried again and again resetting it before uploading, after uploading, during uploading, twice, keeping resetted,... but always the IDE says that the board is not connected. Every time I reset, the led blinks once but nothing happens. What should I do?  @Majenko

You may want to reinstall the bootloader - not to repair the bootloader, but to erase the sketch. A major drawback of the bootloader is that it has no proper manual way of forcing it to run.

Ok and what should I do? Thank you for your time!

Are you sure it is a "micro"? Can you show a photo or give a link to the board? When it is a board with a atmega32u4 microcontroller than a bad sketch can indeed lock it. For example sending a lot of data to the serial port without delay in the loop(). Pressing the reset button (and releasing it at the right time) needs some practice, it has to be at exactly the right time. If nothing helps then you could burn a new bootloader in it. I had to do that a couple of times with a bad sketch for a arduino leonardo, micro and pro micro. Use a programmer or arduino uno as isp to burn a new bootloader.

So I was facing this issue for the past few hours and this is how I managed to get it to work.
After reading similar issues on knockoff NANOS,  I downloaded and installed this as many knockoff NANOS uses a different Serial CHIPSET.
After that, on the IDE side, just press compile to ensure your code is good to go. And then when you hit upload, wait for it to finish compiling and the second it says UPLOADING, hit the reset button. It should upload now and be available in your COM port.

I had this issue a while back and in order to fix it as suggested above I had to re flash the boot loader using a 2nd Arduino as an ISP. I used this page as a guide:
https://schou.dk/linux/arduino/isp/
Before connecting the wiring I first updated the UNO with the "ArduinoISP" Sketch, connected the wiring, then flashed the boot loader.

Opps, just realised this was asked 1 year, 9 months ago... oh well hopefully someone finds it helpful


text:
Parse long CSV file with esp8266
I'm trying to write a code for nodeMCU (esp8266 based board) to continuously calculate distance between GPS location and geographical coordinates written in a CSV file in SD. Originally I thought the best way to do it was to parse the file, save the longitudes and latitudes in two arrays at startup and, then, calculate continuously distances between arrays and coordinates taken from GPS. If distance is less than a value, an output warns me. There is only a "little" problem: the file contains 5500 coordinates and, so, it is impossible to allocate two arrays containing 5500 floats inside ram memory. Now I have thought two alternatives:
1) save the two arrays in flash memory that is, I know, a lot slower but also bigger
2) parse and calculate distance line by line continuously: in a loop I'll take the first line from SD, parse it, calculate distance between it and GPS location and, then do the same thing for second, third,... line. It requires the continuous access to SD and parsing but I don't have to use flash memory.
What is the best option in your opinion? Have you got alternatives or suggestions?
Thank you!!

I vote for 1). Is SD card faster then flash? Why not use file with SPIFFS?

I don't know if SD is faster than flash; probably it is. I have never used spiffs so I am a little bit scared on how to use it. Have you got suggestions?

Can I only save .txt files inside SPIFFS or also arrays? If I save, for example, a .txt file with coordinates, I need to reopen it and parse it again, will it be convenient? Maybe I can use option 2 with SPIFFS instead of with SD

I moved the comments to an answer

use an ESP32 instead: ~6X the usable RAM of the 8266

@dandavis at the end I decided to save file in SPIFFS, parse line by line and calculate distance line by line. It only takes 6 seconds at 160MHz; it's acceptable for what I want to do. Thank you anyway.

Instead od the SD card you can use the esp8266 file system SPIFFS. It uses the flash of the esp8266, which is connected at 40MHz as Quad I/O on newer systems.
To use SPIFFS you create a folder named data in your esp8266 sketch folder. You put the files in that folder and then you use the SPIFFS upload plugin.
In runtime use the SPIFFS library. It is similar to SD library.


text:
Pressure Sensor-MPX10DP with amplifier and Arduino UNO - output to kPa
I'm working with an Arduino UNO. I'm trying to use this Sensor to obtain the pressure in kPa. I'm using a tl084cn to amplifier the signal. But I don't know what values I'm getting and what to do with them.
Not applying  pressure prints 0, if I apply air pressure it's goes up to 800-900 as max. What mean this values?
What is the maximum pressure that I should get? 10 kPa? I don't understand that very well. Because the data sheet says:

Maximum Pressure (P1 > P2) PMAX 75 kPa

I can understand what is the differences between Max. Pressure and Max. Differential Pressure.

Your previous question: https://arduino.stackexchange.com/questions/40234/how-to-connect-a-pressure-sensor-mpx10dp-to-an-arduino The TL084 is not an instrumentation amplifier. The MPX10DP can measure from 0 to 10 kPa differential pressure and it breaks at 75 kPa differential pressure. The sensor output has a offset of 20mV and a range of 35mV. When no pressure is applied, you measure the offset.

@Jot So, I can't use the TL084 to amplify the output?

You can amplify the signal with a TL084, but depending on the circuit the impedance of the circuit could influence the bridge output of the sensor. Measuring the exact pressure would be disturbed. The output impedance of the sensor is about 1 kΩ. Are you really determined to get into more and more trouble instead of buying a MPX5010 ? With a MPX5010 all your troubles are gone at once.

@Jot, the problem is that in my country there is no place to buy a MPX5010, that's why I was trying to accomplish it with this sensor from my college laboratory.

And what about a INA125 or similar instrumentation amplifier ? Those are made for wheatstone sensors. Or what about an Arduino Leonardo or Arduino Mega 2560 ? Those have internal differential mode with a gain, that is somewhat similar to a instrumentation amplifier.