text:
Question about configuration EEPROM or Flash
I want to make an external (not related to Arduino) computer application that creates a big 'setup file' (like max. 64 KB). This setup file contains lookup tables (which are configurable and the tables with data themselves).
This 'setup file' needs be stored in the Arduino.
Now I thought of the following alternatives:

Somehow let end users use the computer application to store the setup file they created into the Arduino's extended EEPROM (I will add a 64KB EEPROM for this). However I don't know if a computer application can be made that can do this (i.e. store the information to EEPROM).
Do like above, but store it in Flash (as far as I know, only the Arduino computer application can do this, to send a sketch to USB).
Create an application that 'adds' the setup file to the sketch. However, probably end users cannot store it in the Arduino without the Arduino software which is unwanted.
Use a SD card and read information from there; however, I read 512 bytes SRAM is needed.

To make it more complicated, I want the Arduino sketch to handle like reading on average 50 random bytes from the storage the setup file is stored, and perform several algorithm (not so difficult but still) and do this in max. 10-20 ms.
Can you please give me some more information which alternative would work or not? Or maybe I missed out something trivial or an alternative is impossible?

Somehow let end users use the computer application to store the setup file they created into the Arduino's extended EEPROM (I will add a 64KB EEPROM for this). However I don't know if a computer application can be made that can do this (i.e. store the information to EEPROM).

Perfectly viable - although an SPI Flash chip would be more appropriate.

Do like above, but store it in Flash (as far as I know, only the Arduino computer application can do this, to send a sketch to USB).

It is the bootloader that can write to flash. I don't thing the main program can write to flash, or it would wipe itself out. You may need a special bootloader with your own protocol and upload program to go with it.

Create an application that 'adds' the setup file to the sketch. However, probably end users cannot store it in the Arduino without the Arduino software which is unwanted.

Perfectly viable, but tricky to say the least.

Use a SD card and read information from there; however, I read 512 bytes SRAM is needed.

Yes, 512 bytes of SRAM, since that is the size of one block on an SD card. But an UNO has 2048 bytes of SRAM - more than enough for SD card support.
The SD card would be my route of choice. It's the easiest from a user's perspective (slip the card into their computer and copy the files), and pretty simple and straight forward to connect and program the Arduino for.

To make it more complicated, I want the Arduino sketch to handle like reading on average 50 random bytes from the storage the setup file is stored, and perform several algorithm (not so difficult but still) and do this in max. 10-20 ms.

If you know where in the file the byte are then you can seek() straight to them. Takes almost no time. 20ms is an eternity for a microcontroller.

Thanks for these great answers! I have one additional question, 20 ms is an eternity ... wondering if reading like 20 blocks (of 512 bytes) can be done too from an SD card within 20 ms?

10K might be pushing it - especially as you can't store that data - you'd have to be processing it on the fly.

Thanks very much ... Maybe I can store the (useful) data... or maybe even better: I can store a lot of data with the computer application and read it for the Arduino in the most easy way.

Not sure what it is you are trying to achieve, but if you are going to use an SD card, you've got a very very large amount of storage available. You could maybe do some pre-processing on the data before storing it on the SD card. Create multiple versions of the file that are pre-randomized. Similar to what  rainbow-tables do; use more diskspace, to lower computation time.

Yes, something like that sounds good... I will add a bit of what I need in my question as background.

@Majenko you say 20 ms is an eternity but I asked a more detailed question about the speed in http://arduino.stackexchange.com/questions/35610/how-fast-is-a-sd-page-read-from-a-file/35611?noredirect=1#comment70985_35611  and it shows the speed is about 200 KB/s which means one 512 byte page to read in 2.5 so I can read like 8 maximum per 20 ms?


text:
#define above static const int?
I see a lot of people, but also libraries, defining constants (like pin numbers, length of items etc) as #define:
#define LENGTH 5

While it is recommended to use in this case static const int:
static const int LENGTH = 5;

I did a test and for memory it does not make a difference.
Is there some specific Arduino reason why #define is (mis)used so often?

Old habits from plain C?

@EdgarBonet I was already a bit 'afraid' of such remark.

People copying examples from people that have bad habits, or learned from people with bad habits.

I would use a byte for values that are <=255, save on memory.

@CrossRoads You are right ... although I use mostly int's when I just want to test something, for a program where I expect (even in future) that memory is an issue (which is very fast for an Arduino) I use smaller types. In this case it doesn't matter, it doesn't use any SRAM memory.

