text:
Code test the duration press of the button
I wrote code that tracks the duration of a button click. It has bounce protection and frequent clicks. (Freeze)
My code:
bool freeze_time, btn_read, debounce;
unsigned int freeze_timer, btn_timer;

#define BTN 6

void setup() {
  Serial.begin(9600);
  pinMode(BTN, INPUT);
}

void loop() {
  /* Freeze Timer Protection */
  if(freeze_time) {
    if((millis() - freeze_timer) >= 2500) {
      freeze_time = false;
      btn_read = false;
    }
  }
  /* Read Button State */
  if(digitalRead(BTN) == HIGH) {
    if(!btn_read) {
      btn_timer = millis();
      debounce = true;
      btn_read = true;
    }
  }
  /* BTN Read Process */
  if(btn_read) {
    /* Debounce Protection */
    if(debounce) {
      if((millis() - btn_timer) >= 1000) {
        if(digitalRead(BTN) == HIGH) {
          Serial.println("Debounce ok.");
          btn_timer = millis();
          debounce = false;
        } else {
          Serial.println("Debounce fail.");
          freeze_time = true;
          debounce = false;
        }
      }
    }
    /* BTN Read Process */
    else if(!freeze_time) {
      if((millis() - btn_timer) >= 1500) {
        if(digitalRead(BTN) == HIGH) {
          Serial.println("Ok. Button Pressed > 1500ms");
          freeze_timer = millis();
          freeze_time = true;
        } else {
          Serial.println("Ok. Button Pressed < 1500ms");
          freeze_timer = millis();
          freeze_time = true;
        }
      }
    }
  }
}

I checked it on real Arduino UNO and Tinkercad simulator. Initially, everything works well, but if I press the button indefinitely, the system will fail (every time you press the serial port, messages appear as if all flags were lost and the timers did not work. I filmed the behavior:
1) Initially: http://recordit.co/lVlR1z1CUq
2) System is broken: http://recordit.co/lhvzM100DI
What could be the problem and how to make it fault tolerant?

(millis() - btn_timer) >= 1000 Switch bounce doesn't last for a full second. You could however press the button, and release it within one second. Try changing it to a more sensible value like 10. The rest of the code doesn't really make sense to me. Could you explain what it is you want to achieve, as it looks like the code it way to complicated to just measure if a button was press for more or for less that 1500ms.

upvote for posting  correctly formatted code

you can reduce the number of lines of code by putting repeated command lines outside of if-else blocks .....  for  example, in the last if-else block, keep the  serial.println() lines inside the block, but move the freeze_timer = millis(); and freeze_time = true; to outside of the block, either before or after the block (it makes no difference logically in this instance) ........... same with the debounce = false;  in the previous if-else block