For numbers, certainly, const <type> is preferred.  This is chiefly because it imposes a type (which would only be optional for a #define), which can have a knock-on effect for mathematics.
That's not to say that you should always use const <type> instead of #define.  #define has its place.
One of the benefits of #define over const <type> is that it is a direct literal text replacement. The replacement is done before the compilation, so anything that is valid in your code can be put in a #define, whereas only things which evaluate to the correct type at runtime can be placed in a const <type>.
Take strings for example.  Yes, you can use:
const char *foo = "This is text";

And you can use that wherever a const char * is expected.  However, if you use:
#define FOO "This is text"

you can use it anywhere a string literal is expected.  That makes for useful things such as C's way of concatenating string literals at compile time:
Serial.println("I say: " FOO);

The two string literals "I say: " and FOO (which expands to "This is text") are concatenated into a singe string literal at compile time into:
Serial.println("I say: This is text");

You can't do that with const char *.
Another big difference with const <type> compared with #define is when expressions are evaluated.  Take for example:
const float sinpi = sinf(3.141592653);

That will calculate the sine of PI once at startup. However:
#define SINPI sinf(3.141592653);

will calculate the sine of PI every time it is used.
So in this instance const float not only gives you an imposed type of float for all calculations, it also reduces calculation overhead by only running the calculation once and saving the result.
So as you can see there are pros and cons to each.  But in general, for numbers:

const <type> is preferred for storing internal numerical data that doesn't change, and
#define is most often used for user-configurable data, since it doesn't impose the ; at the end of the line which often gets forgotten by (newer) users.

Thanks for the insight ... the last remark is 'interesting' (forgotten by newer users).

even though it is not directly related to the subject of the question, perhaps you could mention the use of #define for conditional compiling

source: Stack Exchange

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

sort: votes


text:
Does DmxSerial stops interrupts?
I am trying to build a setup with an Arduino Mega, having a DMX output (using DMXSimple library), and a MIDI library (to be done).
I was wondering, if I get into problems. According to This question, where Majenko's answer mentions that FastLED holds interrupts, I wonder if I can get into problems if I try to read MIDI data from 3 serial ports while sending DMX.
Probably FastLED (for led strips) and DMX (250 kbps) have some similarity. DMXSimple works with just one data line (no UART), but MIDI is using UART (31.25 kbps), 3 UARTS.
My fear is that everything works separately (I tried it before, long time ago with MIDI), but when I try to combine it, I get timing problems.

Yes, it does disable interrupts when sending a byte:
#if defined(__AVR__)
void dmxSendByte(volatile uint8_t value)
{
  uint8_t bitCount, delCount;
  __asm__ volatile (
    "cli\n"                            <<==== DISABLE INTERRUPTS
    "ld __tmp_reg__,%a[dmxPort]\n"
    "and __tmp_reg__,%[outMask]\n"
    "st %a[dmxPort],__tmp_reg__\n"
    "ldi %[bitCount],11\n" // 11 bit intervals per transmitted byte
    "rjmp bitLoop%=\n"     // Delay 2 clock cycles.
  "bitLoop%=:\n"\
    "ldi %[delCount],%[delCountVal]\n"
  "delLoop%=:\n"
    "nop\n"
    "dec %[delCount]\n"
    "brne delLoop%=\n"
    "ld __tmp_reg__,%a[dmxPort]\n"
    "and __tmp_reg__,%[outMask]\n"
    "sec\n"
    "ror %[value]\n"
    "brcc sendzero%=\n"
    "or __tmp_reg__,%[outBit]\n"
  "sendzero%=:\n"
    "st %a[dmxPort],__tmp_reg__\n"
    "dec %[bitCount]\n"
    "brne bitLoop%=\n"
    "sei\n"                             <<==== ENABLE INTERRUPTS
    :
      [bitCount] "=&d" (bitCount),
      [delCount] "=&d" (delCount)
    :
      [dmxPort] "e" (dmxPort),
      [outMask] "r" (~dmxBit),
      [outBit] "r" (dmxBit),
      [delCountVal] "M" (F_CPU/1000000-3),
      [value] "r" (value)
  );
}

Also that routine is run from within a timer interrupt routine. On AVR with no interrupt priorities even without disabling interrupts it would still be blocking all other software from running.

Thanks for answering so fast, do you think it could give problems to MIDI input? 3 serial ports, 31 kbps? Or is this so slow, the MIDI will be handled between calls to dmxSendByte of this library?

It's not the baud rate that is a problem, but how rapidly bytes arrive. There has to be time to put the incoming byte into the RX buffer before the next byte arrives, and DMXSimple will end up creating windows where that can happen. If you have two bytes arriving between windows then one will be lost.

Ok (I hope because I use hardware UARTs, the RX buffer will be filled before this problem happens. Anyway, I will do some testing of 'simultaneous' MIDI and DMX together. Thanks for the insights.

There is (IIRC) only one byte of hardware RX buffer. It has to be emptied by the RX interrupt before the next byte arrives.

Ok ... that means thus 32 us, but that seems longer than the time for executing those 20 instructions ... so it could be ok :-)

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


text:
Printing bitmap image from thermal printer using Serial input
I want to print Bitmap image from thermal printer, but image data is from Serial Input. But I am not getting valid print. What wrong i am doing ?
Here is code i wrote
#include "Adafruit_Thermal.h"
#include "SoftwareSerial.h"
// PIN 6 -> Yellow
// PIN 5 -> Green
// GND -> Black

#define TX_PIN 6
#define RX_PIN 5

SoftwareSerial mySerial(RX_PIN, TX_PIN);
Adafruit_Thermal printer(&mySerial);

int count =0;
void setup() {
  pinMode(7, OUTPUT);
  digitalWrite(7, LOW);
  mySerial.begin(9600);  // Initialize SoftwareSerial
  printer.begin();        // Init printer (same regardless of serial type)

  Serial.begin(9600);
  Serial.print("1");

  //printer.printBitmap(384, 5, image);

  //printer.feed(2);

  printer.sleep();      // Tell printer to sleep

  delay(3000L);         // Sleep for 3 seconds
  printer.wake();       // MUST wake() before printing again, even if reset
  printer.setDefault(); // Restore printer to defaults
}

void loop() {
    if(Serial.available()>48){
      uint8_t image[50];
      Serial.readBytes(image,48);
      printer.printBitmap(384, 1, image);
    }

}

Does the example sketch print a logo? Why do you put your printer to sleep? What printer model do you have? Also a single line bitmap is kind of easy to miss.

Yes i can print the logo, It was old code so i didn't bother to disable it,
I have https://www.adafruit.com/products/597. I tried printing 5 lines of bitmap so i have idea how small it would be that is why i sent multiple lines a complete 402px height image. i.e. 402 rows

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


text:
Using N mosfet to switch ESC to BLDC phases
I have an ESC that powers 36v 3 phase BLDC motor. The ESC has limited functionality and can power motor only in one direction. If I switch manually two of the ESC to Motor phase connections, than the motor direction will change. Now, I want to do the same i.e. switching phase to phase connections with 4 power mosfets.
As in scheme, the blue ESC phase will be connected to Mosfet source and the drain will be connected to Motors yellow phase. The next mosfet will connect to ESC yellow at source and motor blue at drain.  Two other mosfets will connect blue to blue and yellow to yellow.
I won't  do the switching while motor is on so I assume it should be safe.
How can I connect MOSFET's gate to Arduino ?
I need no pwm just ON/OFF.

you want a "mosfet driver", opto-isolated if possible. i make my own with 3 red LEDs in series used as a photovolatic source driven by a white LED at 3.3v, which results in ~5v output. then the red cathode is connected to source, and the annode to gate. that way, there's no electrical connection to the MCU and Vgs never gets far from Vd... A small solar cell can work as well, light it with the MCU.

the Mosfet I am using is logical level so the gate voltage is about the same as  arduino output

well if you can share the ground with the MCU it's not an issue; but if you have to power it inline, you need to watch the max VGS

This is not going to be practical given that you basically need to switch AC power, you would far, far, far better off getting a bidirectional ESC or seeing if it is one of those which can have an unofficial aftermarket open source firmware installed.  Additionally, this is an electronics question that has nothing really to do with Arduino.

if it's AC, you need two mosfets back to back to allow current in both polarities.

@dandavis and a non-trivial drive structure.  The AC signals the poster wants to switch are each already coming from a MOSFET half-bridge sourced from an actual DC rail; what should be changed is the software controlling those - doing it afterwards is awkward enough to eliminate any gain over using a suitable bidirectional ESC to start with.

This is covered fairly well in an EDN.com “MOSFET pair makes simple SPDT switch” article.  You would use two of the SPDT circuits to make a DPDT.  Attach switch commons to yellow and blue, and attach the “switch points” of one circuit to motor yellow and blue, and those of the other vice versa.  Attach both control pins to one Arduino IO pin.  The picture below comes from the referenced article, which shows the circuit in use for a primary-power vs secondary-power application.   See the article for details.

Sorry I can't still understand the control part. In most switch schemes I have seen the MOSFET is used on ground wire, and the mosfet source is connected to arduino ground. But in case the source/drain is V+ how can  arduino & mosfets have common ground?

@Naho, I don't know.  The capacitor may be related to having a common reference.  But l guess I don't know enough about the ESC wiring to know whether grounds can be common.  You might have to use optoisolators as someone suggested.

This will not work, the requirement is effectively for an AC switch.  Driving two of them in complement is the trivially easy part.

authors: Георгий Победоносцев

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


text:
Switching low current AC
What is the simplest way to switch ON/OFF a 60v and 5 mA of current ?
I don't want the common relays for arduinos as they make click noise.

Solid State Relay (SSR)?

e.g., Fotek SSR-10 DA for next to nothing on eBay...

Is there something smaller than SSR ? maybe Triac or similar

That's basically what is inside the SSR. A triac and a bit of control circuitry. BigClive does a teardown of one: https://youtu.be/DxEhxjvifyY

// Following devices could be helpful in you case.

Power BJT as a switch (check datasheets if it comes on your required range).
Solid state relay is obviously, but cast is little high in this case.


text:
How to detect if the arduino wire is still connected
I have hall sensors connected to an arduino, because of mechanical movements there is some possibility that the input wire may accidentally slip out of the arduino analogin sockets. Is there any way I can detect if the wire is still connected to hall sensor  ? I don't want to solder the cables yet.

Schematic and datasheet where?

if the read values don't make sense, or fluctuate wildly, they've become unplugged.

Solder the cables to headers so they don't slip out?

You can maybe try to see if the value on analog pins when sensors are connected (while not sensing anything) is different when not connected.
Depending on your sensors and schematic, if analog input is fluctuating, you can use this command to use pull resistor to avoid this fluctuation.
digitalWrite(Ax, INPUT_PULLUP);

If the above gets true, then you can set up a threshold for detection. Below or beside threshold value, sensor is unplugged.
Otherwise, use some vinyl duct tape.... this would securize the thing a bit!

are you mixing up pinMode constants and digitalWrite, or is this a secret?

this is no secret: link. It may work by writing HIGH instead of INPUT_PULLUP, at least it works when wanting to set the internal pullup resistor for digital input.

Either use pinMode(Ax, INPUT_PULLUP); or digitalWrite(Ax, HIGH);. It will work either way, but it's no good programming practice.

What would be the best programming practice to enable an input pull-up on arduino? Other than accessing the proper register directly?


text:
How to calculate step delay?
I'm struggling with get suitable step delay while driving a stepper motor.
How to calculate exact step delay for 1.8deg/step stepper motor?
Give some example calculation.

Convert the RPM of the motor to RPS.
Take reciprocal to get seconds per revolution.
Divide it by 360 to get seconds per degree.
Multiply by 1.8 to get seconds per step.

How to calculate exact step delay for 1.8deg/step stepper motor?

each rpm = 360 degrees * rpm / 60 second.
So the time, between each step, is resolution / (60 * rpm), where resolution = 1.8deg/step in your case.


text:
Port manipulation in Arduino using byte value
I'm trying to write PORTB and PORTD in ATmega328P using byte system like this,
    //  PD7  PD6  PD5  PD4  PD3  PD2  PD1  PD0
    //  N     N    N    N    N    U    U    U
    //  7     6    5    4    3    2    1    0
    //======================================
    //  PB7  PB6  PB5  PB4  PB3  PB2  PB1  PB0
    //  X     X    1    1    1    1    1    1
    //  C     C    13   12   11   10   9    8
    //======================================
    //C-Crystal Pins/U-Un used/N-Used/X-unknown value

    byte pins[] = {3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};

    //uint16_t style1=1365; //10101010101
    //uint16_t style2=682;  //01010101010

    void setup() {
      for (int i = 0; i < 11; i++) {
        pinMode(pins[i],OUTPUT);
        PORTD=B00000000;
        PORTB=B00000000;
      }

    }

    void loop() {
      PORTD=B10101000;
      PORTB=B00101010;
      delay(1000);
      PORTD=B01010000;
      PORTB=B00010101;

    }

According to this , Port value should be swapped.
But, It's still remaining given value of the code before delay()
What is the problem in this code?

What is the problem in this code?

No problem, it does change the bits of port D and B from 0B10101000 and 0B00101010 to 0B01010000 and 0B00010101 respectively.
However, microseconds later loop() runs again and changes them back to  0B10101000 and 0B00101010 for a full second.
To better see what's happening, add a second delay(1000); statement, placing it just before the closing brace.

Ops,,,I really know about that.But,I have forgot that.,Im  very mad. Thank you.


text:
Send a file from PC to Arduino using HC-06 module
I want to send a file from my Laptop using its own Bluetooth transmitter to Arduino. Arduino has HC-06 module as receiver.Arduino has SD Card fore store the file.
I was able to send bytes using Python application.
How to send a file using a Python application to Arduino?

What kind of file?

Open the file in rb mode in your Python code.
Since the Arduino SoftSerial RX buffer is 64 bytes in size, sending 60 bytes per packet to the Arduino is okay. You basically call out = file.read(60) in python to read 60 bytes from the file and then write these bytes to the Arduino with ser.write(out). You can have the python program wait for acknowledgement from the Arduino, perhaps indicating how many bytes it actually received (after a given timeout period) or what byte was last received. This is just very minor error detection.
The Arduino saves the 60-byte packet to an array and writes everything at once to a file on the SD card, that you've already opened.
After receiving acknowledgement from the Arduino, the Python program reads the next 60 bytes and forwards to the Arduino like before. Continue till the file is exhausted. You could send some sort of signature byte to inform the Arduino that no more bytes are coming and to close the file. Alternatively, a timeout period can be used.

Note: It'll be more efficient if you wrote to the SD card in chunks, where the chunk size is a factor of the card's sector size. 64 bytes is the highest you can do with the default RX buffer size, but thats living dangerously as you risk buffer overflow if anything goes bump.
This can be avoided though, by reading bytes from the RX buffer and into your own array, as soon as they arrive.
Chunks of 32 bytes is safer but it will naturally take longer to send the whole file. Test and judge for yourself.

Draining the buffer shouldn't be a challenge if the Arduino is ready, and it may be more useful to operate in chunks that divide evenly into a sector on the card.

@ChrisStratton like 64 bytes, you mean? I just used 60 for some redundancy. Its easier to test this way and if it all works, optimize it. I'll edit though.

I'd personally be trying to avoid the situation where the serial buffer is holding much at all, by making sure the program is able to drain data promptly.

@ChrisStratton Just realized I strayed off...I get your point.


text:
Get production count for current minute
I am trying to make a production counter for a machine. I want to display production count of the last minute for each seconds. So, display should update every second and should display real value of last 60 seconds.  I have a system for detect real-time product output and get it to the Arduino using digital input pin.
I wrote below codes and for that.
what I have done is count output and get output per second. Then store it on an array as separated value for each seconds. Every second the array updated and added new value for current second. At last add all count value of last 60 seconds and output as production rate of current minute.
My question is, Is there any easy and efficient way for do this without using few variables ?
    #define countSensor 8  //count sensor input

    uint8_t records[60];
    uint8_t countSensorState = 0;
    uint8_t totalCount = 0;
    uint8_t countOfLastSec = 0;
    uint8_t lastCount = 0;
    uint8_t lastMinCount;
    uint32_t preMills = 0;

    void setup() {
      Serial.begin(9600);
      //init sensor input pin
      pinMode(countSensor, INPUT_PULLUP); //change according to sensor type

      //clear random value of memory locations
      for (int i = 0; i < 60; i++) {
        records[i] = 0;
      }

    }

    void loop() {
      //get count at falling edge
      if (digitalRead(countSensor)^ countSensorState) {
        if (!digitalRead(countSensor)) {
          totalCount++;

        }
        countSensorState = digitalRead(countSensor);
      }
      //get count of last second
      if (millis() - preMills > 1000) {
        preMills = millis();
        countOfLastSec = totalCount - lastCount;
        lastCount = totalCount;
        //record last 60s counts
        //--shift back a second in the array
        for (int i = 0; i < 59; i++) {
          records[i] = records[i + 1];
        }
        //--record current second in array at 59th index
        records[59] = countOfLastSec;
        //get last 60s count
        for (int i = 0; i < 60; i++) {
          lastMinCount += records[i];
        }
        Serial.println(lastMinCount);
      }

    }

If you really need the total of the last 60 seconds, then yes, you have to store that array. If you can live with something like an exponentially weighted moving average, then only the previous value of the average has to be stored.

you don't need to shift the values .... index the array in circular manner

@jsotola I couldn't get it correctly. How can I apply circular array to my code? Could you give me a modified code...

right now you use for loop to iterate the array using a pointer i ....  remove the for statement ... use i++ every second instead ... count 0 1 2.. 59 0 1 2 ....

As I said in a comment, if you really need to compute that moving sum,
you absolutely need to store the last 60 one-second counts in memory.
That being said, there are a few small issues with this code for which I
would have some suggestions:

There is no point in storing totalCount. You do not really use it,
and it will eventually overflow.

You do not need to explicitly initialize all globals to zero, as that
is implicitly done by the runtime: it is a requirement of the
language.

Your are calling digitalRead(countSensor) three times in a row. The
logic for counting edges is sound as long as the three calls yield the
same result, but that is not guaranteed. It is safer to only read the
pin once per loop iteration.

Similarly, the two calls to millis() can yield different results,
and that will make your timings slightly off.

The condition millis() - preMills > 1000 will only fire when
1001 milliseconds have elapsed. Because of the way millis() works,
sometimes you will miss the 1001th millisecond, and process on the
1002nd millisecond. In order to avoid accumulating these small timing
errors, it is best to update preMills by always adding exactly 1000.

As pointed out by jsotola, you do not need to shift the array: you can
instead reuse the array cell that holds the data you do not need
anymore.

You do not need to perform the whole sum every time. You can instead
update the previously computed sum by removing the count of the second
that falls off the current one-minute window, and adding the count of
the current second.

Here is my attempt at applying all the above suggestions. Warning: it
has not been tested.
const uint8_t countSensor = 8;

uint8_t record[60];       // last 60 one-second counts
uint8_t currentIndex;     // current index in record[]
uint8_t oldSensorState;   // previous state of countSensor input
uint32_t previousSecond;  // last time we printed minuteCount
uint8_t thisSecondCount;  // count of items in the current second
uint16_t minuteCount;     // count of items in the last minute

void setup() {
    Serial.begin(9600);
    pinMode(countSensor, INPUT_PULLUP);
}

void loop() {
    // Count falling edges.
    uint8_t sensorState = digitalRead(countSensor);
    if (oldSensorState == HIGH && sensorState == LOW) {
        thisSecondCount++;
    }
    oldSensorState = sensorState;

    // Update stats every full second.
    if (millis() - previousSecond >= 1000) {
        previousSecond += 1000;

        // Update minuteCount by removing the second that falls off
        // the window and adding the one that enters the window.
        minuteCount += thisSecondCount - record[currentIndex];

        // Replace the count that is not needed anymore by
        // the current one.
        record[currentIndex] = thisSecondCount;

        // Start counting a new second.
        thisSecondCount = 0;

        // Update current index, wrapping at 60.
        if (++currentIndex >= 60) {
            currentIndex = 0;
        }

        Serial.println(minuteCount);
    }
}


text:
Memory organisation of MIFARE 1K
I'm trying to use a MIFARE 1K RFID card with RC522 RFID reader/writer for my college project.
I'm trying to understand about memory organization of MIFARE 1K.A documentation() that supplied with a RFID Arduino library() says like this.
I will very appreciate if someone explain me this portion clearly.

The MIFARE Classic 1K offers 1024 bytes of data storage, split into 16 sectors; each sector is protected by two different keys, called A and B. Each key can be
  programmed to allow operations such as reading, writing, increasing valueblocks,
  etc. MIFARE Classic 4K offers 4096 bytes split into forty sectors, of which 32 are same size as in the 1K with eight more that are quadruple size sectors. MIFARE Classic mini offers 320 bytes split into five sectors.
  For each of these card types, 16 bytes per sector are reserved for the keys and access conditions and can not normally be used for user data. Also, the very first 16 bytes contain the serial number of the card and certain other manufacturer data and are read only. That brings the net storage capacity of these cards down to 752 bytes for MIFARE Classic 1k, 3440 bytes for MIFARE Classic 4k, and 224 bytes for Mini. It uses an NXP proprietary security protocol (Crypto-1) for authentication and ciphering.

Accordind to above quote,

For each of these card types, 16 bytes per sector are reserved for the keys and access conditions and can not normally be used for user data.
  Blockquote

Explain how to divide 1024 bytes like this.It has 16 sectors.So,total memory should be 16*16=256 bytes.This is impossible. Please explain this.

You're reading (and doing your sums) backwards.
You have 1024 bytes of data space.
That data space is split into 16 sectors, so 1024 / 16 = 64 bytes per sector.
Each sector has 16 bytes reserved for keys etc, so each sector has 64 - 16 = 48 bytes of user data space.
48 bytes of user data space per sector multiplied by 16 sectors is 768 bytes.
Incidentally 1024 - 768 = 256, which is what you were calculating before.  What you calculated was the amount of the 1024 bytes that is reserved in total for the keys and access controls.

Thanks @Majenko...I haven't read this clearly..It's very simple.Thanks for explanation.

Divide 1024 bytes into 16 sectors -
1024 bytes / 16 sectors = 64 bytes per sector

The first 16 bytes of each sector are used for 'management' and thus reserved. This leaves -
64 - 16 = 48 bytes (per sector) for general storage

Ops..Thanks friend.I have not read this clearly.Thanks

There is also an excellent graphic of the various mifare card layouts, that someone has put together: https://upload.wikimedia.org/wikipedia/commons/thumb/3/39/MiFare_Byte_Layout.png/220px-MiFare_Byte_Layout.png

this is a large image
https://upload.wikimedia.org/wikipedia/commons/3/39/MiFare_Byte_Layout.png


text:
Can Arduino Uno's serial handle to foward push through 1-wire protocol?
tl;dr on on digital ouput/input I would like to communicate with a 1-wire device, whose protocol requires precision to ~15 microseconds. My question is if Arduino Uno's serial communication can be as quick as to support to map the digital pin via serial->USB to my host computers app which should implement the 1-wire protocol?
long version
The mode in which I thought to use my Arduino was, to attach it to a host computer and run the logic of what should be done on the host computer, having the Arduino only receive the data (for the pins) and return the state of the pins.
The challenge which prompts me to this question is that the Serial communication is not really that quick, compared to the timing requirement of some protocols (e.g. 1 wire) I wish to implement.
For example: 1-wire-protocol's timing requirements (i.e. range of micorseconds) could easily be kept from code running on the Arduino Uno's Atmega328 directly, which at 16Mhz and assumed 2 cycles per command would allow somewhat a resolution of 2/16Mhz = 0,125 us.
If alternatively the data/instruction for the 1-wire protocol should be mapped via the serial interface to an application running on an PC attached to the Arduino I wonder if the time requirements of the 1-wire protocal can be reached?
It boils down to a question if the Serial communication can have a temporal granularity as small as the about 1 to 15 microseconds needed to implement the 1-wire protocol - not within arduino itself - but in the attached PC's application.

Ok, so there's two issues at stake here.

Can the Arduino generate a 1-wire protocol with enough accuracy?
Can you transfer the data fast enough through the UART to tell it to do that generation?

You can't just stream a 1-wire protocol through serial and expect it to work.  The low-level serial protocol would very much get in the way.  So you have to send instructions to the Arduino to say "Raise the IO pin" and "Lower the IO pin" and "Tell me when the IO pin changes level", and "Set the IO pin to input" etc.
Each of those actions would be a discrete item that you would have to send.  Given that you could have a single byte per action (send "I" for set to input, send "O" for set to output, send "L" for set to low, etc - Arduino sends "H" if the pin goes high, or "L" if it goes low, etc), what kind of response could you expect?
Well, at 8 bits + start + stop per byte (so 10 bits) at a good fast rate (say 1MBaud), you would expect one byte to take (1/(1000000/10) = 0.00001s (10µs) to transfer.  That's raw transfer speed.  On top of that you then have to add the processing of that incoming data - the Arduino adds it to a circular buffer to allow your sketch to read it, and that takes time, and your program then interpreting it, you could expect a latency of say 15µs.  At maximum stream rate (no breaks between characters being sent at all) you would have a basic granularity of 10µs (processing the last incoming character while the next one is being received).
That's not counting any other factors such as the UART buffers on your computer, latency before the character even gets to the USB port's endpoint, etc.
So all in all there might be a slim chance that you could do it, but it would be very slim and not easy to achieve a stable result.
Far better would be to implement the 1-Wire protocol on the Arduino and just send/receive the control information to tell it to go ahead and do the work and return the results.  After all, that's what the Arduino is designed for - low level interfacing like that.

I was fearing as much. I do loath somewhat to implement anything on the Arduino itself, because its limitations with multitasking, ideally I would have simply done the heavilifting on a PC and abuse Arduino via Serial simply as a way to set/get the pins (somewhat in bitflash or firmata style). your answer was helpful.

Your idea seems wrong-headed, if I may say so without giving offence.
The Arduino is quite capable of generating 1-wire protocol. It certain reads it easily enough with bit-banging.
Trying to send down HLHLHHHLL through serial because your PC is "more powerful" is just not the right way of doing it. Next you'll be wanting to generate PWM on the PC and have the Arduino relay it to an output pin.
Remember, the Arduino (Uno) runs at 16 MHz. The original IBM PC ran at 4.77 MHz (if I remember correctly) so you can regard the Arduino as being as powerful as an early PC.
The simple solution is to send from the PC the data you actually want communicated by 1-wire, and let the Arduino do the actual bit-banging.

You suggest well and I do appreciate Arduino and the Atmega328. Yet I think the IBM PC had longer registers (less cycles whenever 16bit/32bit.... calculations where done) and most importantly no 2000 Byte ram, which makes attempts to schedule multitasking and implementing bigger things, challenging for people not yet as good in reducing memory as me. thank you

It certainly is possible for an Arduino to do this.  For example, source code for Atmel's implementations of 1-Wire protocol via bit-banging, via polling UART, and via interrupt-driven UART, is available at github.com.
There is a 21-page PDF file, doc2579.pdf, available at Atmel.  It documents how the different implementations work.
However, the notion of communicating faster than serial via the 1-Wire protocol seems like a mistaken notion.  As I understand it, the serial implementations above use one serial character per 1-Wire bit, so necessarily are slower than serial.

thank you for the encouragement. After some research the numbers I figured were. Highest speed of Serial from Arduino Uno Rev3 is 2,000,000 bits per second, which means that a bit takes about 500nanosecs. Becoming available in a package of 1 Byte means 8500=4us. For my intented purpose it would need to work with packages for PORT(B,C,D) and DDR(B,C,D) and PIN(B,C,D) send back, which meant 9 bytes per interaction (forwarding PC-app to Arduino) and would be (ignoring yet any CRC overhead) at 98*500ns=36us and by this breaking the 1-wire required max 15us for sending a logical 1.


text:
Arduino 75kHz output frequency setup
i don't know how to manipulate arduino uno or mega registers and timers to be close to 75kHz output frequency. Could you help please ?

output frequency from where to where?

First you have to compute, from your desired frequency, the number of
CPU cycles per period of the signal:
F_CPU / 75 kHz = 16,000 kHz / 75 kHz ≈ 213.33
Since the timers can only count up to an integer, the closest you can
get is 213 CPU cycles. The frequency you get will then be
F_CPU / 213 = 16,000 kHz / 213 ≈ 75.12 kHz
Now you can configure a timer. I find that the easiest is to use a so
called “fast PWM” mode. Choose one of those modes where the TOP value
can be set with a register, and set it to one unit less than the desired
period: the timer will then repeatedly count from 0 to 212.
Here is an example using channel A of Timer 1 on an Arduino Uno.
The output is on digital pin 9 = OC1A = PB1:
// Configure Timer 1 for PWM @ 75.12 kHz.
DDRB  |= PB1;         // set OC1A = PB1 as output
TCCR1A = 0;           // clear the settings of the Arduino core
TCCR1B = 0;           // ...ditto
TCNT1  = 0;           // clear the timer
TCCR1A = _BV(COM1A1)  // non-inverting PWM on OC1A
       | _BV(WGM11);  // mode 14: fast PWM, TOP = ICR1
TCCR1B = _BV(WGM12)   // ...ditto
       | _BV(WGM13)   // ...ditto
       | _BV(CS10);   // clock at F_CPU
ICR1   = 213 - 1;     // period = 213 CPU cycles = 13.3125 us
OCR1A  = 213/2 - 1;   // duty cycle ~ 50%

You can easily adapt this to any timer on the Uno or Mega. Just avoid
Timer 0 if you are going to use the Arduino timekeeping functions.

I think the answer given by Edgar Bonet is the right one, all things considered, and I up-voted it for that reason.
For S&G, I want to add the following:

The easiest way is to simply use the tone(GPIO,Frequency); command - and there are caveats. BUT, the frequency argument is an unsigned int so the fastest frequency is 65535Hz - it will do you no good for 75kHz.

Using a frequency counter and an UNO (crystal), tone(10,65535); the output was 65556/8 Hz. On a Pro Mini 5V (ceramic resonator as I recall), it was 65540 Hz.

Again, for S&G, I tried this code (and adjusted the number of NOPs) to get as close as I could to 75kHz:

void setup() {
pinMode(10, OUTPUT);
}
void loop() {
here:
  digitalWrite(10, HIGH);
  delayMicroseconds(3);
  __asm__("nop\n\t");
  __asm__("nop\n\t");
  __asm__("nop\n\t");
  __asm__("nop\n\t");
  __asm__("nop\n\t");
  __asm__("nop\n\t");
  __asm__("nop\n\t");
  digitalWrite(10, LOW);
  delayMicroseconds(3);
  __asm__("nop\n\t");
  __asm__("nop\n\t");
  __asm__("nop\n\t");
  __asm__("nop\n\t");
  __asm__("nop\n\t");
  __asm__("nop\n\t");
  __asm__("nop\n\t");
  goto here;
}

The output on the UNO was 75004/6 Hz  - not too bad. On the Pro Mini, the best I could do was 74986 Hz.
Of course, we are talking about square waves.

Note that: 1. You can replace delayMicroseconds() and the train of nop with a single call to _delay_us(). This macro has single cycle resolution: _delay_us(3.4375) delays by exactly 55 CPU cycles with a 16 MHz clock. 2. This approach works better with interrupts disabled. Otherwise you get a small glitch on every timer interrupt. BTW: what does “S&G” mean?

https://www.urbandictionary.com/define.php?term=S%26G picked up the expression for someplace a long time ago :)


text:
How to use php file_get_contents with ESP8266
A part of my project need to get datas from an ESP8266 with php script. I tested this script and i don't know why i can get the datas in an iframe element and nothing with file_get_content function. In iframe element my browser displayes "Hello my friend!" as wanted:
The ESP8266 server mode at 192.168.4.1 address, part of code:
String webpage = "
Hello
";
webpage += "
my
";
webpage += "
friend!
";

String cipSend = "AT+CIPSEND=";
cipSend += 0;
cipSend += ",";
cipSend +=webpage.length();
cipSend +="\r\n";

sendData(cipSend,1000,DEBUG);
sendData(webpage,1000,DEBUG);
sendData("AT+CIPCLOSE=0\r\n", 100, DEBUG);

The php script:

 <?php

 $url="http://192.168.4.1/?cmd=SS,0,0,";
 $lines_string = file_get_contents($url);
 echo htmlspecialchars($lines_string);

?>

If i replace the url by:
$url=https://arduino.stackexchange.com

It works with php script,so what is the issue with the ESP8266 ?

Where does the PHP run? I think your PHP is running on a remote server, while the ESP is on a local network (behind a NAT), with a local IP address. The remote server can't access your local network, while you browser can.

Php script is running on php home server Linux machine. I can send all i want to the ESP8266 by wifi.

Is your home server on the same network (/subnet)? Can you curl/gwet the url from your home server?

No home network. Just php server (localhost) and ESP8266 as access point.

To process the request by php, you must send valid HTTP response. The browser tolerates too much.
String webpage = "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n";
webpage += "
Hello
";

PERFECT !!! I can get "Hello" with

file_get_contents("http://192.168.4.1/?cmd=SS,0,0,");


text:
How to send information from a web-site to the arduino?
I currently have an Arduino Mega + an Arduino Ethernet shield, I would like to know if it's possible to send data to the arduino from a web-site hosted on the shield itself. So that when someone press a Button on the web-site it sends a signal to the arduino to trigger an action. Could anyone kindly help me.

Have you tried typing this question into Google?  There are many, many examples of this being done.

@MarkSmith There aren't in the specific way am trying, and I tried stack since its friendly to me compared to google which will bring me to spam sites, yet I didn't found my answer off google, it wasn't precise.

Yes of course!
First things first - Yes, it is possible to accomplish what you're thinking.
The idea is to create a server on the Ethernet Shield and open the webpage hosted by it on any device and based on the options selected on the web page we can trigger desired actions on the Arduino.
I've modified the web server code of Arduino built-in examples to match your requirements, just upload it and make necessary changes as required, here it is-
#include<SPI.h>
#include<Ethernet.h>

byte mac[] = {
   0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02
 };

 IPAddress ip(192,168,1,199); // Any ip address not on your network.
 EthernetServer server(80);   // Port 80 is default for http.

  int led=2;

  String request;

  void setup(){
    Ethernet.begin(mac,ip);
    pinMode(led,OUTPUT);
    Serial.begin(9600);
   }

  void loop(){

      EthernetClient client = server.available();
  if(client)
         {
       Serial.println("Client is trying to connect......");
       while(client.connected())
       {
  if(client.available())
  {
    char c = client.read();
    request.concat(c);
    if(c=='\n'){
    Serial.print(request);
    if(request.indexOf("ON")>0){
      digitalWrite(led,HIGH);
      Serial.println("ON");
      }

      else if(request.indexOf("OFF")>0){
        digitalWrite(led,LOW);
        Serial.println("OFF");
        }
    client.println("HTTP/1.1 200 OK");
    client.println("Content-Type: text/html");
    //client.println("Refresh: 5");  // refresh the page automatically every 5 sec
    client.println();

    client.println("<!doctype html>");
    client.println("");
    client.println("<title>LED</title>");
    client.print("<!DOCTYPE HTML>
LED ON

LED OFF

" );
    client.println("");
    client.stop();
    request="";

  }
  }
 }

    }

   }

This sketch will turn an LED on or off attached to digital pin 2.
You have to go to the IP address that you provide to the shield (192.168.1.199 in my case). You'll see 2 hyperlinks to switch on or off the led and that would pass a query which the Arduino looks for again and again in the loop and takes action accordingly.
Hope this helps, try this out, and do let me know the result.
NOTE
Make sure that you access the Ethernet Shield from a device within your LAN only otherwise you'll have to use port forwarding.

It work all fine, yet I don't know if it's possible to have another file on the SD card in HTML and CSS to do the same exact thing. Instead of having an entire web-page in the sketch itself.

Obviously that's possible! Give me a day or two I'll help you out

The only limitation to the applications of an arduino is the user's imagination! :)

I completely agree :D I always say that :D 8

Actually I understood what you doing here, you using the URL to determine if the LED is on or off, but I want a way where I can communicate with the arduino from the Web-Site Interface sending and receiving information.

That is what it is,  The process of parsing the url includes the query operator ('?') this operator would take our link and place it in the url under the same domain (IP in our case) and when the server (Arduino) gets the request it toggles the LED accordingly.

Hum isn't there any other way such as Serial to communicate to the arduino from  a web interface.

Let us continue this discussion in chat.

https://startingelectronics.org/tutorials/arduino/arduino-MEGA-24-output-web-server/ I found this article. They did pretty much the same thing using Ajax


text:
Power Arduino Over 9V automatically after being disconnected from USB 5V
Am wondering if there is some way the Arduino can automatically power itself using through the 9v port in case the USB is disconnected, and afterwards if the USB is connected again it stop feeding from the 9v Input.

The anwser is somewhat.
If you connect a 9V battery to Vin, I'll "take over" the power wheter if the USB is connected or not. Note tought that some problems may occur when both are connected at the same time (personnal opinion). See this link for more info.
So in conclusion, if you have a USB, remove the 9V for power efficiency. Once you include the 9V though, it will take over control of the power on the ARDUINO.

Actually the opposite is the case. The USB takes over if the 9V is removed. If 9V is there it is used for power regardless of whether USB is there or not.

@Majenko, good point! I've modified the anwser!

I need the Arduino to power itself when the USB is removed, but not use the 9V if its connected. And this need to be done automatically and not manually.

@Majenko IF I connect Both USB and Power Jack, it's going to choose the power from the power jack over 5Volts. Yet will the serial be available?

@The_Little_Cousin Yes and yes.

@Majenko Powering both USB and 9V Jack won't burn the Arduino. You 100% Sure?

Positive. The Arduino is designed specifically to work like that.

Bro my life gonna be easier ^^ It's gonna open a new world to my Home-Automation project :D Like some post wrote it can burn your Arduino :| But it doesn't according to you :D

If you do home automation, connect use a 5V wallplug. Its more efficient then a 9V battery

@Majenko The Jack input not working, am using the adapter which came with the arduino and its not working at all. :| Its not turning on, nothing connected to it, its powering over USB and I upload a Led Blink sketch this works fine on USB but on the jack alone its not working.

there is one way you can make it.
you can use a temporary capacitor(with a voltage output near to 9v)(or a lipo battery) connected to arduino's voltage input pin and 9v battery connected to arduino with a transistor.
whatever program you are uploading to arduino, you can add a code that reads the serial port, and if serial port is not available then it opens the transistor's gate so as the capacitor gets discharged very quickly the 9v battery takes the job.when it gets the serial port again it closes the transistor's gate and arduino stops feeding upon battery and takes power from USB port.

A lipo connected to Vin is impossible. Vin is connected to the input of the V regulator which needs a voltage more then 7V to operate proprelly.


text:
keypad code is not working and produces wrong numbers
I have the following issues:
1) When i press for example number 7 on the keypad it shows a different number on the serial monitor
2) The servo motor works for any combination of 4 numbers.
Code:
/*http://openhwdesign.comLock system using a Keypad
*/
#include <Password.h>
#include <Keypad.h>
#include <Servo.h>
#pragma GCC diagnostic ignored "-Wwrite-strings"
Servo myservo; //declare servo
Password password = Password( "5523" );

const byte ROWS = 4; // declare the rows of the keypad
const byte COLS = 3; // declare the columns of the keypad

// Define the Keymap

char keys[ROWS][COLS] = {
{'1','2','3'},
{'4','5','6'},
{'7','8','9'},
{'*','0','#'}
};

byte rowPins[ROWS] = {2,3,4,5}; // Connect keypad’s pins to these Arduino pins.
byte colPins[COLS] = {6,7,8}; // Connect keypad’s pins to these Arduino pins.

// Create the KeyPad
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

void setup(){
Serial.begin(9600);
myservo.write(0);
pinMode(11, OUTPUT); //The green led is set as an output.
pinMode(12, OUTPUT); //The red led is set as an output.
myservo.attach(13); //The servo is connected to the digital pin 13.
keypad.addEventListener(keypadEvent); //Add an event listener for the KeyPad

}

void loop(){
keypad.getKey();
myservo.write(180); //why? what happens if you comment it? ###########################
//delay(5);
}

void keypadEvent(KeypadEvent eKey){
// When the KeyPad will be pressed, the results will appear on the serial monitor.
switch (keypad.getState()){
case PRESSED:
Serial.print("Enter: ");
Serial.println(eKey);
delay(10);

switch (eKey){
case '*':
checkPassword(); // Will check the password.
delay(1); // Delay used for stability.
break;

case '#':
password.reset(); //Will reset the password
delay(1); // Delay used for stability.
break;

default:
password.append(eKey); //Append any keypress that is not a ‘#’ nor a ‘*’.
delay(1);
}
}
}
void checkPassword(){

if (password.evaluate()){ //If the combination inserted is equal to the combination saved, the servo’ll rotate.
Serial.println("Accepted");
//delay(5000);
delay(10);
myservo.write(50); //was 140
delay(5000);

digitalWrite(11, HIGH); //Turn the green led on.
delay(500); //Wait 5 seconds.
digitalWrite(11, LOW); //Turn the green led off.

//break; // remove if trial did not work #####################try#####################
}
//break; // remove if trial did not work ##########################################
else{ //If the combination inserted isn’t equal to the combination saved, the servo will not rotate.
//delay(5000); delays response
Serial.println("denied");
delay(10);
//delay(5000);
myservo.write(20); // was 50
digitalWrite(12, HIGH); //Turn the green led on.
delay(5000); //Wait 5 seconds. was 500 ///
digitalWrite(12, LOW); //Turn the green led off.

    }
}

Thank you.

Just change the keys array to get the correct values. The keypad you have is probably wired differently from the one in the article.

The first thing you need to do is just look at what the problem is.  Create a new sketch and paste this code into it.
#include <Keypad.h>

const byte ROWS = 4; // declare the rows of the keypad
const byte COLS = 3; // declare the columns of the keypad

// Define the Keymap
char keys[ROWS][COLS] =
{
    {'1','2','3'},
    {'4','5','6'},
    {'7','8','9'},
    {'*','0','#'}
};

byte rowPins[ROWS] = {2,3,4,5}; // Connect keypad’s pins to these Arduino pins.
byte colPins[COLS] = {6,7,8};   // Connect keypad’s pins to these Arduino pins.

// Create the KeyPad
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

void keypadEvent(KeypadEvent eKey)
{
    // When the KeyPad will be pressed, the results will appear on the serial monitor.
    switch (keypad.getState())
    {
    case PRESSED:
        Serial.print("Enter: ");
        Serial.println(eKey);
        delay(10);
        break;
    }
}

void setup()
{
    Serial.begin(9600);
    keypad.addEventListener(keypadEvent); //Add an event listener for the KeyPad
}

void loop()
{
    keypad.getKey();
    delay(20);
}

You should recognise it, its a reformatted version of your code (pretty code is easier to debug), but with only the keypad bits in.
Now load that onto your hardware and write down what number is shown when you press 1 three times.  Do it three times just to make sure its the same number and you haven't got something totally obscure happening. Repeat for the other 11 buttons.
If 7 and 3 always give you 3 and 6 then you have got your row and column wires crossed.
If 7 always gives you 1 and 9 always gives you 3 then the wires for row 4 and 2 are crossed over. etc
If you can't work out the patter post your findings and I'm sure someone will solve the puzzle.
As for problem 2, don't even go there until you know what you are typing. :)
Hope that helps


text:
Unusual behaviour over serial communication
I am sending data over serial connection from a python script to my Arduino UNO. Now initially whenever I tried to send data to the arduino, it would reset. The fix was to put a 10 microFarad capacitor between the 5V and RESET pins. I did that and everything started working.
Now after while,  mistakenly today I ran the same script without the capacitor between the 5V and RESET pins and for some reason it was working perfectly well. No more resetting when a value was received over serial communication.
Is something wrong with my Arduino?

The reset only occurs if you create a connection. So as long as the python script keeps the connection open, not further resets will occur.

Which OS are you using?

@Majenko Win 10 Home Premium

This reset on connection behavior is ultimately under software control of the host operating system and is usually configurable.  If you can still program the board through this connection (without your modification installed), the hardware is fine.

Knowing the entire setup would help.  For instance, knowing if the RS232 source will drive the Arduino input's dangerously past the Arduino's power rails.
If you have connected a real RS232 signal to the Arduino, the +12 to -12 volt swings could adversely affect the processor.  Causing unexpected behavior.  In such a case you would need a converter like this one.
Over driving inputs is discussed in this Stack Exchange question where the highest scoring answer says:

If you violate the spec sheet normal operating conditions requirements
  you can expect to experience abnormal operating conditions. These may
  range fro perfectly normal opration through complete maloperation...

That answer also links to this tutorial about logic level conversion.
Finally, there is this tutorial which specifically addresses converting RS232 to safe TTL level signals appropriate for a micro processor.

I am connected to a motor driver, which is connected in turn to a motor.

We would need the specifications of the serrial interface. Maybe that could be foubd from the modle number of the motor driver? It is starting to sound like you need the proper interface.

No its not like I'm having a problem here. In fact not having to connect a capacitor between the 5v and RESET pins saves me the hassle of connecting a mini breadboard. Thing is that how can all of a sudden the absolute need of a capacitor between 5V & RESET disappeared?

When driving digital integrated circut inputs beyond the power supply rails, the state of the integrated circuit is indeterminate.

There is no reason to believe the poster is using RS232 signalling at all, especially as if they were they would have had to explicitly hook up a connection between a modem control line and the reset to trigger this, rather than what they did do which was add components to defeat such an apparently forced connection.   All evidence suggests they are using the Arduino's build in USB serial converter, which has such a modem line to reset connection as part of it.


text:
Different time betweenTiny RTC and IDE
I have time late in my Tiny RTC when i try to set time at sketch downloading.
Library: RTClib.h
Setup line:
if (rtc.lostPower()) {
Serial.println("RTC lost power, lets set the time!");
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));

The problem is that my computer displays 15:45 and Serial.print displays 15:12.
How can i fix that ?

__TIME__ is the time the sketch was compiled, not when the board starts running. It was compiled at 15:12, but you applied power at 15:45...?

I compiled and then load the sketch just after. Why so much delay?

Try to Serial.println(F(__TIME__)). This will show you the time that you attempted to set in the RTC, which is your compiler's idea of the current time when it is doing the compilation.

The key here is if (rtc.lostPower()) { -- That is, if the RTC loses power then reset the time to what it was back when you compiled the sketch. If you want to set the time to now then you will need to include some mechanism to either query the time from somewhere or allow the user to set the time manually.

I just removed "if" condition and keep rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
Solved!


text:
Send data to a pc localhost with ESP-01 wifi module
i use a linux machine with a localhost php server installed. Wifi machine is connected to the ESP-01 module (access point mode) and i can send several datas to the Arduino via the ESP-01 set as:
  sendData("AT+RST\r\n",2000,DEBUG); // reset module
  sendData("AT+CWMODE=2\r\n",1000,DEBUG); // configure as access point
  sendData("AT+CIFSR\r\n",1000,DEBUG); // get ip address
  sendData("AT+CIPMUX=1\r\n",1000,DEBUG); // configure for multiple connections
  sendData("AT+CIPSERVER=1,80\r\n",1000,DEBUG); // turn on server on port 80

The php server can send data by GET method and Arduino receives pin=11:
 http://192.168.4.1:80/?pin=11

But, now, i would like to send to the php server datas from the Arduino. I tried this configuration but in my sketch but, it returns, error.
sendData("AT+CIPSTART=0,'TCP','http://localhost',80\r\n",1000,DEBUG);

Serial monitor:
   ERROR
   AT+CIPSTART=0,'TCP','http://localhost/test_php',80

   Link type ERROR

So please, how can i send and receive data with my ESP-01 module?

"localhost" is a name associated with the loopback interface of your computer. That is, 127.0.0.1.
It is not the address of your computer on the network. The only computer that can talk to "localhost" is the computer itself.
Instead of "localhost" you must use the IP address of your computer (or a FQDN that resolves to the IP address of your computer).
And you cannot open a TCP connection to a URL.  You open a TCP connection to an IP or FQDN.
You really should learn the basics of IP networks before trying to write software for them.

Since your PC can communicate with the ESP8266 on 192.168.4.1 I assume that you are running the ESP8266 in SOFTAP mode and you have a WiFi interface connected to that access point. If so that WiFi interface will have a 192.168.4.x address assigned to it.  That is the address you must open with a TCP connection on port 80 to connect to your apache server.
For example:
sendData("AT+CIPSTART=0,'TCP','192.168.4.3',80\r\n",1000,DEBUG);

Then you can craft a suitable HTTP request to send the data.

i replaced localhot by 127.0.0.1. Terminal returns same error Link type

I said not localhost.

And you deleted the protocol.

ERROR
AT+CIPSTART=0,'TCP','127.0.0.1/test_php',80
Link type ERROR

Do you read? I said do NOT use the localhost address. Use the IP address of your computer on the network. And put back in the protocol that you deleted.

Although you are using raw TCP commands to try and acess a URL. YOu want only an IP address in there. And not 127.0.0.1

Learn the basics of networking before you try working with networks.

Sorry, but i'm a beginner with arduino and i try to understand how it works with ESP-01 and distant php server. The ESP is not linked to my house network and i don't want it as. i need more help...

If your PC can communicate with the ESP8266 then there must be some form of network between them.

Yes, pc can send, but how can arduino do the same to the pc?

By opening a connection to the IP address of your PC.

Open command prompt and type ipconfig
Under IPv4 Address you can see IP or your PC.
That IP address is address of localhost(because your PC is a "server" within your local/home network).
Don't forget to config XAMP/WAMP to listen special addresses. And of course if you want use localhost, your PC must be on.

Yes, pc can send, but how can arduino do the same to the pc

Yes, it can. PC(localhost) is server and Arduino is client, like Stackexchange is host and your PC is a client (to Stackexchange). I hope you get it
 The ESP is not linked to my house network and i don't want it as

You can use public server, but you need to Know IP address of the server.

he connects to esp8266 as AP. so not the address on home network, but the address on WiFi interface connected to esp8266


text:
Can't replace SoftwareSerial by Serial1 on Mega board
This sketch runs well with SoftwareSerial define and the monitor displays device modbus values. But now, i want to replace SoftwareSerial by Serial1
and i have no data.
This is the sketch with SoftwareSerial:
#include <SoftwareSerial.h>
#define SSerialRX        10  //Serial Receive pin
#define SSerialTX        11  //Serial Transmit pin
#define SSerialTxControl 40   //RS485 Direction control
#define RS485Transmit    HIGH
#define RS485Receive     LOW

SoftwareSerial RS485Serial(SSerialRX, SSerialTX); // RX, TX
byte byteSend;

void setup()
{
  Serial.begin(9600);
  pinMode(SSerialTxControl, OUTPUT);
  digitalWrite(SSerialTxControl, RS485Transmit);  // Init Transceiver
  RS485Serial.begin(9600);
}
void loop()
{
  delay(500);
  if (RS485Serial.available())
  { for(int i=0; i<7; i++)
    {
    byteSend = RS485Serial.read();   // Read the byte

    Serial.print(byteSend, HEX);
    Serial.print(" ");
    }
  }
  digitalWrite(SSerialTxControl, RS485Transmit);  // Init Transceiver
  byte request[] = {0x01, 0x03, 0x00, 0x00, 0x00, 0x01, 0x84, 0x0A};
  RS485Serial.write(request, sizeof(request));

  digitalWrite(SSerialTxControl, RS485Receive);
  Serial.println(" ");
}

And the sketch i tried with Serial1 (pin 19(Rx) and 18(Tx)):
#define SSerialTxControl 40   //RS485 Direction control
#define RS485Transmit    HIGH
#define RS485Receive     LOW

byte byteSend;

void setup()
{
  Serial.begin(9600);
  pinMode(SSerialTxControl, OUTPUT);
  digitalWrite(SSerialTxControl, RS485Transmit);  // Init Transceiver
  Serial1.begin(9600);
}
void loop()
{
  delay(500);
  if (Serial1.available())
  { for(int i=0; i<7; i++)
    {
    byteSend = Serial1.read();   // Read the byte

    Serial.print(byteSend, HEX);
    Serial.print(" ");
    }
  }
  digitalWrite(SSerialTxControl, RS485Transmit);  // Init Transceiver
  byte request[] = {0x01, 0x03, 0x00, 0x00, 0x00, 0x01, 0x84, 0x0A};
  Serial1.write(request, sizeof(request));

  digitalWrite(SSerialTxControl, RS485Receive);
  Serial.println(" ");
}

Can you help me to find my mistake ?

your code expects 7 bytes after asking if at least one is available

https://majenko.co.uk/blog/reading-serial-arduino

Sorry, but i don't understand what you mean ? Is there  a difference with byteSend length using SoftwareSerial or Serial1 ?

The difference is likely due to SoftwareSerial::read() taking a full character time (appx 105uSec at 9600 baud) because individual bits are collected by the software. With a hardware UART, the ::read() call takes only a few microseconds, since the bits are collected by hardware, without holding up the software (much...). So in the hardware case, loop() can execute the ::read() call much more frequently than characters can arrive. Short answer: in the the software version, you just got lucky!

So what is the best way to solve it, using Serial1?

I tried Majenko advices but nothing on monitor...

You need to wait until everything is transmitted before turning low the control signal. Try to add Serial1.flush() https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/HardwareSerial.cpp#L205 When searching on github.com for arduino rs485 libraries, every library that I can find uses serial.flush or a delay to allow the byte to be transmitted before turning low the control signal.

Ok, i will try.

what is the best way to solve it, using Serial1?

With either serial device, you need to collect characters until you have an entire message. If every message will be a fixed number of bytes, you can wait until the return value of the Serial::available() call indicates it has that many characters, then collect them into a buffer and process them. But this assumes you'll never get a badly-formed message. If you do, the incoming bytes will get out of sync with your program.
A better way is to collect bytes into your buffer (but do nothing with them) until you have a complete message (by byte-count, newline character, or however you need to recognize that it is complete) or your buffer is about to overflow, and then either process them, or if your buffer filled and the contents doesn't look like a valid message, discard it and try to re-synchronize with the source. That may mean reading and ignoring bytes until you get a newline, and dealing with the fact you got a garbled message, or telling your source to restart or reset. The exact method (or whether you even want to bother detecting bad messages) depends on the particular situation. Will someone die if you fail? Will something catch fire, burn parts, lose weeks worth of good data, ... ? Or is this an experiment whose consequence of failure are zero or at least not worth any effort to detect it?


text:
How do I use this motor shield?

I am stuck with this motor shield. All I have is the shield. No documentation available online, nothing.
I need to run two motors off this thing and I only have a few hours to figure out how this works.
Can anyone point me in the right direction..?
Like how to control the 2 motors that I have from it (if they could be plugged into the pins right on top of that green thing with screws, that would be great) and where to plug in the power supply?
I've seen a lot of weird motor controllers for Arduino, this one I just can't figure out.

What chip is that?

Just a little bit of googling and here it is. It is based on L293D, it is quite a common one. In that link there is PDF but you have to login there in order to read it.
https://www.robomart.com/l293d-motor-driver-shield?dtags%5B0%5D=13

@Sener Damn... I must be going blind.
Thanks a lot


text:
Cannot upload sketch to Arduino Nano
I've been using Arduino UNO for quite sometime and brought a new Arduino Nano. When I connected it to my computer, the power usb lit up and the blink sketch started running ( as expected of course).
Now I opened up the IDE and switched boards. But when I try to upload code to my Nano I get an error-

avrdude: ser_open(): can't open device "\.\COM3": The system cannot find the file specified.

Clearly the IDE can't see my board. Uploading to my UNO goes fine. The serial port option is greyed out so I can't change it.
I have searched extensively online for a solution and have found none. This must be either a very unique issue or a very simple one.

Is it a genuine Arduino Nano or a cheap Chinese clone Nano?

@Majenko most probably a clone. I don't see anything written on the board. And the same coloured power and pin13 LED further confirm the fact. Have I done a mistake??

No, but it will need different drivers. CH340G

@Majenko I bought it online. The seller listed it a genuine one, but I just noticed that. BTW a google search for CH340G shows up differrent adapters. Do I need to buy an external adapted to program it??

Check the numbers on the chip on the underside first.

yes its CH340G...

So download and install those drivers then. Then Windows should identify it and give you a COM port to use.

@Majenko  did download them. Tried installing. Nothing happened...

I find it hard to believe that nothing happened. Did windows try and identify the hardware? Is there an unidentified or failed device in the device manager? Did windows make any sounds when you plugged the Nano in?

No sounds no devices in device manager. I installed the driver and it said pre-installed the drivers. Just nothing happened. is that bcz I'm on Win10.

Are you using a cable with no data wires in it?

@Majenko I don't know. Its a new cable I bought off at a local shop just half an hour ago. It powers up the Nano. But I'm not sure about how many wires are in it

Do you not have more than one cable? You should have a drawer full of USB cables. Everyone has a drawer full of USB cables.

@Majenko I had a drawer full of USB cables. In fact I kept a usb b type cable for charging my wireless headpiece but it went missing. BTW I tried connecting a phone using the same USB cable and guess what, nothing happened, the phone is just charging and my PC didn't detect a thing. So its a cable fault I assume

Certainly sounds like it. You can get cables without data wires that are purely for charging small devices (not phones and things which use the data wires to identify the charger and get more current).

@Majenko and yes the cable it was. Borrowed a cable from my neighbor and the Nano is working perfectly fine. Thanks. Please state that as an answer so I can mark it

I solved the problem, followed this: "http://www.instructables.com/id/How-To-Burn-a-Bootloader-to-Clone-Arduino-Nano-30/"

Firstly, you have a clone not a genuine Arduino Nano. They use a different USB chip and require different drivers. Install the CH340 drivers.
Secondly your cable is bad. It sounds like one with no data wires in it used for powering or charging small low-powered devices like bluetooth headsets etc. Replace the cable with a proper one.

When using a cheap knockoff Nano, it seems that in the newer versions of the Arduino IDE (at least in 1.8.8), you may need to select "ATmega328P (Old bootloader)" from the Processor options under the Tools menu in order to upload sketches.

Phew. I never would have guessed this. Thanks!

I've seen this error a few times and renaming the serial port fixed the problem in my case. I documented the steps in detail in Tip #4 of this blog post: https://gyorgybalassy.wordpress.com/2020/10/16/cant-open-device-com-access-is-denied-arduino-upload/

I don't really see a question in the OP, but here is the immediate answer:
Go into Control Panel..Device manager.  Open the Ports (COM & LPT) and see what you have.  It should be listed.
If it is a CH340 port it will just give a COMx number.
If you have the genuine article then it will actually say so and give you the COMx number to use.
If no COM ports show then try switching out the cable.  Power cycle the Arduino and try again.
There aren't that many moving parts in this, but sometimes, Windows gets confused and a Windows reboot might be necessary.  That usually only happens if you unplug and replug the Arduino too many times for Windows to keep track of.


text:
Trying to map a room with Arduino controlled bot

What you see above is a map of my room. The boxes in black are obstacles and the box in red is my bot.
Now I want my bot to go around the room, avoiding all obstacles, but at the same time, covering the entire floor. Think of it like the robot is painting the floor and it has to paint the entire floor avoiding all obstacles.
Now my first approach was to put 3 HC-SR ultrasonic sensors on 3 sides and listen to them in a sequence, deciding which path is best and then going there. But this method leaves out quite a lot of floor area uncovered.
So how can I cover the entire floor area here?
 Presently I am working with Arduino UNO and HC-SR04 but wouldn't hesitate to throw my Pi3 or a few more sensors in there...-

This is more of a robotics question and not really about Arduino,

This is actually quite a complex thing to achieve. I'll give some suggestions, though this is not something I have attempted (yet).
The main thing to do is divide the room up into a grid. The resolution you choose (X and Y dimensions) depends on how small your robot is, how big the room is, and how much memory your have available (on an Uno that's not much at all).
The second thing you need to do is work out a way of determining exactly where in the room you are. That could be done by trying to get as close to the bottom-left corner as possible before starting to map.
Now you can work from square to square (you could do with some encoders to know how far you have driven, and a magnetometer so you know which direction you are facing) using whatever method you like to decide which way to go, and in each square you look to see which of the squares around you are accessible. From that you can work out which way you can go from that square.
As you go you maintain a map in memory of all the squares you have been to, and the squares that you cannot get to. Note that it may not be enough to say "You can't get to square 4,3" - instead you may to keep a more detailed list (depending on what your obstacles are). "You can't get to square 4,3 from square 4,2, nor 3,3, but you can get to it from square 5,3" for example (e.g., a thin obstacle that only blocks entry to that square from certain sides).
Since your sensors cover longer ranges than just one square (unless you have big squares) you can work out how far away an obstacle is, and mark the square it's in before you even get close to it. The square immediately preceding it on a path between it and you would be the "you can't get there from here" square.
Now you can work out paths and routes to get to the squares you need to so you can cover all the available floor.

I must say... That was much more complex than I thought it would be.. But I'm gonna give it a shot for sure


text:
Wierd Issue with PWM pin
I'm trying to run two of my motors through PWM. Here's my code -
#include <Servo.h>
int Lm = 11;
int Rm = 10;
int incomingByte = 0;
int pos = 0;
Servo myservo;
void setup() {
  pinMode(Rm, OUTPUT);
  pinMode(Lm, OUTPUT);
  pinMode(7,OUTPUT);
  pinMode(2,OUTPUT);
  myservo.attach(3);
  Serial.begin(9600);

}

void loop() {
  blinkers();
  if (Serial.available() > 0) {
                incomingByte = Serial.read();
  }
  if(incomingByte == 49){
    analogWrite(Rm, 128);
    analogWrite(Lm, 128);
  }
   else if(incomingByte == 48){
    analogWrite(Rm, 0);
    analogWrite(Lm, 0);
    myservo.write(0);
  }
  else if(incomingByte == 50){
    analogWrite(Rm, 0);
    analogWrite(Lm, 128);
    delay(500);
    analogWrite(Lm, 0);
  }
  else if(incomingByte == 51){
    analogWrite(Rm, 128);
    analogWrite(Lm, 0);
    delay(500);
    analogWrite(Rm, 0);
  }
  else if(incomingByte == 52){
    for (pos = 0; pos <= 180; pos += 10) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for (pos = 180; pos >= 0; pos -= 10) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);
  }
}
}