Use a more concise and reliable model for debounce (https://arduino.stackexchange.com/a/33577/42061)

Why did the timers stop working?
The main issue seems to be that freeze_timer and btn_timer are of type unsigned int, while millis, as stated in its documentation, returns an unsigned long.
As you may know, unsigned int is normally be able to hold a much smaller range of values than unsigned long. In the case of whatever compiler Tinkercad uses for the Arduino Uno, I checked and unsigned int can hold values from 0 to 65535, while unsigned long can hold values from 0 to 4294967295. Whenever you save an unsigned long into an unsigned int, it will be reduced modulo 65536.
This means that once you pass 65.536 seconds checks such as the (millis() - freeze_timer) >= 2500 will always be true (at least until millis wraps back around after 4294967.296 seconds - around 50 days).
If you would like to learn a bit more about integer conversions, I think this Stack Overflow question covers it.
The simplest solution is, of course, to declare freeze_timer and btn_timer to be of the appropriate type, unsigned long.
Use simpler code
All of the above being said, like Gerben said, the code seems overly complex.
There also seem to be other issues. For instance, I would expect the debounce behavior should not ignore presses that last less than 1 second. Like Gerben said, 10 ms should be enough to discard any bounces.
Furthermore, I think it would be more appropriate to not even discard presses that last less than 10 ms. I would say the debouncer should trigger "press" regardless of whether the press lasted less than 10 ms. It's role should just be to ignore multiple presses within that 10 ms window (although to be fair, ignoring short presses is not a terribly big issue).
Although one could make some guesses, to really help you with this, we would need a description of your intended behavior. What is the purpose of freezing? Is it intended to allow multiple presses to be triggered when you never release the button (or maybe you should wait until release before triggering one again)?

Works! Thank you!!!


text:
Question on pin management using PCA9534PW IO Extender
There is an IO expander PCA9534PW, Arduino UNO. I don’t really understand how I can manage this expander using UNO over I2C.
I found an example, but here is the reading mode.
What I need:
Set the IO0 pin to exit mode,
set the HIGH / LOW level to IO0.
In the datasheet, I just realized that to enter the settings mode - you need to write Wire.write(0x03).
How can I do it?

Hint: There is more or less always someone that has done this before you, and shared it. Please see, for instance, https://github.com/alotaiba/PCA9534.

Answer: Write to the configuration register to set the pin mode. See https://github.com/alotaiba/PCA9534/blob/master/src/PCA9534.cpp#L14.

You set the pin mode by setting the configuration register.
Wire.beginTransmission(0x20);
Wire.write(0x03);                   // Configuration Register
Wire.write(0xfe);                   // IO7-IO1 Input, IO0 Output
Wire.endTransmission();

Then write the output port register with HIGH and LOW.
Wire.beginTransmission(0x20);
Wire.write(0x01);                   // Output Port Register
Wire.write(0x01);                   // IO0 HIGH
Wire.endTransmission();
delay(500);
Wire.beginTransmission(0x20);
Wire.write(0x01);                   // Output Port Register
Wire.write(0x00);                   // IO0 LOW
Wire.endTransmission();

But using a library is much easier. See, for instance, https://github.com/alotaiba/PCA9534.

Many thanks for the example! I have seen this library, but it does not compile under Arduino. https://github.com/alotaiba/PCA9534/issues/1

It should be very easy to port from Particle. Have you tried to comment out this line, https://github.com/alotaiba/PCA9534/blob/master/src/PCA9534.h#L14, or just create an empty file with the name "Particle.h".

source: Stack Exchange

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

sort: votes


text:
Is it permissible to connect 3.3V powered devices to the 5V I2C bus?
I have several devices on the I2C bus:

RTC DS3231SN
TMP100 temperature sensor
EEPROM 24LC256

All devices are powered by 3.3V. The voltage on the I2C bus is 5V.
Question:
Is the voltage difference on the bus and device power normal?

It's better to use level translator. Or you can try to power pull-ups from 3.3V, it usually works, but 3.3V CMOS output interfacing 5V CMOS logic input isn't 100% compatible as some devices might need almost 3.5V to detect high level.

KIIV, Thank you for the help!

Are you using the bare chips, or do you have breakout board. If the latter, the problem might be with Arduino enabling the internal pull-up resistors inside the MCU. The breakouts already have pull-up resistors on them, so the Arduino board shouldn't do that (but does). Usually it doesn't matter, and help with people using bare chips, and forgetting to add pull-up resistors on the I2C lines. To disable them; see https://arduino.stackexchange.com/questions/13448/disabling-i2c-internal-pull-up-resistors . After that the I2C lines should read 3.3V instead of 5V.

There are 3.3V devices that have 5V-tolerant inputs; that may be the case for your devices, but I would not risk it. Use a level converter designed for I2C, such as https://www.adafruit.com/product/757. Or you can make your own; https://cdn-shop.adafruit.com/datasheets/an97055.pdf explains how such a level converter works. Use a BSS138 if you are comfortable with soldering SMT components; otherwise use a 2N7000.

JayEye,
Thanks for the answer!

For the DS3231 the maximum voltage if Vcc+0.3V. The TMP100 seems to allow up to 6V regardless of Vcc. The 24L256's maximum is Vcc+1.0V

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


text:
How to declare a global variable in the .h file?
I have a .h library file in which I want to declare a global variable that can be read in the program loop and in the library's .cpp file.
The question is, is it possible to declare a variable in the .h file and make it global?

.h file is included by the compilation preprocessor as text into the .c or .cpp file. It is included as if you would replace the #include preprocessor instruction with the content of the .h file. (The Arduino .ino file is converted to cpp file before preprocessing.)
After the inclusion the cpp file is compiled to 'object' (.o file). If the cpp file contains a variable definition the variable is defined in this object file. If your .h file contained a variable definition, the it is also in this object file.
If two cpp files included the .h file with the definition of the variable, then the variable will be in two object files and the linker will exit with an error, because of two variables with the same name.
If only one cpp/ino files includes the variable definition, then it is OK. It is not a good practice, but sometimes a necessary compromise. (example of it)
To have one global variable made accessible by a .h file, the variable should be only declared in the .h file and be defined in one cpp file. Usually it is a pair of .h and .cpp file with same name.
An example of global variable is Serial. It is a global object of type HardwareSerial declared in HardwareSerial.h as
extern HardwareSerial Serial;
and defined in HardwareSerial0.cpp as
HardwareSerial Serial(&UBRR0H, &UBRR0L, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);
Do you see the difference? The declaration has the keyword extern and the definition has in this case parameters for the constructor of the object. The declaration with extern keyword makes object Serial visible in all cpp files which include HardwareSerial.h (or an include file which includes HardwareSerial.h like Arduino.h included by ino to cpp conversion).

You can declare the variable as a static variable inside an inline function, and then just call this function to get a reference to this variable. Example:
inline int& getMyInteger()
{
    static int x;
    return x;
}

This definition can be in a header file, included into multiple *.cpp files, and any call to getMyInteger will return reference to the same object. You don't need any extern, nor to actually put the variable in any compilation unit as you would need with a simple namespace-scope variable. This trick just uses the linker's ability to de-duplicate inline functions.
See also: static variables in an inlined function question on StackOverflow.


text:
Is it permissible to use strlcpy to copy an array to itself?
Task: delete "\n" at the beginning of the array.
Example:
char s_msg[15] = "\nHello world!";

void setup()
{
  Serial.begin(115200);
  Serial.println("Load");
  // Search \n
  if(strstr(s_msg, "\n") != NULL) {
    Serial.println(s_msg);
    strlcpy(s_msg, &s_msg[1], sizeof(s_msg));
    Serial.println(s_msg);
  }
}

void loop() {}

Description:
If the \ n character is present at the beginning of the message, then we copy the original character to the same character, but without \ n.
Question: is it ok to copy char to itself (s_msg is the destination buffer and the source string at the same time)

why are you asking? ... try it first, then post a question if it does not work as expected

The documentation of strlcpy() should tell you. You might also look into memmove() and memcpy().

this functions are 50 years old. there are books an many Internet sites describing them

the other question is why do you need to delete the leafing character?

This manual page of strlcpy() is quite clear:

If the src and dst strings overlap, the behavior is undefined.

This means you should avoid it, even if it works on some tests. The
advice you got of just trying is not good advice. Use
memmove() instead.


text:
Do some arduino pins give signals when the controller starts?
For example, on the ESP32 board there are several contacts that can issue pulses when the controller starts, which is connected with the operation of the chip itself. It is not recommended to connect devices that respond to input signals from the ESP to these contacts.
Tell me, are there any contacts on the Arduino UNO (Atmega328P) that give out any impulses at startup?
In particular, it is important for me to know about the following contacts:

PB1 (9 pin)
PD4 (4 pin)
PD5 (5 pin)

Thank you!

on ATmegas the pins are INPUT at startup

If the arduino is programmed with a sketch, it depends on the sketch if the pin are input or output. If it is a new arduino the bootloader does not setup any outputs. An ESP has mostly a firmware installed. So the flashing pins are probably driven by this firmware. An Arduino may have a program already installed, that could also flash pins.

Most Arduino boards come with a bootloader of some form.  This bootloader may do things with IO pins. However apart from that, no, nothing else happens to any IO pins.
The bootloader may:

Flash pin 13 (built in LED)
Configure and communicate on pins 0/1 (UART)

With no bootloader then absolutely nothing happens on any IO pins.

thank you for the answer!


text:
Will an Arduino UNO operating at 16mHz communicate with UART / I2C with an STM32 operating at a different frequency?
I plan to connect Arduino UNO via I2C / UART with a controller based on STM32F334K8T6, whose frequency will be about 20mHz or higher.
Tell me, does the difference in clock frequencies of microcontrollers affect the operation of buses between them?
The tire speed will be equal. (UART 115200 Baud / I2C 100kHz)

20 millihertz? I guess you mean megahertz, or MHz, with a capital M.

Tell me, does the difference in clock frequencies of microcontrollers affect the operation of buses between them?

No it doesn't. Or not much any way. It may affect the accuracy of clock generation1, which may have an affect at very high asynchronous baud rates, but other than that, no.
For synchronous communication it's all synchronised to the communication protocol's clock, so processor clocks are irrelevant.

1: Baud rates are usually generated as an integer division of the system clock. Different system clocks give different results for baud rate divisor calculations, yielding marginally different baud rates. Different baud rates will have different error percentages on different system clocks. At low speeds this has no noticeable affect. At high speeds (millions of bits per second) it can cause errors to creep in.

Majenko, thank you for the answer!

Nice thorough answer.  You provided a simple yes/no answer, and then added some more nuance without obscuring the top level "doesn't matter" nature of the answer. Well done. (As usual.)


text:
How to send Serial.Print only If Serial Connection is open?
So I looked through the Arduino Mega2560 documentation and searched the web for a solution, and so far I haven't had any success.
What I'm trying to accomplish is fairly simple. I need to send a serial command over serial, ONLY if there is a serial connection between the PC and the Arduino. I've tried:
If(Serial){
   Serial.Println("COMMAND");
}

That doesn't work, and I think it's because the Arduino cannot distinguish between listening to the Serial port versus establishing a Serial connection.
Any help would be appreciated.
Cheers!

The Arduino Mega's "serial" connection comes from an external chip implementing USB-serial conversion.  While this chip knows if a session is open with a host, the standard design has no way to share that information with the main ATmega.
In contrast, on a Leonardo type board the main processor implements the USB interface, so it does know.
Your options include changing the requirement, having the PC program send some data to the Arduino, changing the processor to an ATmega or ARM with integrated USB, or perhaps modifying the USB implementation.

Thank you for the clarification. I'll have to go with 'having the PC program send some data to the Arduino'.

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


text:
Arduino to DAC to ADC back to Arduino?
My question is simple. Is the following possible?
I am using one Arduino Mega 2560 board and its SPI functionality to adjust voltages (0-4.096V) through a 12-bit DAC (MCP4822).
I would like to measure the output voltages from the DAC by feeding them through a 12-bit ADC and back to the Arduino. The DAC's output voltages that will be directly measured by the ADC will be displayed on an LCD and on LabVIEW.
Is this possible, given that both the DAC and the ADC have to be connected to the same SDI and SCK pins on the Arduino for SPI to work?

Yes, perfectly possible. Just provide two separate CS pins to select between the two devices.

Perfect.. Given that the DAC and ADC have to be connected to the same SCK and SDI pins, I'm assuming that the ADC cannot update the voltages (send data) until the CS pin on the DAC is inactive (low with the MCP4822). The CS pins on both the DAC and the ADC cannot be active at the same time, correct?

That is correct. You set the DAC first then read the voltage second.

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


text:
Read information from Twitch's API and execute actions depending on the output
i'm trying to create a display that notifies me when someone goes live on twitch. I need to acess the API and check if the 'stream' object is null or not. Then, perform an action depending on this.
The address to the API is http://api.twitch.tv/kraken/streams/pedrinholuizf
What can I do? I'm using an Arduino Leonardo with the Ethernet Shield.

Break your problem into small steps and try to identify the success criteria for each step. So you might:

Try to set up the Ethernet shield and get it to respond to a ping on your local network.
Try to connect to a site outside of your network.
See if you can find some examples of using the Twitch API.
Try to replicate one of the simple examples.
See if you can get the Stream object that you want.
See if you can read the value of the object.

If you have a plan and try to follow it you'll be able to tell us what you've been doing and where you got stuck / confused. That is likely to get you better answers – both because we can be more specific and also because we can see that you're "carrying your weight" as we work on the problem.


text:
Arduino throwing error while using modbus RS485 code
I have been trying to make a communication with my industrial drive. All I want to do is read a few values of drive, like current, voltage etc.
For that I am using a library:
I don't understand why it's happening. When the same code I have used before and the sketch was uploaded on the board, very well.
Here's the code from an example:
#include <SimpleModbusMaster.h>

// led to indicate that a communication error is present
#define connection_error_led 13

//////////////////// Port information ///////////////////
#define baud 9600
#define timeout 1000
#define polling 200 // the scan rate

// If the packets internal retry register matches
// the set retry count then communication is stopped
// on that packet. To re-enable the packet you must
// set the "connection" variable to true.
#define retry_count 10

// used to toggle the receive/transmit pin on the driver
#define TxEnablePin 2

// This is the easiest way to create new packets
// Add as many as you want. TOTAL_NO_OF_PACKETS
// is automatically updated.
enum
{
  PACKET1,
  PACKET2,
  // leave this last entry
  TOTAL_NO_OF_PACKETS
};

// Create an array of Packets for modbus_update()
Packet packets[TOTAL_NO_OF_PACKETS];

// Create a packetPointer to access each packet
// individually. This is not required you can access
// the array explicitly. E.g. packets[PACKET1].id = 2;
// This does become tedious though...
packetPointer packet1 = &packets[PACKET1];
packetPointer packet2 = &packets[PACKET2];

// The data from the PLC will be stored
// in the regs array
unsigned int regs[9];

void setup()
{
  // read 3 registers starting at address 0
  packet1->id = 2;
  packet1->function = READ_HOLDING_REGISTERS;
  packet1->address = 0;
  packet1->no_of_registers = 3;
  packet1->register_array = regs;

  // write the 9 registers to the PLC starting at address 3
  packet2->id = 2;
  packet2->function = PRESET_MULTIPLE_REGISTERS;
  packet2->address = 3;
  packet2->no_of_registers = 9;
  packet2->register_array = regs;

  // P.S. the register_array entries above can be different arrays

  // Initialize communication settings etc...
  modbus_configure(baud, timeout, polling, retry_count, TxEnablePin, packets, TOTAL_NO_OF_PACKETS);

  pinMode(connection_error_led, OUTPUT);
}

void loop()
{
  unsigned int connection_status = modbus_update(packets);

  if (connection_status != TOTAL_NO_OF_PACKETS)
  {
    digitalWrite(connection_error_led, HIGH);
    // You could re-enable the connection by:
    //packets[connection_status].connection = true;
  }
  else
    digitalWrite(connection_error_led, LOW);

  // update the array with the counter data
  regs[3] = packet1->requests;
  regs[4] = packet1->successful_requests;
  regs[5] = packet1->total_errors;
  regs[6] = packet2->requests;
  regs[7] = packet2->successful_requests;
  regs[8] = packet2->total_errors;
}

Also, here is the error I am receiving upon uploading the sketch
This report would have more information with
  "Show verbose output during compilation"
  enabled in File > Preferences.
Arduino: 1.0.6 (Windows 7), Board: "Arduino Uno"
SimpleModbusMasterExample:110: error: 'packetPointer' does not name a type
SimpleModbusMasterExample:111: error: 'packetPointer' does not name a type
SimpleModbusMasterExample.ino: In function 'void setup()':
SimpleModbusMasterExample:120: error: 'packet1' was not declared in this scope
SimpleModbusMasterExample:127: error: 'packet2' was not declared in this scope
SimpleModbusMasterExample:136: error: invalid conversion from 'int' to 'HardwareSerial*'
SimpleModbusMasterExample:136: error: invalid conversion from 'Packet*' to 'unsigned char'
C:\Users\xyz\Documents\Arduino\libraries\SimpleModbusMasterV2rev2/SimpleModbusMaster.h:143: error: too few arguments to function 'void modbus_configure(HardwareSerial*, long int, unsigned char, long int, long int, unsigned char, unsigned char, Packet*, unsigned int, unsigned int*)'
SimpleModbusMasterExample:136: error: at this point in file
C:\Users\xyz\Documents\Arduino\libraries\SimpleModbusMasterV2rev2/SimpleModbusMaster.h: In function 'void loop()':
C:\Users\xyz\Documents\Arduino\libraries\SimpleModbusMasterV2rev2/SimpleModbusMaster.h:125: error: too many arguments to function 'void modbus_update()'
SimpleModbusMasterExample:143: error: at this point in file
SimpleModbusMasterExample:143: error: void value not ignored as it ought to be
SimpleModbusMasterExample:155: error: 'packet1' was not declared in this scope
SimpleModbusMasterExample:158: error: 'packet2' was not declared in this scope

I would guess that it's not your code that has changed but the library you are using. Are you sure you have the right version of the right library?

The code you are using is the example provided with the SimpleModbusMaster library found on GitHub: https://github.com/angeloc/simplemodbusng
It appears that the SimpleModbusMaster library isn't installed. This can happen if you install a new version of the Arduino IDE.
To install this library:

Go to the link above and download the zip of the code.
Extract the contents and then copy the folder "SimpleModbusMaster".
Paste the folder into the Arduino/libraries folder located on your computer.  (On my computer it is: C:\Program Files (x86)\Arduino\libraries).
Restart the  Arduino IDE. You can go straight to the example code by selecting: File > Examples > SimpleModbusMaster > SimpleModbusMasterExample

This procedure compiled for me with no errors.

Was the answer helpful? If so, please accept it by clicking on the "tick" icon next to the answer, and also possibly upvote it. This indicates to other users that you found the answer useful, and it also stops Stack Exchange from periodically "bumping" your question in the hope of getting an accepted answer. Thanks for your understanding and cooperation!


text:
Reprogram CH341A chips VID PID etc
I know it's possible (in theory) to reprogram the VID PID details back into a chip. It is however way beyond me.
Recently I learned that Microsoft distributed a piece of malicious software as part of their Windows update service. This virus was written by the FTDI chip makers to brick any chips such as the CH341's found in many cheaper Arduinos et al.
The virus attacked my CH341A serial to USB chip by writing 0's to the VID PIC and probably other locations. This makes the hardware 'Unknown' and even if you have the correct driver software, the device is never associated with it.
Does anyone know a solution to get the zeroed information back into the CH341A?

Here's the guide I used to correct the problem :-
HOW TO FIX THE USB-FTDI PROBLEM
(on arduino nano, usb ttl, ft232, ...)
There must have been a production of faulty ftdi drivers (version 2.12.0.0 or later) on august 2014 that makes some arduino boards and other usb devices not readable from the computer. The problem is random, meaning that it is possible to program the arduino a couple of times and then it comes out the ftdi problem, at that point the board isn't accessible anymore.
Once you come up with this problem, upgrading/downgrading the drivers, the IDE or the bootloader is just a waste of time, as the ftdi driver installed leaves some wrong data. This guide followed step by step will completely fix the driver problem thus making your board working again.
Step 1: check if you have a faulty ftdi chip driver
Not every ftdi chip has faulty drivers, so the first step is to check the chip's driver version. In order to check the version you need a software like usbview or usbdeview (both freeware and don't need any installation). Run the software and look for the "USB serial converter" device which is the one related to the ftdi driver, then read the vendor-id and the Product-id whose values should be 0x0403 for the vendor and 0x6001 for the product. The goal is to modify that 0x6001 value with 0x0000, and to do that we need some other software.
Step 2: modify values
Unplug your arduino nano or usb device. In order to modify the driver values you need CDMUninstaller (no installation needed). Fill the vendor and product fields with the values found with usbview (0403 and 6001) and click 'add', finally click 'remove devices'.
Step 3: download the 2.10.0.0 ftdi driver
Go to the ftdi website and download the 2.10.0.0 virtual driver choosing between 32 or 64 bit version, voiding the 'setup executable' file: just download the folder. After downloading the folder, we have to overwrite some files inside of it. Click FTDI.rar to download the files already modified, and place them inside the 2.10.0.0 folder overwriting the old ones.
Step 4: connect your arduino board
connect your arduino board, and stop windows from looking for new drivers. Go to device manager and look for FT232 USB device, then right click on it, select Properties and click on update drivers. Manually select the place in which scan for the new drivers and choose the 2.10.0.0 driver folder with the modified files. Now windows will prompt you saying that it can't certificate the new drivers. Ignore the alert and proceed with the installation. Once installation has finished, windows should recognize the connected board as 'USB recuperacion'.
Close the window and go to device manager, and look for the COM ports device. The connected device is now showing up like USB recuperation by ElectroHobby.es
Step 5: modify the chip eeprom
This is the last step and you need to restore the initial vendor and product values inside the ftdi chip eeprom. In order to do that you need to download and install Ftprog, click on the magnifing glass icon, select 'USB device descriptor' and again select 'custom pid'. Finally click on 'ftdi default'.
A new window shows up and you just need to check flag the device list and then click on 'program'.