void blinkers(){
    digitalWrite(7, HIGH);
    digitalWrite(2, HIGH);
  delay(100);
  digitalWrite(7, LOW);
  digitalWrite(2, LOW);
  delay(100);
}

Now in this code... Lm, and Rm are my motors. The motor Lm runs perfectly fine, but Rm doesn't move at all. When I use digitalWrite instead, both motors work fine.
I tried running the motor in the exact same setup but this time with only the code for running the motor by PWM. The code was -
void setup() {
  pinMode(10,OUTPUT);

}

void loop() {
  analogWrite(10, 128);
  delay(100);
  analogWrite(10, 0);
  delay(100);

}

This code worked perfectly fine.
So clearly there is an issue in the earlier code but I can't figure out what. Everything is correct in that as well but the motor refuses to move...
Can anyone tell why is this happening?

It is a timer conflict.
The Servo reference says: "...use of the library disables analogWrite() (PWM) functionality on pins 9 and 10..."
This is a picture of the pinmapping of the Arduino Uno: PighiXXX - Uno.
Pin 9 en 10 uses OC1A en OC1B for PWM, that is Timer1. You can't use PWM on them when the Servo is used.
Pin 11 uses OC2A for PWM, which is Timer2.
I suppose it will work if you choose another PWM pin for analogWrite. Timer0 is used for millis and therefor the PWM frequency will be different (pin 5 and 6). That is mentioned in the analogWrite reference. In most cases that is not a problem.
Pin 3 is a normal PWM pin.
This is a common problem. The documentation is not always clear about the use of timers and other parts of the microcontroller. Many times the source code has to be read to see what is used. In the end, you need more experienced Arduino users to spot the conflict.

Yeah I had no idea that something like this would be the reason... Thanks for the answer @Jot


text:
Unable to use Keyboard library with Arduino UNO even after changing the firmware
So I'm trying to use my UNO as an HID device. I followed this tutorial, flashed the firmware and got the UNO to be detected as an HID device.
However, I am still getting the error

'Keyboard' not found. Does your sketch include the line '#include '?

Here's the code -
/*
Copyright (c) 2014 NicoHood
 See the readme for credit to other people.

 Keyboard example
 Press a button to write some text to your pc.
 See official documentation for more infos
 */

// include HID library
#include <HID.h>

const int pinLed = 13;
const int pinButton = 8;

void setup() {
  pinMode(pinLed, OUTPUT);
  pinMode(pinButton, INPUT_PULLUP);

  // Starts Serial at baud 115200 otherwise HID wont work on Uno/Mega.
  // This is not needed for Leonado/(Pro)Micro but make sure to activate desired USB functions in HID.h
  Serial.begin(115200);

  // Sends a clean report to the host. This is important because
  // the 16u2 of the Uno/Mega is not turned off while programming
  // so you want to start with a clean report to avoid strange bugs after reset.
  Keyboard.begin();
}

void loop() {
  if (!digitalRead(pinButton)) {
    digitalWrite(pinLed, HIGH);

    // Same use as the official library, pretty much self explaining
    Keyboard.println("This message was sent with my Arduino.");
    Serial.println("Serial port is still working and not glitching out");

    // simple debounce
    delay(300);
    digitalWrite(pinLed, LOW);
  }
}