What you call a “virus” is, more properly, malware.  FTDI's driver that bricked fake FT232R chips was withdrawn from Windows Update in October of 2014.  (See, for example, discussion at epanorama.net, sparkfun, and hackaday.  The hackaday article, “Unbricking a counterfeit FTDI chip”, has links to an article about unbricking counterfeits.)
The CH341A is not a fake FT232; it is a cheaper alternative that requires a different driver.  The driver is not automatically installed by Windows. Several web pages I've seen about it suggest downloading from Chinese-language web pages, which is a gamble if you don't understand what the page says.  [However, English-language driverscape.com seems to have a CH341A driver at the moment.  I don't know if it works or whether it is free, and anyway have no Windows machine to test it on.]

FYI...FTDI are at it again.
Also, my CH341 was running fine until the update. After it, the VID PID was 0's.

@James, did any of the hackaday article turn out to be relevant?

If you have Windows updates turned on and use CH341 or fake FTDI chips then it's relevant. The article linked so that readers understand that the FTDI drivers have changed twice, with the latest change only recently.

@James, I meant, does the unbricking method given in hackaday work?

I gave it a quick try and it didn't work. I plan on giving it (and the above) a real good try tonight after work. I'll definitely post back.


text:
how to read arduino board info serial no programmatically
well I am try to make an project with original arduino. but I want to make this project unique. if my codes are copied and loaded another arduino board, my app should not work. how can make unique app, are there any idea? on Arduino IDE Tools> Get Board İnfo> SN look unique id. but how can read it programmatically.

You can't. The serial number is burned into the ATMega16U2 chip and is only available to the computer over the USB interface.  There is no method for you to get it from the UART interface that connects the two MCUs together.
To stop people copying your code there are two things you need to do:

Don't allow anyone access to the source code or any compiled code files, and
Enable the "code protection" facility of the ATMega328P.

The latter will stop people being able to read the code from the Arduino. It would also be beneficial to remove the bootloader and program the board directly. That way there is no other possible route for getting at your code.
You enable code protection by setting the correct fuse bits.


text:
How the light brightness stays constant when we increase the frequency of stroboscope
Well I am trying to make a Stroboscop. I found this code at blow: and tried. It works normally. But if I increase the RPM so decrease the "strobeDelay" time, the brightness of the LEDs goes out. Even if I try the GreatScott code. The same problem persists at high RPM. I am using power LED.
On the other hand there is a stroboscop which is Fluke 820, it says

Features high-intensity 7-LED array—4,800 Lux @ 6,000 FPM/30cm

How they achieve that constant brightness under the high frequency?
    // Gray text are just helpful comments, you don’t need to type them. :)

/******* -----=====!! EASY STUFF TO MESS WITH !!=====------ ******/

  // What analog pin should we use to read the value from the potentiometer?
  int analogPin = 2; // Yep, you heard right: The coolest of the Analog pins...

  // What pin is the LED connected to?
  int ledPin = 13; // Contains a built in resistor!

  // How much time should the light stay on between delays, in Microseconds (millionths of a second)?
    /* Big number = more blur, more perceived brightness
     * Small number = less blur, less perceived brightness  */
  long onTime = 250;

  // What should the minimum delay be in milliseconds (thousandths of a second)?
  // This sets the bottom delay range of the strobe, as a delay of 0 doesn't actually flash =P
  // The strobe starts with this as the "fastest" mode, and goes slower from there, adding to the delay
  int minDelay = 1; // 1 is the lowest we can actually do without a better delay function

  // What should the maximum delay be in milliseconds?
  // This is the longest time that the biggest potentiometer value will be mapped to, and longest
  // time between strobe flashes.
  int maxDelay = 100;

/******* -----=====^^ EASY STUFF TO MESS WITH ^^=====------ ******/

// Initialize the number to hold our strobe delay. Isn't used till we get to the main loop
long strobeDelay = 0;

void setup() {
 pinMode(ledPin, OUTPUT); // Setup ledPin as an output.
}

void loop() {
  // To make the math easier, we use map(value, fromMin, fromMax, toMin, toMax) to convert the
  // 0 to 1023 range we get from analogRead, into our strobe delay range of 1 to 100 :D
  strobeDelay = map(analogRead(analogPin), 0, 1023, minDelay, maxDelay);

  digitalWrite(ledPin, HIGH); // Switch the ledPin to HIGH, turn it on!
  delayMicroseconds(onTime); // Delay while on, for the given onTime.
  digitalWrite(ledPin, LOW); // Switch the ledPin to LOW, turn if off!
  delay(strobeDelay); // Delay while off, for given strobeDelay.
}

For those who wonder there is a video, but another brand same result, brightness constant even if RPM changes. I tried 2 different power LED. on of them is this, the other LED is I found in a broken projector, I used them 2 working strip. No doubt in your mind, this led strip is very bright at low frequency. Both of them same result like this:

How are you driving the LEDs?

I think the answer is in the comments on the code you posted:    Big number = more blur, more perceived brightness * Small number = less blur, less perceived brightness Short duration makes for lower perceived brightness. The actual brightness is the same, but our eyes see it as less when the duration is shorter.

I don't think the term RPM applies here. What do you mean by it? What parameter are you changing and what exactly is the effect, that you see with what values? The analogRead() currently only changes the delay between the pulses. The onTime stays constant. Each pulse will be as bright as the other one. Though you might see the overall brightness rising with lower delays, as your eyes will start tying the pulses together - more pulses per second means more overall brightness.

@Majenko a npn channel mosfet (IRFZ44N) datasheet is here https://datasheet.octopart.com/IRFZ44N-Inchange-Semiconductor-datasheet-15981338.pdf

@chrisl Actually your says looks absolutly right, but in realty not works.I've never heard of it yet, but is there a time required for the leds to flash? I will change leds and try again.

@chrisl same result nothing changed. I think I need very shiny leds

Leds can be modulated very fast, much faster than your 1kHz. The led module is probably not the problem.

To keep the same brightness, you have to keep the same duty cycle (percent of on time over off time).  So to change the rate without changing the brightness, you have to increase
delayMicroseconds(onTime) by the same percent you increase delay(strobeDelay).  But note that as you go slower, the on time will be too long to freeze the motion you are trying to study.  (If it's just for a party effect this may not matter.)

Try delayMicroseconds(strobeDelay*250); (instead of delayMicroseconds(onTime);). This should give you the same perceived brightness, not matter what speed/"RPM" is selected.

nice idea, I will try tomorrow and write here the result

@Gerben same result nothing changed. I think I need very shiny leds


text:
What is the relation between Arduino's clock and possible VGA resolution?
I have seen it said over and over (in different places) that in order to achieve 640x480 resolution out to a DB15 VGA connection, the arduino would need to be clocked at 25Mhz or that at half resolution it would need to be clocked at 12.5Mhz.
What is the relation between resolution and internal clock? I would expect that so long we can feed the signal fast enough that would be enough.

I doubt if that would be fast enough. See my thread about connecting to a VGA monitor.
Borrowing from that page, so as to not make a link-only answer ...

For 640x480 pixels of active video you have something like this:

Vertical Sync
Let's start with the vertical sync pulses. In fact, we'll show how all the timing data can be derived from three figures:

The screen refresh rate (eg. 60 Hz)
The screen resolution (eg. 640 x 480)

So what is the refresh rate? It's the rate at which the entire screen is redrawn. If you ever looked at Windows screen resolution you probably saw something like this:

That's the refresh rate: 60 Hz (60 times a second). This figure was probably originally chosen because it is the mains frequency in the USA, so that would minimize the artifact of mains hum bars appearing on the screen, in the days of CRT monitors.
The other figure of interest is the screen resolution.
In our case we are going for the minimum we can (640 x 480) and seeing where those figures lead us.
Starting with the refresh rate, a 60 Hz refresh rate will require a "vertical sync" pulse 60 times a second, or a period of 1/60 (16.66 ms).

Generating vertical sync pulses
This code in my VGA output sketch generates the vertical sync pulses:
  // Timer 1 - vertical sync pulses
  pinMode (vSyncPin, OUTPUT);
  Timer1::setMode (15, Timer1::PRESCALE_1024, Timer1::CLEAR_B_ON_COMPARE);
  OCR1A = 259;  // 16666 / 64 uS = 260 (less one)
  OCR1B = 0;    // 64 / 64 uS = 1 (less one)

The clock period is 62.5 ns (1/16000000). By applying a prescaler of 1024 the timer counts up once every 64 µs. So to get a period of 1/60 of a second (16666 µs) we need to count up to 260 (16666 / 64 = 260). Since the timer counts are zero-relative we set OCR1A to count up to 259. This sets the frequency of Timer 1.
Then we need to set the pulse width by putting the correct value in OCR1B. We want a pulse width of two lines. One line is 1 / 60 / 525, namely 31.7 µs. So two lines would be 63.4 µs. This is close enough to exactly one timer count (64 µs). So OCR1B is set to zero (being zero-relative, making it zero gives a count of 1).
Timer 1 is configured to "clear B on compare" which effectively means that it toggles the output pin (D10 on the Uno) so it is high for the duty cycle width (64 µs) and low the rest of the time. If you wanted the opposite sync pulse polarity, change CLEAR_B_ON_COMPARE to SET_B_ON_COMPARE.
The timer is also set up to generate an interrupt, which is used to tell the code that we are starting another vertical cycle, by setting the line count to zero:
ISR (TIMER1_OVF_vect)
  {
  vLine = 0;
  messageLine = 0;
  backPorchLinesToGo = verticalBackPorchLines;
  } // end of TIMER1_OVF_vect

Horizontal sync
Horizontal sync pulses tell the monitor when to start drawing each line.
To calculate the horizontal sync frequency we need to divide the overall frame rate (60 Hz) by the number of total lines (525 if you count the sync pulse itself, and the front and back porches).
In other words:
 (1/60) / 525 * 1e6 = 31.74 µs

We also need to know the sync pulse width. That is documented to be 96 pixels, so we need to know the width of one pixel. That would be the figure above, divided by 800 (being the total screen width including the sync pulse, and front and back porches).
Thus that is:
((1/60) / 525 * 1e9) / 800 = 39.68  ns
1 / (((1/60) / 525 * 1e6) / 800) = 25.2 MHz

So our pixel width is 39.68 ns and the pixel clock is 25.2 mHz.
The horizontal sync pulse width is 96 pixels, so we want a pulse of:
96 * 39.68 ns = 3.8 µs

Generating horizontal sync pulses
Now we are ready to set up the timer for the horizontal sync pulses:
  // Timer 2 - horizontal sync pulses
  pinMode (hSyncPin, OUTPUT);
  Timer2::setMode (7, Timer2::PRESCALE_8, Timer2::CLEAR_B_ON_COMPARE);
  OCR2A = 63;   // 32 / 0.5 µs = 64 (less one)
  OCR2B = 7;    // 4 / 0.5 µs = 8 (less one)

The clock period is 62.5 ns (1/16000000). By applying a prescaler of 8 the timer counts up once every 0.5 µs. So to get a period of 32 µs we need to count up to 64 (32 / 0.5 = 64). Since the timer counts are zero-relative we set OCR2A to count up to 63. This sets the frequency of Timer 2.
Then we need to set the pulse width by putting the correct value in OCR2B. We want a pulse width of 96 pixels (3.8 µs). So OCR2B is set to 7 (being zero-relative, making it 7 gives a count of 8, which is 4 / 0.5).
Again, if you wanted the opposite sync pulse polarity, change CLEAR_B_ON_COMPARE to SET_B_ON_COMPARE.
The timer is also set up to generate an interrupt, which has the sole purpose of waking the processor up from sleep, so it can draw each line with exactly the same delay after the pulse. If it wasn't asleep, there would be a variation of two to three clock cycles (since an interrupt cannot occur during a single instruction) and this gives very bad-looking "jitter" on the screen.
ISR (TIMER2_OVF_vect)
  {
  } // end of TIMER2_OVF_vect

Pixel data
Now things get tricky ...
Let's see how long we have to draw 640 pixels:
((1/60) / 525 * 1e9) / 800  * 640 = 25396.82 ns (25.39 µs)

It just can't be done on this processor. The clock period itself is only 62.5 ns, so there is no way we can output a pixel every 39.68 ns (that is: 25396.82 / 640 = 39.68).
The fastest way we can get bits "out the door" is using the SPI hardware. That can run at a maximum clock rate of twice the system clock, that is, one pixel every 125 ns. So we will have to settle for having the pixels 4 times as wide. A horizontal resolution therefore of 160 pixels. Since we will display 8-pixel characters, that gives us 20 characters per line.

Summary
Even at 25 MHz processor speed (which exceeds its spec) you won't be able to clock out pixels fast enough for 640 pixel width (since the fastest SPI speed is half the processor clock speed).

I would expect that so long we can feed the signal fast enough that would be enough.

That's the tricky bit. To output data you have to do more than merely send it. You have to read it from memory, so it would take a least a couple of clock cycles to do that.

Example of working at that resolution
A screen shot of my sketch in action (160 characters wide - 640 pixels and 30 characters high - 480 pixels, which is 16 pixels each as they were "doubled" in height to make them look in proportion). The font data was 8x8 pixels, and thus they appear as 16x16 on the screen.

So does that mean that there really isn't a direct relation between clock speed and resolution? Other than, the clock must be faster than this

To work even at that speed the processor speed needs to be a multiple of the VGA clock, or close enough for the monitor to accept. (Looking at my figures the pixel rate is not in fact a multiple of 39.68 ns, so I am guessing that my monitor was able to adjust).
You could get better results by having a system clock which was an exact multiple of 39.68 ns (around 25 MHz - precisely 25.201613 MHz) - which is what you suggested in the question. However that just gives more accurate timing, you would still get similar resolution to what I show here.
So yes, to work on more monitors you should have a direct relation between clock speed and resolution.
I seem to have a 25.175 MHz crystal in my parts drawer, so perhaps I experimented with this a while back. Of course, you have to recalculate the other timings if you use that, and the processor is running out of spec.

It just can't be done on this processor. - I have managed to generate VGA at that kind of resolution using an 80MHz PIC32 and it was very very tight even then - it requires special optimizations to get the maximum speed out of it. Not much processing time left for anything else, and certainly no chance of any other interrupts being used - I even had to have the VGA code generate its own vsync-linked millis() since the system millis() could no longer run. No chance on a little Arduino ;)

So does that mean that there really isn't a direct relation between clock speed and resolution? Other than, the clock must be faster than this.

See my added notes in the answer.

The empty ISR can be conveniently defined as EMPTY_INTERRUPT(TIMER2_OVF_vect);.

I wrote that when I was young and foolish. ;) - However you are right, that would be faster.

Out of curiosity, what would be a better off the shelf chip for generating a VGA 640x480 60Hz signal? Preferably something that is not super over powered, easy to use, and preferably open source.

Take a look at http://www.gammon.com.au/forum/?id=12623 - that guy used an AD725 chip which outputs composite video in NTSC or PAL. This probably doesn't really answer your question, but it is interesting. Also search for tinyvga - there are various chips and boards around for generating VGA for microcontrollers.

That is awesome, thanks. I was looking for that post but I couldn't find any specifics. I thought that was done on an uno and it was one of the reasons I thought this was possible.

Yes, but he didn't have 640x480 resolution. From the linked page: The game has a display resolution of 104x80 with 256 colors.

In case someone finds this page later and wonders what I ended up using. I found an fpga board that was open source and used a Spartan chip called gameduino. It was cheapish, and readily available. More than enough for my prototyping needs.


text:
Hooking up the Arduino to a car's 12v
I am planning an uno based tachometer for my truck, which doesn't have a tachometer. With nothing in place for me to get a reliable signal, I started looking at other sources to read the rpm from the engine.
It seems to me that an engine should affect the power every time a cylinder fires --the power should spike in some way. So in theory I should be able to hook up to the 12v cigar lighter, count the spikes, and calculate the rpm. It would only need to be accurate within 500 rpm or so.
This is a two part question.

How would I hook up the arduino to the 12v system? As in, what should I do to protect the io of the arduino?
How would I gather the test data to see if this is possible? Is there a way to hook the arduino up to the truck via the 12v and my computer via usb and send data back that I can record or monitor?

How would I hook up the arduino to the 12v system? As in, what should I do to protect the io of the arduino?

First you're going to need to do some investigative work. You're going to need to beg, steel, borrow (or use your own if you have one) an oscilloscope. You can then use that to examine the 12V power coming from the cigarette lighter.  Armed with that you can then tell:

If there is any power fluctuation from the engine, and
What form that fluctuation takes.

If there is any fluctuation it will appear as an AC component imposed on top of the 12V DC voltage. Removing the 12V DC offset is simple enough. All you need to do is pass the power through a high pass filter. That's simply a capacitor and a resistor. You need to ensure that the cut-off frequency of the filter is below the lowest frequency you want to measure (idle frequency) yet high enough to cut out the DC component effectively.
Once you have done that you can then clip the waveform using a diode to protect against negative voltage, and a resistor and zenner diode to limit the positive voltage.
For instance, something similar to the following (it's not exact - the source isn't creating spikes, but an offset low duty cycle PWM, which is kind of similar for demonstration purposes):

The first point measured is the 12V signal with big high voltage spikes. Next the power has been high-pass filtered by the RC network and the lower portion of the waveform clipped by the reverse biased diode. Following that the zenner diode clips the upper portion of the waveform to within safe limits for the Arduino. The 100Ω resistor with the zenner is there to limit the current through the zenner.
Don't take any of those values as gospel, since the signal I am filtering there is not your signal. You need to know your signal first before you can work out exactly how it should be filtered, but that gives you the basic idea of how it can be done.

How would I gather the test data to see if this is possible? Is there a way to hook the arduino up to the truck via the 12v and my computer via usb and send data back that I can record or monitor?

Connect the filtered and clipped signal to an interrupt input on the Arduino. Count the pulses within a given time period (1 second, 5 seconds, whatever you choose) and multiply up for number of pulses in a minute. Don't forget to then divide by 4 for a 4-cylinder engine, since I would expect you would see 4 sparks per revolution. How you then gather the data is up to you. It might be simplest to add an SD card shield to your Arduino and record the data onto an SD card. You can then place that card into your computer to process the data at your leisure.
The best way to power your Arduino is, of course, direct from the truck's power. The safest way, because of all those nasty spikes in the power, is to use car USB phone charger adapter. Plug that into the USB of the Arduino and all should be nice and happy.

I was hoping I wouldn't need to acquire an oscilloscope. Is there any way to figure out the filter's values without one, or to build a beefy way to hook up the arduino to 12v without the filters in place to get the numbers?


text:
How to switch on 32A/240VAC with Arduino?
I have an air conditioner switch rated at 32A/240V AC - how do I turn this on using Arduino and Relay.
I'm based in India and I am unable to find a relay switch rated higher than this.
I don't want to try anything that results in a fire hazard. My aim is to switch on the AC with my mobile phone. I'm using Arduino Uno with a 2.4GHz transceiver for communication.

Google is your friend; for instance http://www.seeedstudio.com/wiki/Grove_-_SPDT_Relay%2830A%29, http://www.ebay.com/bhp/30a-relay, http://yourduino.com/sunshop2/index.php?l=product_detail&p=327 and so on.

Does the AC have a remote? If yes, you can possibly emulate it.

You need to look beyond "Arduino compatible" peripherals. All relays are Arduino compatible if you understand even the basics of electronics. For 32A you might stand a better chance finding a "Solid State Relay", but it depends on what stockists are available in India.

Just go with a solid state relay: you can search on ebay for SSR-40DA (240V, 40A, from China around 4$) or, better, SSR-100DA (240V, 100A, from China around 6$). For 32A you should definitely mount it on an heatsink (they sell quite a lot of them on ebay).
The main advantage of that kind of SSR is that you can command them directly from the arduino. No transistors, no limiting resistors, just connect the ground and the pin and you are done.
With a relay my arduino halted often (probably because of the 5V-12V boost, but it was necessary to drive the 12V relay). In the end I switched to an SSR and... Works like a charm. And since it is quite cheap I suggest you to use it.

I don't want to try anything that results in a fire hazard.

That's a good idea.
Besides those toy relays there are real ones:
440 V AC * 63 A (Around there, you can find smaller ones too)
BTW: Don't rely on what's printed on the relay itself, with cheap Arduino relay modules. 230V and some current need proper handling by the PCB board as well (size and distance of the copper tracks on the scondary side)
If you want a solution that could be certified (or certifiable) as "safe" there probably won't be an Arduino involved or being built by anyone asking questions like you do  ;(   (sorry)

What about staying with small relay and just add a contactor? The relay will deal with the low current 230v to drive the contactor and the contactor would deal with the high current.

As in https://en.wikipedia.org/wiki/Contactor

The simple answer is: you need to find a relay rated high enough for the voltage and current. There's no way you can make a small relay handle a large current, and relays cannot be joined together to share the load.
If a relay is not available in your country (and I seriously doubt that - you're probably just looking in the wrong places - instead of looking for things on Amazon or eBay try looking at proper industrial electronics suppliers) then you would have to come up with something more creative.
How about designing and building a small electro-mechanical system that physically changes the position of the existing switch for you? Solenoids to press the right bits of the switch, or motors to turn the right bit round, etc.


text:
How to test Arduino behaviour on Windows?
Hello fellow Arduino enthusiasts,
I created an Arduino project for a Mega2560 board in Microsoft Visual Studio.
Before loading the code on the board I want to test it on my Windows desktop computer.
I'd like to automatically provide input (e.g. with a file containing some values) for the 4 hardware Serials as well as the I2C/Wire bus and check their output for validity.
How can one achieve that?
I read about mocking (e.g. "Arduino-mock") but this does not seem to be what I need since it is more a way of ignoring the absence of object implementations.
Are there maybe some simulators that can automatically generate input and create output logs or even check the output?
Thank you for any advice!

You can check this thread for some ideas: http://arduino.stackexchange.com/questions/61/can-i-program-for-arduino-without-having-a-real-board The question is a couple of years old, but not much has changed since then. There are a whole bunch of half implemented solutions that don't work very well. The best way to test Arduino code at this point in time is still to just run it on the hardware.

Shameless plug: check out this I2C test example: https://iobtoolkit.com/docs/tutorials/i2c_python_mcp7940n_test.html
This project is in active development. If you need some specific I/O function it'd like to hear from you.


text:
Arduino Uno with UsbSerial Android library w/ baud rate over 9600?
I am having no issues talking to Android at baud rate of 9600. But once I raise the baud rate to anything higher Android seems to become deaf. When I try to read the Serial output using putty all seems fine.
Has anyone had success with baud rate over 9600 when talking to Android?
I am using the felHR85/UsbSerial library.

I have no enough reputations to make a comment so I will drop my two cents here.
Are you changing the baudrate at both sides?
I have been using the arduino's built-in UART library for a while using different baudrates with no problems. Your problem could be an issue related to the library you are using.

Yes sir, I set the same speed on both sides. On Arduino I use the default Serial library too. The issue probably lies on the Android side.

Seems like there is a bug in the library.


text:
Running Multiple Languages on Arduino
This is mostly a conceptual question. Is it possible to have two scripts running on an Arduino, where one is a Julia script, and one is a Python script or something like that?

julialang.org refers to  “Julia’s LLVM-based just-in-time compiler”.   If you get LLVM bitcode from the compiler, it might be possible to put that through the AVR Backend To LLVM to get an assembly language or ELF file to download to an AVR.

Basically no, because you can't run either Julia or Python, let alone both together.
Bear in mind also what an Arduino is (what most of them are, anyway): a low (computational) power microprocessor with a tiny amount of RAM. No operating system, no multi-tasking. Not in the same league as, for example, a Raspberry Pi.

Thats a pretty straight forward answer lol! Thanks. I'm not surprised by Python because it's interpretted, but Julia compiles into machine code, so I thought that would at least work.

And basically correct one. There is ofcourse possibility to run interpreted langs on Arduino, even python ( http://stackoverflow.com/questions/8114916/is-there-a-way-to-compile-python-code-onto-an-arduino-uno ), there are some OS for it too and it can use external memory somehow, but Arduino is better used for other tasks, where you need small platform for some small things, which should be lightweigth and fast and usually solve just one or two tasks.  Cars, motocycles, bycicles and walks are also best fit for different tasks :)

What about Arduino DUE? It's an ARM based board.


text:
What does a delay(0) actually do?
I've seen some code where the developers add delay(0), it doesnt make sense, what does it do? Delay with zero milliseconds, why?
bool DFRobotDFPlayerMini::waitAvailable(unsigned long duration){
  unsigned long timer = millis();
  if (!duration) {
    duration = _timeOutDuration;
  }
  while (!available()){
    if (millis() - timer > duration) {
      return false;
    }
    delay(0);
  }
  return true;
}

Delay (traditionally) has two functions that it performs:

Wait for a period
Yield processing to other threads through the yield() weak symbol.

By using a delay(0) the author thinks they are saying "I don't want to delay here, but if anything is using the yield() function it can run now."
However, that is not correct.
The code for delay() in the AVR core looks like this:
void delay(unsigned long ms)
{
    uint32_t start = micros();

    while (ms > 0) {
        yield();
        while ( ms > 0 && (micros() - start) >= 1000) {
            ms--;
            start += 1000;
        }
    }
}

You can see that, as well as delaying for a period, yield() is regularly called. However that only ever happens if ms is greater than 0. If you pass 0 as the delay length then the delay() function essentially does nothing at all.
Now it could be that an earlier version of the core had yield() always being called even with ms==0, but the current version doesn't. Maybe this is a hangup from an old coding style.  But for the current core if you want to yield you must explicitly call yield() or delay for at least one millisecond.

esp8266 delay has yield with 0 delay and esp32 delay directly calls vTaskDelay in SDK. The mded cores call RTOS thread sleep.

Is there anything to yield to in the AVR core?

@AndreKR Not in the core, no. yield() is defined "weak" so that you (or a library) can override it to implement a form of crude cooperative threading.

Yepp this is exactly what i saw when looking at the delay() method. That made it more confusing. So it does nothing since milliseconds is lower then zero.

Not "lower than" but "not greater than". Subtle difference.

@Majenko Sorry =P


text:
Arduino receives no external UART comms after Serial.begin(9600)
I face the following issue. I connected my RasPi (3b) with an Arduino Uno via RX/TX and a logic level converter. UART comms from the RasPi to the Arduino and vice-versa work fine on minicom and serial monitor. It also works fine from my qt program to the serial monitor, but as soon as I start a Serial.begin(9600,8N1) or Serial.begin(9600) function on the Arduino there seems to be no communication anymore at all between the two. Neither the expected result (toggle an LED, works from serial monitor), nor any blinking of the tx/ex LEDs onboard anymore. Issue occurs no matter if I provide power to the Arduino via USB or the 9v powercable. Any suggestions?

Are you saying the USB connection works, but as soon as you try and use pins 0/1 the USB connection breaks? That's logical, since the USB connection uses pins 0/1. There is only one Serial on the Uno, and that is pins 0/1, whether you directly wire them or use the USB port.

The funny thing is it works when my raspberry is wired to the Arduino and the Arduino is connected to my Mac on USB to read the serial monitor (there is no connection between the raspberry and the mac)

Mac (USB) - Arduino - (Wire TX/RX) Raspberry. Even if I disconnect the Mac (and toggle an LED for example when anything is received on the Arduino) nothing happens...

"no external UART comms ...": in those cases, try to see if internal UART comms works first.

Solved. I double crossed the rx/tx connection which made it wrong again... stupidity attacks


text:
String(int) function stopping the Arduino
Well I am trying make an application with arduino leonardo and GSM Shield. There are conditions if, else if, else .. etc
  if (smsMetni.indexOf("DURUM") != -1) {
    Serial.println("SMS income");
    String temp= String(analogRead(LM35_pin) * 0.48828125);
    String temp2 = "Hava " + temp + " derece.";
    char tempSMS2[] = "";
    temp2.toCharArray(tempSMS2, 30);
    Serial.println(tempSMS2);
    Kapadokya.smsGonder(gonderilecekTelNumarasi, tempSMS2);
  }

After the last line "Kapadokya.smsGonder(gonderilecekTelNumarasi, tempSMS2);" program stopping I watching serial monitor there is no notification or error. just stopping.
If I change those lines and remove String(analogRead(LM35_pin) * 0.48828125) :
    String temp= String(analogRead(LM35_pin) * 0.48828125);
    String temp2 = "Hava " + temp + " derece.";

and just write like this, it works very well.
String temp2 = "Hava  derece.";

maybe you think there is a problem with LM35, even if I change it String(analogRead(LM35_pin) * 0.48828125); with String(30);, it doesn't work again. after the last line it is not continue.
only one sollution I've found if add delay(500) after each line it works but my codes looks ugly with this. are there any solution.

Without seeing the whole program code I suspect you are running out of memory because you are using the String class extensively. Try NOT to combine strings into a new string object as you need twice the space and then only copy its content into a TOO SMALL tempSMS2 array that has the size of 1 (the terminating null character).
Just serial print the string literals as you have them at hand. Also use the L-Macro to keep the string literals in program memory and not in RAM. Serial.print is also perfectly capable to print numbers. No need to convert them into String first.

You should avoid String on the Arduino. It will cause random crashes. However that's not your issue. Your issue is trying to copy the data into an array that is too small.
char tempSMS2[] = "";

That creates a one byte array which contains just a \0. You then try and squeeze your String data into it and it of course overflows all over the rest of your variables and data.
A better solution is to work directly in char arrays. It is a little trickier though:
First convert your float to a string:
char tempFloat[8];
dtostrf(analogRead(LM35_pin) * 0.48828125, -7, 3, tempFloat);

Then build up your string:
char tempSMS2[30];
strcpy_P(tempSMS2, PSTR("Hava "));
strcat(tempSMS2, tempFloat);
strcat_P(tempSMS2, PSTR(" derece."));

Wow. it looks amazing. but if add Serial.println(tempSMS2); at the last line only printing " derece". can you fix it.

Oops, that last strcpy_P should have been a strcat_P.

(PGM_P)F("foo") can be written more simply PSTR("foo"). Actually, the F() macro uses PSTR().

@EdgarBonet Yeah, I can never remember which is which of these macros. TBH I never use them, but then I never use AVR unless the client specifically requires it.


text:
USB-C to USB-C cable Arduino is not responding even not powered by this cable
Hi I want to connect arduino NANO to my laptop with Type-C (USB-C) ports (on below image left side [4] and other side 3). Now I bought a USB-C to USB-C cable, because it appeared to be the right tool, but the Arduino is not even powered by this cable. if I use regular USB 3.2 Gen 2 Port (on below image [5]) everythings for fine. but this usb-c ports not recognize the Arduino NANO even NANO's power LED is not switching ON.
On the other hand If I plug in my phone to this usb-c cable it works both ports. It means that cable is working good. I have changed 2 times cable stil not responding.
On the docs, it look usb-c and regular usb 3.2 ports works same. But why usb-c ports not working with Arduino. also my laptop is MSI GS66

I'd appreciate if anyone has a solution or an idea to fix it. Thanks!

Maybe that port does only provide power if you draw enough power from it (like powerbanks often do). When the power LED isn't on but the Arduino works with a USB3 to USB-C cable from another port the problem is not with the Arduino. You can verify the absence of power by measuring the voltage between 5V and ground.

does Arduino Nano have a USB-C connector?

@jsotola https://urun.n11.com/arduino-urunleri-ve-setleri/type-c-cikisli-yeni-nesil-arduino-nano-type-c-kablo-hediyeli-P508671734

@jsotola Not the official Nanos, but there are many clones that do have USB-C.

@chrisl just because it has a USB-C connector, it does not mean that it has the circuitry to make it a USB-C interface

The pair of 5.1K resistors (CC1/CC2 pull-downs) seen in their product picture constitute the only extra circuitry a type C connector requires over the original  Nano's mini-B.  For C to C it's important that CC1/CC2 are doing their job because the negotiate the direction of the connection. For an A to C cable CC1 and CC2 and their resistors go unused. What I'm getting from this is that CC1/CC2 are failing to be pulled to GND, because one of the board/connector/jack are bad. If one (but not both) of the CC# lines are bad, rotating the cable 180 degrees would switch to the good CC#.

That Nano is not USB-C compliant. Yes, it has the connector, but it doesn't do all the required handshaking to put the USB-C port on the laptop into host (and provide power) mode. This is needed because those ports are also power inputs and have to be told to output power - otherwise plug in power to them and bang horrible things happen.
You have to use the larger USB 3.2 ports which are always power providers and never power consumers.

I understood. thanks. you mean if I use usb-c to usb-b converter cable arduino uno should work. or  usb-c to mini usb can work original nano.


text:
which is the best way to declare Serial while creating Arduino library?
Well, I am trying make a library for HMI display. display and Arduino comminicate with Serial. So I will so many times Serial port. Generally I will use Serial.write commend. if I examine other libraries, there are lots way to declare serial. Why and which is the best I want to learn.
there I have seen declaring Serial methods.
Method 1
in library .h file
nothing

in library .cpp file
#include <SoftwareSerial.h>

SoftwareSerial SIM(RX_PIN,TX_PIN);

void KapadokyaGSM::basla(){
    SIM.begin(9600);
  _tampon.reserve(255);
}

Method 2
in library .h file
public:
EasyNex(HardwareSerial& serial);
...
private:
HardwareSerial* _serial;
...

in library .cpp file
EasyNex::EasyNex(HardwareSerial& serial){  // Constructor's parameter is the Serial we want to use
_serial = &serial;
}

void EasyNex::begin(unsigned long baud){
_serial->begin(baud);  // We pass the initialization data to the objects (baud rate) default: 9600
delay(100);            // Wait for the Serial to initialize

Also I have seen declaring with Stream but now i didnt find example codes. So finally Can anyone tell me what is the best for declearing Serial in library. it can be for only hardware serial or both

The basic concept that you're asking about is called dependency injection.

As regards the use of Stream:
I usually use Stream instead of HardwareSerial because:

It allows the use of other serial devices, like SoftwareSerial or USBSerial that aren't "Hardware" UARTs.
It even allows the use of non-serial systems, like sending data over networks or wireless devices

However it means:

The user has to manually initialize their serial object / device as Stream has no facility for setting things like baud rates.

Can you show me a tutorial, or github library which is using Stream.

@mehmet try this one: https://github.com/MajenkoLibraries/ICSC/tree/master/src

There is no best way, the first is using a global variable, being static. The second is dynamically (or at least to pass a serial instance).
It depends on your use

If you want your code always to work with the same declared serial (hardware or serial) instance, you can use the first method, as it is the easiest.
If you want your serial hardware port to be flexible (your code to work e.g. with a selectable hardware serial port on an Arduino Mega), you need the second.
If you want to your serial port to be either software or hardware, you can use the second method, but you need another type (not the mentioned HardwareSerial class. I don't know by head the parent class of SoftwareSerial and HardwareSerial (The Stream class you mentioned could be a common parent class).

there is no Serial base class

Can i ask a last question, why second method uses "->" and Why not "." Such us _serial.begin(baud). Is this totally same

If you have access to the object itself, e.g., Serial, you can say Serial.println(). If your library only has a pointer to the object, you have use ->, the dereference operator: serialPtr->println(). The result is the same: calling the object's 'println()' member. The difference is in how the compiled code gets you to that member.

@Juraj Thanks for that addition (I was not sure, so I removed the comment about not being sure and the statement in my answer).

@mehmet, it is common C++ object member access you asked about


text:
How to convert bool array to byte?
I have following problem:
I'm reading 8 bit signal from one Arduino pin and store all informatin in bool array. Now I want to convert this array to single byte in decimal. How to do this?
I've tried this:
bool ID[8] = {0, 0, 0, 0, 0, 0, 1, 1};
int recivedID = int(ID);

and
bool ID[8] = {0, 0, 0, 0, 0, 0, 1, 1};
int recivedID = ID.toInt();

non works.

Why save it in a bool array in the first place? You could make a byte and set each bit individually. That will be more efficient.

try with this:
int recivedID = ID[0] | (ID[1] << 1) | (ID[2] << 2) | (ID[3] << 3) | (ID[4] << 4) | (ID[5] << 5) | (ID[6] << 6) | (ID[7] << 7);

which is the same as
int recivedID = 0;
for(int i=0; i<8; i++){
   recivedID |= ID[i] << i;
}

I haven't tested it though.

byte BoolArrayToByte(bool boolArray[8])
{
  byte result = 0;

  for(int i = 0; i < 8; i++)
  {
    if(boolArray[i])
    {
      result = result | (1 << i);
    }
  }

  return result;
}


text:
Best way to detect tilt using MPU 6050
I want to make a gesture controlled car using this IMU.. What is the simplest way to detect tilts? I've seen many programs on the Internet that calculate the angles but is this really necessary?
Why can't we just get components of acceleration in the x, y plane and then detect tilts..Pls tell me how to do this!

Well suppose you have a starting position, let's say 0 degrees, then once you detect and angle change, let's say 10 degrees, you know that there is a tilt of 10 degrees on one of the 3 axies.
The MPU6050 is a 6DOF, meaning 6 Degrees Of Freedom. This means that it can detect acceleration on axis: x, y, and z and it can detect gyro angles on axis: yaw, pitch, and roll.
For the best accuracy, use a mix of both acceleration and the gyroscope. This is the best way to calculate position. Heck, the Apollo space program used a gyro and accelerometer to navigate from planet Earth to the Moon.

How could I just use accelerometer readings to detect the tilt??

You can't, you mainly use a gyroscope for tilt detection, but, in some cases where super accuracy is necesssary, a hybrid of both is great. It is very complex so I don't really want to go in much detail. The MPU6050 has a gyro, why not use it?


text:
Arduino MPU6050 Control 2 Servo
I'm new to gyroscope and accelerometer and am working on my project to control servo with Arduino Uno R3 based on the reading from InvenSense MPU6050 6DOF gyroscope and accelerometer. I've found the a same sheet of code from different websites.
Website 1_http://www.projehocam.com/wp-content/uploads/mpu6050-2-servo.txt
Website 2_http://www.instructables.com/files/orig/FLY/GZAL/IDIN48PC/FLYGZALIDIN48PC.ino
And from this part of the code, I couldn't understand the servo.write part...
    #ifdef OUTPUT_READABLE_YAWPITCHROLL
        // display Euler angles in degrees
        mpu.dmpGetQuaternion(&q, fifoBuffer);
        mpu.dmpGetGravity(&gravity, &q);
        mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
        Serial.print("ypr\t");
        Serial.print(ypr[0] * 180/M_PI);
        Serial.print("\t");
        Serial.print(ypr[1] * 180/M_PI);
        myservoY.write(int(ypr[1] * -180/M_PI)+90);   // Rotation around Y
        Serial.print("\t");
        Serial.println(ypr[2] * 180/M_PI);
        myservoX.write(int(ypr[2] * 180/M_PI)+90);   // Rotation around X
    #endif

Why is the operation (int(ypr[1] * -180/M_PI)+90) ??

ypr contains the Yaw, Pitch and Roll. It is provided in radians.
Servo.write takes degrees.
Multiplying radians by 180/PI converts it to degrees.  Adding 90 centralises it around the 90 degree point (half way) of the servo.


text:
Is it possible to use UART0 freely when connecting ESP32 s3 via USB (D+, D-)?
I've designed a test PCB that utilizes an ESP32 S3 and testing pins. During program uploads, I use the USB interface over GPIO20 and GPIO19 as D+ and D-. Everything works fine in this configuration. However, I've encountered an issue where UART0 becomes inactive after using the USB interface. Now, I want to connect the TX pin of a GPS module (NEO 6m) to UART0's RX pin, but I'm unable to do so. It's impractical to run the code as is because when data is received on RX0, it floods the continuous serial screen. I'm looking for a solution to completely disconnect UART0 from the USB interface so that I can use it independently.
In Short How I can receive date from UART0 and than Serial.print to Serial monitor over the USB interface?
#define RXD2 6
#define TXD2 7

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  while (!Serial)
    delay(200);
  Serial.println("start GPS...");

  Serial2.begin(9600, SERIAL_8N1, RXD2, TXD2);
}

void loop() {
  while (Serial.available()) {
    Serial.print(char(Serial.read()));
  }
}

Serial is 'com' port over USB on esp32 with native USB (and "USB CDC On Boot" option selected in Tools menu). For UART0 the core then creates Serial0.
From documentation:

To use the UART as serial output, you can use Serial0.print("Hello World!"); instead of Serial.print("Hello World!"); which will be printed using USB CDC.


text:
How 2 bytes can produce negative number, mind blowing?
I am trying to use LoRAWAN and sending tempurature values as less bytes. I found that way and tested it works fine it can send negative and positive numbers as 2 bytes instead of "float" as 4 bytes or "double" as 8 bytes but still I can not understood how this code produce int celciusInt = (bytes[0] & 0x80 ? 0xFFFF0000 : 0) | bytes[0] << 8 | bytes[1]; negative numbers. as a result it makes 4 bytes for nagetive numbers but ttn network still see this as 2 bytes and mind blowing
TEST code:
byte bytes[2];
int derece = -3556;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  delay(3000);
}

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

  bytes[0] = derece >> 8;
  bytes[1] = derece & 0xFF;

  int celciusInt = (bytes[0] & 0x80 ? 0xFFFF0000 : 0) | bytes[0] << 8 | bytes[1];

  Serial.println(celciusInt);

  delay(3000);
}

OUTPUT:
-3556

As a result -3556 number is returning 0xFFFFF0E4 value and how this make negative numbers still I did not understant. So many times I read chatgpt or etc. but still not understood.
Can you explain it to me like you would to a 5-year-old?

how would you encode negative numbers? the sign in the first bit for example?

In reality computers doesn't know numbers, just bits (high and low). Then some arithmetic operations may be added on a CPU, but with a well known bit encoding (and it depends on the data). Integers (so signed) may be encoded with sign-bit, 1-complement, 2-complement (and for sure more methods). floats have totally different encoding, BCD (now seldom) are a mix bag. On youtube Ben Eatan describe basic of electronics until building a simple CPU (I think in one or two videos go also on arithmetic and encoding). The series is very long (but you get all, nothing hidden).

is it still mind blowing if you think How 2 bytes can represent negative number?

@jsotola Still reading ;) I am reading the assignment that Edgar Bonet gave me. If the number is signed, the first bit indicates whether it is negative or positive. If the number is unsigned, the first bit is considered as a normal number. The maximum value for an int16_t is 32767, but for a uint16_t it is 65535. In short, the number does not become negative; it becomes positive or negative depending on how we define the number type

... Continue, For example, the number -55 in binary is 11001001, but when we enter this binary value into a calculator, it outputs 201. Why? Because the calculator always assumes the number is positive.

this might help ... https://www.rapidtables.com/convert/number/hex-to-decimal.html?x=8000 .... https://www.rapidtables.com/convert/number/hex-to-decimal.html?x=FF00

I won't explain it like you are 5-years old because it would take to
much effort, you are a grown up, and you are capable of reading articles
yourself. So start by putting aside ChatGPT, and instead read the
Wikipedia article Two's complement. I mean, read carefully,
taking all the time you need to reach a complete understanding.
Now, the number −3556 would be written in binary as either
11110010.00011100

or
11111111.11111111.11110010.00011100

depending on whether your Arduino uses 16-bit or 32-bit integers (it
varies across Arduino boards). The assignments to bytes[0] and
bytes[1] extract the two least-significant bytes of this number:
bytes[0] = 11110010 (in binary)
bytes[1] = 00011100 (in binary)

The assignment to celciusInt reconstructs the number by ORing together
three terms:
11111111.11111111.00000000.00000000 = (bytes[0] & 0x80 ? 0xFFFF0000 : 0)
00000000.00000000.11110010.00000000 = bytes[0] << 8
00000000.00000000.00000000.00011100 = bytes[1]
───────────────────────────────────
11111111.11111111.11110010.00011100 → assigned to celciusInt

Note that the first term in sign extension (you know what this is,
because you read the article I mentioned, didn't you?). It is only
needed if you want the result as a 32-bit integer. It would be simpler
to forego sign extension and instead store the result in a 16-bit
integer:
int16_t celciusInt = uint16_t(bytes[0]) << 8 | bytes[1];

Note that the code may work even without the cast of bytes[0] to
uint16_t: this cast is only needed to avoid signed integer overflow,
which in C++ is undefined behavior.
Edit: Note that a yet simpler way to split and reconstruct the
number is to use a union. This lets you have a 16-bit integer and an
array of two bytes share the same memory. You can then write to the
integer and read back the bytes or vice-versa:
// A 16-bit integer and a pair of bytes sharing their memory.
union {
    int16_t value;
    uint8_t bytes[2];
} packet;

// Split a 16-bit integer in two bytes.
packet.value = -3556;
Serial.println(packet.bytes[0]);  // -> 28
Serial.println(packet.bytes[1]);  // -> 242

// Reconstruct a 16-bit integer from its bytes.
packet.bytes[0] = 214;
packet.bytes[1] = 255;
Serial.println(packet.value);  // -> -42

Beware of endianness though: unlike in the previous code, bytes[0]
here is the least-significant byte. Practically every Arduino and
computer in use today is little-endian, so this may not be an issue.
However, there are some communication protocols that are big-endian, so
you should be aware of the issue.

Re:  int16_t celciusInt = uint16_t(bytes[0]) << 8 | bytes[1]; You still have the potential for overflow even with the cast, it's just an overflow you get while storing result into the int16_t celciusInt rather than while calculating the result of the bit-wise or.

@timemage: Nope. Storing an out-of-range value in an integer is not technically considered an “overflow”, and is perfectly legit. Actually, it is implementation-defined until C++20, but GCC, like any sane compiler, does the only sensible thing.

@EdgarBonet that makes sense now

@EdgarBonet I guess I just have it in the category of "non-portable". But it is nice that they've codified the common behaviour in a newer standard.

@EdgarBonet I think union can not working with in javascript. Such as I am sending data from arduino to lorawan network (TTN) there is payload formatter. whatelse I tried union can not defined. So I am using for converting at TTN var celciusInt =  uint16_t(bytes[16]) << 8 | bytes[15];

@mehmet: If you want to decode a binary packet in JavaScript, the right tool is a DataView. This lets you extract numbers from any standard C type (uint8_t, int16_t...) at an arbitrary offset in the buffer, with the endianness you want. E.g. let response = await fetch(data_url); let buffer = await response.arrayBuffer(); let view = new DataView(buffer); let celciusInt = view.getInt16(15, true);

I suspect you mixed-up with the Endianness. I've seen many people get it wrong when they deal with Lora communication.
For Lora communication, data are send in Big Endian, while Arduino (and almost all modern computers) are storing data in Little Endian.
So if you are sending an integer 7410 (which is 0x1cf2 in hex) via Lora, 0x1c get send first, followed by 0xf2. However, when stored in the Arduino, if you are storing the data based on the transmission sequence, you would end-up storing 0x1c as first byte in data[0], and 0xfc as the 2nd byte in data[1]. So the data would looks like as 0xf21c when retrieve from Arduino in Little Endian manner, 0xf21c is  the 2-compliment of -3556 in a sign integer!


text:
How to convert a String to Hex array
I am trying use a HMI display. If I want to send a data, for example I want to write "TOPWAY" to 0x00000080 address it should like that:
    Serial.write(0xaa); // packet head
    Serial.write(0x42); // VP_N16 string write command
    Serial.write(0x00); // VP_N16 address
    Serial.write(0x00);
    Serial.write(0x00);
    Serial.write(0x80);
    Serial.write(0x54); //T
    Serial.write(0x4f); //O
    Serial.write(0x50); //P
    Serial.write(0x57); //W
    Serial.write(0x41); //A
    Serial.write(0x59); //Y
    Serial.write(0x00); //string end with "\0"
    Serial.write(0xcc); // packet tail
    Serial.write(0x33); // packet tail
    Serial.write(0xc3); // packet tail
    Serial.write(0x3c); // packet tail

I want to make a method like SendString(String abc) to send that like above. I need convert string a hex array and call in Serial.write(array[i]). Can you hep me?

There is no such thing as a hex array. Everything is all just numbers. Even letters are numbers. Your string is already an array.

Serial.print("TOPWAY"); should do it

@Juraj you mean like that for total query like above: Serial.write(0xaa);
Serial.write(0x42);
Serial.write(0x00);     Serial.write(0x00);
Serial.write(0x00);
Serial.write(0x80); Serial.print("TOPWAY"); Serial.write(0x00); //string end with "\0"
Serial.write(0xcc);
Serial.write(0x33);
Serial.write(0xc3);
Serial.write(0x3c); . if Not? please show me as answer not in comment.

the answer is below

I don't know anything about the particular display, but based on the information provided I hope this is at least shows the foundation of one way you could approach a final solution.
Update:

Incorporated great improvements and a fix from Edgar in the comments.
String overload.
Display baud rate suggested by mehmet

#define DISPLAY_DEVICE Serial
#define DISPLAY_DEVICE_BAUD 9600

static uint8_t displayPktStart[] = {
    0xaa, // packet headchar
    0x42, // VP_N16 string write command
    0x00, // VP_N16 address
    0x00, // ...Fill
    0x00,
    0x80
  };

static uint8_t displayPktEnd[] = {
    0x00, // End of text
    0xcc, // packet tail
    0x33, // packet tail
    0xc3, // packet tail
    0x3c // packet tail
  };

void writeDisplay(const char* text)
{
  // Write packet headers
  DISPLAY_DEVICE.write(displayPktStart, sizeof displayPktStart);

  // Send text
  DISPLAY_DEVICE.print(text);

  // Write packet tail
  DISPLAY_DEVICE.write(displayPktEnd, sizeof displayPktEnd);
}

void writeDisplay(const String& text)
{
  writeDisplay(text.c_str());
}

void setup()
{
  DISPLAY_DEVICE.begin(DISPLAY_DEVICE_BAUD);
}

void loop()
{
  String msg = "TOPWAY";
  writeDisplay(msg);

  delay(2000);
  writeDisplay("Peanuts taste like chicken");
  delay(500);
  writeDisplay("");
  delay(1000);
  writeDisplay("No. Seriously");
  delay(2000);
}

Instead of writing a loop, you can DISPLAY_DEVICE.write(displayPktStart, sizeof displayPktStart);, and likewise for displayPktEnd. 2. You mean DISPLAY_DEVICE.print(text);, not println(). 3. Serial.print() will not send the terminating \0, you may want to add that to displayPktEnd.

@EdgarBonet Thanks. Updated.

Thanks A lot. I've added DISPLAY_DEVICE.begin(9600); in setup

@mehmet I hope my update matches your expectations.

@voidPointer well, I don't want to bother you too much, but I have one more question. if I want to use dynamic address, such as "000080" instead of     Serial.write(0x00);
Serial.write(0x00);
Serial.write(0x80); how to add this method, like writeDisplay(msg, "000080");

@mehmet Remove the address from displayPktStart, add uint32_t parameter to both writeDisplay and send it after directly after DISPLAY_DEVICE.write(displayPktStart,...


text:
Replicating Tx and Rx LEDs
In my application all of the Arduino Uno LEDs will be invisible inside an enclosure, so I wish to provide panel-mounted Tx and Rx LEDS just replicating their on-board counterparts. Is there a way to drive any of the digital outputs to replicate those LEDs? I seem to recall that the Tx and Rx LEDs are driven directly from the FTDI logic, does this preclude hacking their states and sending them to two digital outputs? How could this be done? I could de-solder the LEDs and hardwire the panel LEDS to their pads, but I think this should be a last resort.

The USB to serial and LEDs are done with the ATmega16U2 (the chip near the USB socket).
If you look closely you'll see there are 4 pad near the chip, JP2 in the schematic. You could solder some wire to it to connect your leds. You could then slightly modify the firmware running on the ATMega16u2, and upload it using DFU.
I did this on my arduino uno to break out the reset signal, so I could use my UNO to program an separate ATMega328 over serial.
In your case you could use the pads connected to PB4 and PB5 (as the original code uses PD4 and PD5), so the you only have to change DDRD and PORTD, to DDRB and PORTB in LED.h.

The easiest thing to do would likely be to use an Arduino that does not have an on-board serial connection such as the Pro Mini and then add a separate USB-UART bridge with either bare pads you can solder panel-mount LEDs to or mounting holes that will allow you to mount it with the LEDs aligned to holes on the enclosure.

Personally I would wrap all serial reading and writing in my own functions which, as well as doing the reading and writing, turn on an LED on any chosen GPIO and set a timer variable which is then used in the main loop to turn the LEDs off after a short period (otherwise they flicker too fast to be properly seen).  Something like:
uint32_t readLedTimer = 0;

// Call instead of Serial.read();
int mySerialRead() {
    if (Serial.available()) {
        digitalWrite(13, HIGH);
        readLedTimer = millis();
        return Serial.read();
    }
    return -1;
}

// Call from loop();
void cancelLeds() {
    if ((readLedTimer > 0) && (millis() - readLedTimer > 20)) {
        readLedTimer = 0;
        digitalWrite(13, LOW);
    }
}

Of course, replicate (with a different LED) for the any Serial.write or Serial.print functions you may want to do (use may use overloading to pass different variable types to similar functions).
Another option is to directly modify the serial reading and writing routines within the Arduino AVR core to do the same thing, but that gets rather tricky when you update the IDE or want other people to use your code to build these widgets of yours.


text:
Led issue with arduino controled by raspberry pi/python
I'm having an issue with my project. My project is 8 leds and a potentiometer on an arduino being read and controlled by a raspberry pi running python.
when I'm using a potentiometer the signal is received by my raspberry pi with python which then tells a set of leds to either turn on or off. However my leds flash on my low threshold when they shouldn't, the leds on my higher threshold work as expected and stay on till my pot is out of that range. How can I fix this?
Here is my script!
from nanpy import Arduino
from nanpy import serial_manager
from time import sleep

serial_manager.connect('/dev/ttyUSB0')

POT = 0
LED1 = 13
LED2 = 12
LED3 = 11
LED4 = 10
LED5 = 9
LED6 = 8
LED7 = 7
LED8 = 6

Arduino.pinMode(POT, Arduino.INPUT)
Arduino.pinMode(13, Arduino.OUTPUT)
Arduino.pinMode(12, Arduino.OUTPUT)
Arduino.pinMode(11, Arduino.OUTPUT)
Arduino.pinMode(10, Arduino.OUTPUT)
Arduino.pinMode(9, Arduino.OUTPUT)
Arduino.pinMode(8, Arduino.OUTPUT)
Arduino.pinMode(7, Arduino.OUTPUT)
Arduino.pinMode(6, Arduino.OUTPUT)

print "starting"
while True:
    pot = Arduino.analogRead(POT)
#this is the section that is blinking when it should stay solid
   if pot < 450:
        Arduino.digitalWrite(LED1, Arduino.HIGH)
        Arduino.digitalWrite(LED2, Arduino.HIGH)
        Arduino.digitalWrite(LED3, Arduino.HIGH)
        Arduino.digitalWrite(LED4, Arduino.HIGH)
        Arduino.digitalWrite(LED5, Arduino.LOW)
        Arduino.digitalWrite(LED6, Arduino.LOW)
        Arduino.digitalWrite(LED7, Arduino.LOW)
        Arduino.digitalWrite(LED8, Arduino.LOW)
        sleep(.5)
# end of section
   if pot < 650 > 450:
        Arduino.digitalWrite(LED1, Arduino.LOW)
        Arduino.digitalWrite(LED2, Arduino.LOW)
        Arduino.digitalWrite(LED3, Arduino.LOW)
        Arduino.digitalWrite(LED4, Arduino.LOW)
        Arduino.digitalWrite(LED5, Arduino.LOW)
        Arduino.digitalWrite(LED6, Arduino.LOW)
        Arduino.digitalWrite(LED7, Arduino.LOW)
        Arduino.digitalWrite(LED8, Arduino.LOW)
        sleep(.1)
    if pot > 650:
        Arduino.digitalWrite(LED1, Arduino.LOW)
        Arduino.digitalWrite(LED2, Arduino.LOW)
        Arduino.digitalWrite(LED3, Arduino.LOW)
        Arduino.digitalWrite(LED4, Arduino.LOW)
        Arduino.digitalWrite(LED5, Arduino.HIGH)
        Arduino.digitalWrite(LED6, Arduino.HIGH)
        Arduino.digitalWrite(LED7, Arduino.HIGH)
        Arduino.digitalWrite(LED8, Arduino.HIGH)
        sleep(.5)
    print pot

Implement hysteresis.

Your second condition is written wrongly. It should be this way:
elif pot >= 450 and pot <= 650:
    # do stuff

Your code should be such that only an option is chosen at any time. There should be only one 'if' condition at the top and the rest should be 'elif'.

Yes, except it's python, so - if (pot < 650 and port > 450):

@Kingsley Python! Can't believe I totally missed that

The problem is you're using multiple if statements, whereas the if-blocks should be mutually exclusive, so elif would be better.  It's not really clear what you intend in the 2nd clause either, since it's a typo(?) - not valid python syntax anyway.
if (pot <= 450):
    Arduino.digitalWrite(LED1, Arduino.HIGH)
    ...
    time.sleep(0.5)
elif (pot > 450 and pot <= 650):
    Arduino.digitalWrite(LED1, Arduino.LOW)
    ...
    time.sleep(0.1)
else # pot > 650
    Arduino.digitalWrite(LED1, Arduino.LOW)
    ...
    time.sleep(0.5)

I think your LEDs were flashing because both the first and second if clauses were evaluating to True, thus both code segments were being executed (were only the first four LEDs flashing?)  Using if/elif/else instead, ensures only ever one clause is run.
If I might make a suggestion, assuming you want an LED bar graph based on the POT reading...
The analogRead() will give you a result 0-1023. Graphed over 8 LEDs, this means one more LED should be illuminated roughly per 128 units.  Since you want a full bar when rounding makes the value near 1023, maybe something like 120 is a better divisor (I just guessed this, it's probably calculable).
A simple loop over your LEDs, summing units over each iteration gives an easy way of turning the LEDs on or off.
Arduino.analogRead(POT)
led_bar_per_units = 120   # needs a better name

### illuminate the LED-bar
bar_length = 0
for led in (LED1, LED2, LED3, LED4, LED5, LED6, LED7, LED8):
    bar_length += led_per_bar_units
    if (bar_length <= pot):
        Arduino.digitalWrite(led, Arduino.HIGH)
    else:
        Arduino.digitalWrite(led, Arduino.LOW)
time.sleep(0.5)

EDIT: I know you don't need brackets around python if statements.  I've been doing C/C++ code for so long I find bracketed-clauses easier to read, and thus code my python this way too.

I figured it out.
Here is my new script.
from nanpy import Arduino
from nanpy import serial_manager
from time import sleep

serial_manager.connect('/dev/ttyUSB0')

POT = 0
LED1 = 13
LED2 = 12
LED3 = 11
LED4 = 10
LED5 = 9
LED6 = 8
LED7 = 7
LED8 = 6

Arduino.pinMode(POT, Arduino.INPUT)
Arduino.pinMode(13, Arduino.OUTPUT)
Arduino.pinMode(12, Arduino.OUTPUT)
Arduino.pinMode(11, Arduino.OUTPUT)
Arduino.pinMode(10, Arduino.OUTPUT)
Arduino.pinMode(9, Arduino.OUTPUT)
Arduino.pinMode(8, Arduino.OUTPUT)
Arduino.pinMode(7, Arduino.OUTPUT)
Arduino.pinMode(6, Arduino.OUTPUT)

print "starting"
while True:
    pot = Arduino.analogRead(POT)
    if pot < 450:
        Arduino.digitalWrite(LED1, Arduino.HIGH)
        Arduino.digitalWrite(LED2, Arduino.HIGH)
        Arduino.digitalWrite(LED3, Arduino.HIGH)
        Arduino.digitalWrite(LED4, Arduino.HIGH)
        Arduino.digitalWrite(LED5, Arduino.LOW)
        Arduino.digitalWrite(LED6, Arduino.LOW)
        Arduino.digitalWrite(LED7, Arduino.LOW)
        Arduino.digitalWrite(LED8, Arduino.LOW)
        sleep(.01)
    elif pot > 650:
        Arduino.digitalWrite(LED1, Arduino.LOW)
        Arduino.digitalWrite(LED2, Arduino.LOW)
        Arduino.digitalWrite(LED3, Arduino.LOW)
        Arduino.digitalWrite(LED4, Arduino.LOW)
        Arduino.digitalWrite(LED5, Arduino.HIGH)
        Arduino.digitalWrite(LED6, Arduino.HIGH)
        Arduino.digitalWrite(LED7, Arduino.HIGH)
        Arduino.digitalWrite(LED8, Arduino.HIGH)
        sleep(.01)
    else:
        Arduino.digitalWrite(LED1, Arduino.LOW)
        Arduino.digitalWrite(LED2, Arduino.LOW)
        Arduino.digitalWrite(LED3, Arduino.LOW)
        Arduino.digitalWrite(LED4, Arduino.LOW)
        Arduino.digitalWrite(LED5, Arduino.LOW)
        Arduino.digitalWrite(LED6, Arduino.LOW)
        Arduino.digitalWrite(LED7, Arduino.LOW)
        Arduino.digitalWrite(LED8, Arduino.LOW)
        sleep(.01)
    print pot