/*
Definitions:

 KEY_LEFT_CTRL
 KEY_LEFT_SHIFT
 KEY_LEFT_ALT
 KEY_LEFT_GUI
 KEY_RIGHT_CTRL
 KEY_RIGHT_SHIFT
 KEY_RIGHT_ALT
 KEY_RIGHT_GUI

 KEY_UP_ARROW
 KEY_DOWN_ARROW
 KEY_LEFT_ARROW
 KEY_RIGHT_ARROW
 KEY_BACKSPACE
 KEY_TAB
 KEY_RETURN
 KEY_ESC
 KEY_INSERT
 KEY_DELETE
 KEY_PAGE_UP
 KEY_PAGE_DOWN
 KEY_HOME
 KEY_END
 KEY_CAPS_LOCK
 KEY_F1
 KEY_F2
 KEY_F3
 KEY_F4
 KEY_F5
 KEY_F6
 KEY_F7
 KEY_F8
 KEY_F9
 KEY_F10
 KEY_F11
 KEY_F12

 KEY_PRINT
 KEY_SCROLL_LOCK
 KEY_PAUSE
 */

Can anyone point out what I'm doing wrong here?

Okay, so the problem was that the added HID library was conflicting with the core Keyboard/Mouse library. I replaced the core library with the new one and it worked without any problems.
Well one problem actually, it would ask for a platform.h. To solve this download the Arduino v1.5.7 BETA zip and find the platform.h file in it and paste it in your current Arduino directory.

If I open the rar library file, than I see a file called Keyboard.h. I'm sure you need to include Keyboard.h, than the class Keyboard is known and you can use it in your sketch.

I've tried doing that... It doesn't work. Still gives the same error


text:
Arduino Pro Mini RESET button suddenly stopped working
I am powering my Pro Mini(3.3V version) using an external battery (~6.5V 700mA) . I used to connect it to the RAW and GND pins on my pro mini and everything ran fine.
Today when I powered up my Arduino again, it didn't light up. A quick glance told me that I had connected the battery to the RST and GND pins mistakenly. Quickly pulled them out and put them into place, the Arduino worked perfectly until I discovered that the RESET button is no longer working. Without the RESET button I can't upload anything to my board.
Tried connecting the RST and GND Pins, didn't work.
The board is working fine though, I discovered a new procedure to upload as follows-
NOTE: I use the USB-to-TTL adapter by DSUN (picked up at a local electronics store).

Connect the RX, TX and GND Pins from the adapter to the Pro Mini.
(The green LED on the Pro Mini lights up dimly)
Upload the sketch from the IDE.
As soon as the IDE shows "Uploading", connect the +5V pin from the adapter to RAW pin on Pro Mini. Upload goes fine.

The above procedure is working just fine, and the board as well. But I'd like to have my RESET button back.
So what do I do?

You could probably still use that Arduino in a final project where compilation will only happen once, other wise RIP.

You can buy a Arduino Pro Mini for $2 or less, so I guess it not worth using-It's dead Jim. "Do not grieve, Admiral. It was logical."

What do you do? You replace the chip on the board.
By pumping 6.5V through the RESET pin with no power attached you have irrevocably broken the reset pin inside the chip. Way too much current will have flowed through the internals of the pin leaking its way up to the VCC pin and then back down through the rest of the chip to ground, burning out vital parts of the internal logic of the pin.
It's dead, Jim.
Your "fix" basically relies on the fact that the bootloader runs for any kind of reset - be that a RESET pin reset or a POR (Power-On Reset).

Hmmm so my fix can still get the board running anyways right?

Yep. As long as there is a power-up event (even a brief drop-out of power would do) the bootloader will run.

As if holding the RESET button while uploading wasn't annoying enough. Anyways thanks!


text:
Adding external power supply to any arduino connected component
I have an Arduino Pro Mini 3.3v and the voltage is too small for my buzzer to ring loudly. I want to add a 9v battery to power the buzzer.
This is my current circuit:
Arduino (pin 9) => Buzzer +ve
Arduino Gnd => Buzzer -ve
I want to power the buzzer using an external 9v battery but I have no idea how to implement it in the circuit. All I know is that the ground should be common.
What next?

You can use an NPN transistor for this purpose.
All you have to do is connect it this way
Obviously use a buzzer instead of the motor and pin 9 instead of 4 :D
Arduino (pin 9)==>1k-10k Resistance==>Transistor base
Buzzer +ve ==> + 9V
Buzzer -ve ==> Transistor collector
Transistor Emitter ==> battery -ve ==> Arduino GND.
So now whenever you set the pin 9 to HIGH the transistor would allow current to pass through it from collector to emitter and your buzzer would work just as you wanted.

Sounds good... I was thinking of doing something similar!

Thnx :D you can upvote if this helped you :)

Use a MOSFET. They are like little electronic switches. They will work fine with the 9V that you want to use.
Tutorial.

In this case a regular transistor will also work fine. Use an NPN transistor. The connect the 9V to +ve of the buzzer; -ve of the buzzer to the Collector of the transistor. - of the battery to both GND and the Emitter of the transistor. Connect the Base of the transistor via a resistor (e.g. 1kOhm) to an Arduino pin.

I find a MOSFET just simpler. They are more reliable for beginners.


text:
how many processor cycles/time does it minimaly take to transmit 1 Byte via Serial?
My understanding has been that the Serial transmission is indeed done (on the Arduino Uno) via the pins named TX->1 and RX<-0?
With this I assume that the Atmega has a machine code that would allow in 1 or processor cycles (125 or 62.5 ns) to set a byte (i.e. Port byte DDRD) as to forward exactly one bit of information for further processing to the ATmega16U2 "serial to USB" chip?
If this is true I would expect that 1 Byte = being 8 bits would require a discouragingly slow 8 to 12 cpu cycles (500ns to 1us)? Is this true?

If 16 megabit is discouragingly slow then you are in for a big disappointment. The default serial setting is 9600 baud, and the normal max is 115200.

No, it is not true.
You are assuming (wrongly) that the CPU is doing the UART communication.  It isn't.
The UART is a completely separate piece of hardware inside the chip.  It runs by itself.  The CPU merely places the byte to transfer into a special function register (SFR).  The UART then takes that and clocks it out through the IO pins at the right rate for the serial communication.  While that is going on the CPU is free to perform other operations.
The CPU can then either consult another SFR to determine if the transmission has finished, or utilize an interrupt that the UART will trigger when the transfer has been completed.

great, any change that would allow to make any reasonable guess how many bytes can be writen in a processor cycle? Also was it another wrong idea that the DDRD would have bits related to the tx/rx see https://www.arduino.cc/en/Reference/PortManipulation? maybe you would be able to extent your else already helpful answer, thank you!

The number of bytes you can write per second depends entirely on the baud rate the UART is running at.

Given the Arduino Uno (I am unsure if the revision is of importance), would you know what would the UART be? Also I think that the data must be somewhere indicated to the UART by the Atmega328, which runs at 16Mhz, I thought it was unable to tell more than 16 million times a second something to the UART, which then could have baud rates higher than what could be indicated by the Atmega328 on the Uno, right?

The UART has a baud rate that is dictated by the 16MHz clock. Read the ATMega328P datasheet to find out all about the UART.  The baud rate is a tiny fraction of the 16MHz clock rate - typically measured in the KHz range.

maybe indeed my assumption was wrong to the point that I did not explicitly refer to the UART chip doing the eventual sending out of data. I assume anyway I was quite rightly assuming that the Arduino Uno's 328 yet has to bring the data to this UART chip. To what I can understand this is done via the TX RX pins linked to the 16U2 UART, hence the questions reasoning was somewhat right assuming that the it takes at least 8 CPU cycles to send 1 Byte, only that some 6 or 7 out of those 8 the Atmega can do whatever else and is not doing a read of RAM to that SFR.

According to the datasheet:

Running at 16 MHz (as the Uno does) you can get up to 2 Mbps.

If this is true I would expect that 1 Byte = being 8 bits would require a discouragingly slow 8 to 12 cpu cycles (500ns to 1us)? Is this true?

For a bit or a  byte? At 2 Mbps that is a bit every 8 clock cycles.

would you know what would the UART be?

The UART is built into the processor chip. I suggest you read the datasheet.

I thought it was unable to tell more than 16 million times a second something to the UART, which then could have baud rates higher than what could be indicated by the Atmega328 on the Uno, right?

You can't do anything more than 16 million times a second at 16 MHz. And the clocking out of bits (in SPI, serial, or I2C) itself requires clock cycles, although they are done in parallel with the processor instructions by the hardware.

This is related to your other thread Can Arduino Uno's serial handle to foward push through 1-wire protocol? isn't it? Your end objective, I am guessing, is to try to implement 1-wire reading/writing via sending each bit via serial. This is just not the right way to achieve that objective.
In fact this thread in particular is coming across as an X-Y problem - your stated objective of wanting high-speed serial, is not really the problem you are trying to solve, is it?

you tell it right Nick, indeed the quesiton was in line with the other inquiry about implementing a firmata/bitflash type of protocol related to pass on 1-wire data. As @Majenko pointed out, in addition to my own calculations the time requirements are at best hardly matched. I thank you for your answer, I liked it and maybe can inquire that if the I had another UART chip than the Arduino Uno's Atmega16U2-MU which worked at a higher at say 32Mhz I had changes to Serial sent more than one byte per cycle of the Atmega328P, did I get that right?

if I had another UART chip - no, because you need to communicate with this chip somehow. The fastest method would be SPI which can send one byte every 16 clock cycles.

communicate with the chip somehow As suggested in the answer from @Majenko there would be a SFR in which the Atmega328 but the 8 bits (complete 1 Byte). It seems that such a step would be atomic 1 or 2 Atmega328 cycles. So is the "fastest communication rate" between the Atmega328 and the Atmega16U2 the 1 byte each 16 clocks?

Most of the "store" instructions are two clock cycles, so yes, it would take two clocks to load up the UART register, so it can start sending. Then, remember, that serial has a start and stop bit, so that is 10 bits per byte, not 8. I'm not sure if the Atmega16U2 will support 2 Mbps rate when communicating with the Atmega328, but even if it did, it takes more than zero clock cycles to then send this data in/out the USB port. I think you are flogging a dead horse here.

I have already ordered for a black beagle bone. It combines in one device what I wanted to achieve via a "Arduino extended BananaPi". I simply could learn from your answer and comment and hence revisited and thought. thank you


text:
How reliable is Arduino Uno Serial, via USB (ATmega16U2), CRC needed?
I have a question about the reliability of Serial communication, i.e. in particular if I need to implement CRC/checksum/ECC because of bit transmission errors?
I
I however think there is no general answer as there are different ways in which serial communication with the Arduino Uno's Atmega328P chip might work.

(a) The serial communication is between two Atmega328P Chips, and using rather long wires
(b) The serial communication is between two Atmega328P Chips, and using rather short wires
(c) The serial communication is between one Atmega328P and the ATmega16U2, who picks up and forwards the signals via USB protocol (e.g. to a PC)

My question is with regard to the ATmega16U2. The distance (wire/line length) on the Arduino R3 board is about 2cm/1" tops, which I expect to reduce the likeliness that a signal will become corrupted.
Assuming that the USB protocol which is further employed to transport the signal by itself provides by itself an ECC/CRC/checksums, I wonder if it is not rather superflous to implement a CRC when receving and sending messages via the serial communication in the case (c), while I however expect it to be more necessary for (b) and almost certainly necessary for (c).
Also, if this matters to respond to the question, I was wondering if the power supply (i.e. if Arduino Uno is powered by the USB provided voltage of ~4.5V or rather via an external 12V power adapter) would have an impact on the "corruptability" of the signals on the TX/RX serial lines?

UART already has parity bit in the protocol, though the Arduino doesn't use it. It might be more useful to do some kind of checksum on a higher level protocol, on top of UART.

for a crypto box project, i used thumbtacks as uart contacts. I transferred 2kb keys with CRCs at 115200.  In testing ~1200 keys, I only once had to resend once because of a CRC mismatch, and i think that was because the thumbtacks stopped touching as i plopped down into my desk setup...

If you use the appropriate buffering of the 0/5V signal over the long wires, case A, no error detection and correction is needed. RS232, RS485, your data will be just fine (can be up to thousands of feet).
Shorter wires, from Atmega device to Atmega device, I've neved had to use anything, even at 115200 speeds, case B, case C.
16U2 to PC, that will depend on the quality of the USB cable. The +/-3V differential signal (similar to RS485 levels) is quite high speed, like 4 Mbits/second, so you want a good cable with good shielding.


text:
Reading RFID tags with Arduino IDE, not using Arduino
I am completely new to this technology, but I'm hoping to build a fairly simple program through the Arduino IDE that takes the serial numbers of RFID cards read through my ID-20LA Innovations RFID reader and send those serial numbers to an API endpoint all through the IDE (as in without using a physical Arduino).
Is this possible? Are there any tutorials out there that walk through a stripped down version of this? I don't know where to start code wise, and all tutorials I've found use physical Arduinos to accomplish this.

Arduino ide can't run the program for you. You can create your program in any language and run it on your PC it just need to communicate over serial. Python, nodejs and so on....  You can used arduino ide's Serial monitor to see the output from the reader though.

Like @Molda said, the Arduino IDE can't run programs without a physical Arduino. You could, however, use something like Processing.

Short answer:
NO
Long Answer:
Option 1:
 Use a USB RFID reader and create a basic processing/python/ app to read from the USB RFID reader and post it where ever you want it to
Option 2:
Use the arduino to read from the ID-20LA and send the data via UART to your computer and then create a windows app using processing/python/ to send it to your API endpoint
Option 3:
Use the arduino YUN to read from the ID-20LA and then create a basic python program to run on the YUN itself. Such that it will read data from the atmel microcontroller (on the YUN) and post it to your API endpoint. This is a much cleaner yet slightly more expensive way of doing this.


text:
WebSocket client for ArduinoHttpClient conditional if with readString() incoming data buffer
I'm having issues implementing a web socket on the Arduino/Genuino to procress a string received and do something respectively.
I'm using SimpleWebSocket example, edited for my purpose, from the ArduinoHttpClient...
don't seam to get the hangs of it. don't know what i'm doing wrong, cannot store the received string object on a string variable or use the readString() method on and if statement to compare with a string to decide what flow path to get in to
This is the code im trying:
/*
  Simple WebSocket client for ArduinoHttpClient library
  Connects to the WebSocket server, and sends a hello
  message every 5 seconds

  note: WiFi SSID and password are stored in config.h file.
  If it is not present, add a new tab, call it "config.h"
  and add the following variables:
  char ssid[] = "ssid";     //  your network SSID (name)
  char pass[] = "password"; // your network password

  created 28 Jun 2016
  by Sandeep Mistry

  this example is in the public domain
*/
#include <ArduinoHttpClient.h>
#include <WiFi101.h>
#include "config.h"

char serverAddress[] = "192.168.1.140";  // server address
int port = 8000;

WiFiClient wifi;
WebSocketClient client = WebSocketClient(wifi, serverAddress, port);
int status = WL_IDLE_STATUS;
int count = 0;

void setup() {
  pinMode(6, OUTPUT);

  Serial.begin(9600);
  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to Network named: ");
    Serial.println(ssid);                   // print the network name (SSID);

    // Connect to WPA/WPA2 network:
    status = WiFi.begin(ssid, pass);
  }

  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

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

void loop() {
  Serial.println("starting WebSocket client");
  client.begin();

  while (client.connected()) {
    int messageSize = client.parseMessage();

    if (messageSize > 0) {
      String test = client.readString();
      Serial.println(client.readString());
      Serial.println(test);
      if (client.readString() == "off") {
        Serial.println("low");
        digitalWrite(6, LOW);
      }
      else {
        Serial.println("high");
        digitalWrite(6, HIGH);
      }
    }
  }

  Serial.println("disconnected");
}

On the example above, you can see in the void loop, after I check there's incoming data with messsageSize I store the incoming data using readString on a variable test, which I then println, this shows and empty line, although when I directly via println readString it shows some data, so the data is coming in... subsequently when I try to use the data from the incoming buffer on and if statement to compare with a string is wont work.
I've tried everything I can think off, puting the string to compare in to a variable and compare them, using Compare method from the object and I cannot even remember what else.
does anyone have any advice on how to do this, maybe the library is buggie, maybe I'm doing it wrong, any other libraries that anyone can recommend, I've looked around and this is the only one that looked simple enough to get started with and had the most examples.

this workes:
if (messageSize > 0) {
      //Serial.println(client.readString());
      String input = client.readString();
      Serial.println(input);

looks like reading from the method readString() empties the buffer hence cant use it again, what I did is store it on a String object variable "input" and use that.
It worked.