text:
How to input keyboard commands using Arduino Mega 2560?
I have an Arduino Mega 2560 connected to a Windows 8 laptop. I want to program it to send keystrokes to the attached computer (when a pin's digital read goes from HIGH to LOW.)
The trouble is, I cannot find any way to program my Arduino Mega to send keystrokes.
The supposedly "core" Keyboard and Mouse libraries only support 32u4 boards, and other libraries that give the Arduino keystroke functionality are out of sight. When I googled the issue, I found no question or explanation of how to send keystrokes on the Arduino Mega. When I searched further, I thought the V-USB library would be a potential workaround, but the library throws numerous errors when imported into an Arduino sketch (even on the 1.0.0 IDE it was designed for.)
After hours of searching, two final workarounds seem to have popped up:

Some method to run a Python code to send keystrokes to the PC, and then connect the Arduino code to Python. (I don't know Python...)
Use some program called Gobetwino, which runs between the Arduino and PC, to   convert Serial commands into keystrokes somehow. (Pressing and releasing a key can't be simulated very well by repeatedly sending Serial commands, I think.)

Both are very unideal, very tedious, and are equally likely to just not work. I have spent hours on this.
Does anyone have any suggestions to get me out of this hell? Libraries, workarounds, anything?
(Feel free to PM me questions for clarification.)

Both the Mega 2560 and the Uno R3 have the same second MCU, so I'm marking this one as a duplicate.

The V-USB library is the only practical way. You need a couple of resistors and zener diodes. I suggest you post the exact V-USB library you are attempting to use, and the exact error messages.

However reflashing the USB interface chip is not really an ideal solution.

Scrap the Mega2560 and use a Leonardo.

Why do you want to send keystrokes? What do you want to achieve? Wouldn't it be easier to just signal the pin change via different means?

You are right, the mega can't do what you want unless something in the middle catches the serial/IO and translates to a keystroke command.
Another option, more expensive, is to buy an Arduino Leonardo which is also available as a small usb stick type of device. Then use serial/analog or ano from the mega to the Leonardo.
The Leonardo boards can emulate any usb device such as keyboard, mouse, joystick etc.
Maybe not of interested but also look at Teensy 3.1. It can do what the Leonardo does but is 32 bit and very flexible. The only benefit of the mega is the massive number of pins. Teensy costs about $20.
It all depends on what your project requires.

Untrue.  The Mega2560 hardware is capable of both USB HID (see comments) and PS/2 keyboard interfaces.

Not sure if that is true. It is the ATmega8U2 usb on the same board as the mega that could do this but requires some difficult non-arduino re-programming? The Leonardo is programmed via the sketch as normal so it's a simple solution designed for this purpose. Please correct me if I am wrong about this?


text:
Set Bluno Beetle to Broadcast mode
I recently purchased Bluno Beetle (basically a smaller Arduino with a BLE chip). It is based on the Bluno: Wiki I know that its Bluetooth Chip, the TI CC2540, supports the Broadcast mode: Official page
However I can't find any AT commands that would allow me to set it to this mode, does anyone of you have an idea? I am trying to relay the messages they are sending (sensor readings), essentially building an interconnected network.

It looks like the Bluno only supports the Central and Peripheral roles (i.e. not the Broadcaster and Observer roles.) Keep in mind AT commands are a feature of the firmware, not the actual chip. As such, even if the chip supports a particular mode or role, that doesn't necessarily mean the firmware makes the feature available.

That's what I was afraid of :-/ Thanks for your answer though!

source: Stack Exchange

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

sort: votes


text:
How do I make/get a odometer for a lunch box sized robot?
Say I have given the robot a map of the place, it needs to navigate it. I need a odometer to keep track of its current position in the map. I need it to be precise up to a cm.
Can I simply use the motor's RPM and the diameter of the wheel to calculate how much distance the robot has travelled, or is there any catch?
I searched Google and could not find any odometer small enough for my robot. Most of them are for bicycles.

Seems to work pretty well here: https://youtu.be/tZ3fpZFWHDM?t=453 (7:33)

I had the idea to use a computer mouse (optical) to do this - cheap, easily available. You would need two, if you want to be able to measure turning rate, one on the left and one on the right.
You don't even need the whole mouse - if you pull it apart you can ditch the case, the buttons, and about half the circuitry. You will need to do some hacking to figure out how it works, but I doubt you'll find a cheaper odometer that is anywhere near as accurate.
Note: I pulled one apart, then got distracted on another project, but I can't think of a reason why it wouldn't work.

This is brilliant! If I had 15 reputation I would have given a thumbs up.

Good idea. Saves using a wheel at all. :)

Would this be tracking the ground the same way your mouse tracks the desk in order to move the cursor?

Yes, tracking the ground. I don't know how it would work on uneven surfaces - the lens of a mouse is a little way off the desk, there doesn't seem to be more than 1mm leeway in that.

The circuitry for controlling this might be difficult. I've used photointerrupters with tabs on an axle to track RPM, but that doesn't account for slippage it's true. Dead reckoning is always tricky!

I think the catch is that the wheel will slip, particularly when starting up. The slightest slip and you are counting a rotation that didn't move the robot forwards. Also if it skids when stopping that is more movement that you didn't detect.
You are probably best off with a non-powered wheel (stuck out the side perhaps?) which has the task of only detecting movement. Perhaps put a rubber tire on it to get a good grip. You could connect a rotary encoder to the axle which could count the amount it has turned. There are rotary encoders which do not have friction (eg. optical or magnetic).
If the robot has some non-powered wheels (like a rear wheel) then that could be a good place to measure turns, as it wouldn't slip as much because it isn't under power. You might be able to detect the amount it has turned, for example if it had suitable holes that you could shine a light-detector through.
Alternatively if the area is small enough use a distance sensor (like a sonar) but that probably wouldn't be accurate enough.

I am thinking of using a sonar to calibrate the odometer every half a minute or so. The robot will use a pair of landmarks to determine its position then reset the odometer.

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


text:
Popen command restarts arduino
So I am trying to make a Mac OSX program with Cocoa that will be able to control my Arduino via serial. I currently have the C command
popen("echo 7 > /dev/cu.usbmodem1411", "r");

to try to send the number 7 over serial to the Arduino. I know that the path     /dev/cu.usbmodem1411 is correct because the Arduino is responding, however it seems to "crash" or simply restart whenever this command is received from the Mac. Sorry this may be a question for StackOverflow, but I thought I would start here.

Nope, doesnt seem to do the trick

Are you sure you are sending "the number 7"? I don't know how echo on the Mac works, but are you sending a string with the character '7' in or ASCII 7 or integer 7.  And how are you reading it at the other end?

@Matt I'm actually not sure, is there a better way to do this? I was attempting to send an integer 7

@woakley5 I would guess that you are sending ASCII character 7.  Can you use SoftSerial on the Arduino, and change you program to echo the data received from the Mac.  Echo the byte values received, not the characters, because if you print 7 it ring the bell :)

Despite the poster's denial, this is in fact a duplicate of the reset-on-open issue, and especially now that they seem to have abandoned the question, closing it as a duplicate (as it originally should have been) is the only way we are going to stop it from being periodically churned back up.

@Matt Echo on mac won't send ascii char code like that...

I think the problem is more going to be that you don't have a serial connection to the arduino. ie, if you look in the Arduino IDE, you assign a serial port to the application. When you upload your sketch, a connection is made, the arduino resets (by design) and your sketch is uploaded.
What it appears you are doing here is opening a new connection and sending the character (which is ASCII) which in turn sends the arduino into reboot to look out for a sketch being uploaded.
I'm not familiar with popen and maybe you can use it and keep the connection open and even monitor the data stream, but I would say instead of writing directly to the device as you've done, use an application that will initialise the port properly (ie open it and leave it open) so that you can continue to use/monitor it.
A quick google search has brought up Mike's PBX Cookbook which has some good info about it. I've personally used minicom (a guide for installing minicom) and CoolTerm, I have used Screen but it was so long ago I don't remember why I moved on.
edit: I just followed the link submitted by the first commenter (sorry name not available in the edit screen), and although you've responded with "that's not it", it actually is, you just haven't realised it since your popen command is actually opening the port and triggering the RTS mentioned in that post

Automatic activation of the modem control signals (which trigger the reset) is something which the host operating system can be configured to do or not do.


text:
Help understanding how to drive Step motors with Arduino
I am building a 2-Axis gantry system to dispense some thermal paste on boards. I was given two stepper motors in order to do so along with a gantry already built that will arrive in two weeks. So basically I just need to figure out how to drive them on the software side. However the boss demands testable code to be finished by EOB tomorrow, despite the hardware not being here yet. So I drafted some quick code that should drive a stepper motor, it's an easy open loop system, but I'm struggling. The operator will home the gantry after each cycle so it's just a matter of getting the motors moving.
My method was as follows:
#include <Stepper.h>
*declaring the stepper and all that goes here*
void loop(){ etc.
   basic logic flow stuff
   stepper.step(20); // to move forward twenty steps
   stepper.step(-20) // to move back twenty steps

However my boss says this is incorrect as I need to be giving the steppers both step and direction.
After some tenuous google searching he recommended I use the AccelStepper library to fix this problem. After looking through this library I'm unsure how this will give me anything I need (distances are so small acceleration is useless) and how I am not giving it both step and direction in my original example code, I give it steps (20) and a direction with my negative/positive coefficient.
Am I correct in my thinking? Is there a better solution neither of us have found? I'd love to understand not just that I'm wrong, but why I am.

Does your boss not realize that the polarity of the number is the direction?

@IgnacioVazquez-Abrams thats what I responded with. He just seemed confused and said something  about direct driving. I am not one to question him, he's been in the CNC business longer then I've been alive. I'll suggest this during our standup tomorrow morning.

You should read this: http://www.cncroutersource.com/cnc-control.html
"First lets review how the computer or the stand alone user interface communicates to the controller. Most systems today operate on a step and direction format of command signals. Some higher end machines use a proprietary analog or digital signal, but it is usually a variation of the step and direction format."
Probably your boss wanted to tell you that the protocol from the PC to Arduino (or standard CNC protocol) differs from the way the stepper library works

Also, I'm guessing stepper motors have a rather tricky way of working, they use combinations of pins for rotating, in which forward differs from backward. Your boss might be talking about this, while you're using the arduino library which covers up all the direct hardware interfacing.
You should tell him, or even better, show him with an image that you're using the arduino as a controller, which has software instructions that will drive the stepper.

Sorry for all the commotion on your thread.
It comes down to this: Your boss (probably) wants you to implement the driving off the stepper motors yourself, withouth using the arduino library. You should check some tutorials on stepper motors. And ask him if he wants you to drive the coil pairs 'manually' rather than using a library. He's most likely to say yes (as this is how the pro's do it? :D or how you should learn it.).

Show him the source code of the Stepper library. The first three statements of Stepper::step(int) convert the signed number of steps to a positive number of steps (steps_left = abs(steps_to_move)) and a direction flag (this->direction).

I think there is some mis-communication between you and your boss. I do not think your boss is stupid, but I do think he's talking on a different level as you do. You're using arduino which covers up a lot of hardware-interfacing, especially with steppers.
I suggest you check out this video: https://www.youtube.com/watch?v=bngx2dKl5jU
(I haven't watched it, but It will help you get more into the ideas of your boss)
Now you understand your boss's view, you can try to show him your view. When talking about steppers/arduino and how you can put in negative steps, he might think you're talking trash, as steppers require different pairs of coils to be active depending on the direction. (which is all handled by arduino)
The best way is to provide him a visual guidance, so that he can see the relation with his (hardware-view) on the issue and your software/arduino solution.
You could make something like the image below.
I'm not sure if this is what you're trying to tell him.
I guess you should mention/add that the software on the arduino takes integer values, with negative values being clockwise or such. And that the arduino will convert this to the right coil pairs or direction and step.
P.S:with direct driving, I think he meant toggling the right pins at the right moments so that the stepper will rotate, basically what the stepper library does for you. Maybe he wants you to implement something like the stepper library (is it an internship? so that you can learn?) I suggest you check some tutorials on how stepper motors work, and how you can drive them 'directly' withouth the use of libraries.


text:
Gauss solver for IIR filter
I write a piece of code in online GDB using c++, the code calculates some coefficients for a IIR filter which tries to approximate a fractional derivative and integral for a fractional PID control. The code works as expected in the online IDE, but when I try to execute it in a Arduino Due, the results and only overflows and nan, and really don't know what's the problem so,
Here is the code in GDB online https://onlinegdb.com/rycwt62XL which gives the expected results:
Array A, Array B
1.41421,1
-0.707107,0.5
-2.12132,-1.5
0.883883,-0.625
0.883883,0.625
-0.265165,0.1875
-0.0883883,-0.0625
0.0110485,-0.0078125
And here is the code for the Arduino Due, which only change the printing method using the serial commands, https://onlinegdb.com/ByAs5xyVU, and the results are:
Array A, Array B
ovf,1.00
ovf,ovf
ovf,0.00
inf,ovf
ovf,0.00
inf,ovf
ovf,3.89
inf,ovf
And really don't know where to start for fix this results, thanks. The Method is  exactly the same.

Works fine on every piece of hardware I have tested, except the Due. I've never liked the Due - the compilation has always been really really shaky...

Majenko, I tested on the arduino Mega and works really well, but I've donde all the programming in the Due, but thanks

I can't find the root cause of the problem - it's probably because the Due is possibly the worst board that Arduino ever made, and the compiler / linker / support libraries barely work at the best of times.
However, some things you need to look at in your code:
    double* h = new double[L];
    for(int n = 0; n <= L; n++){
        for(int k = 0; k <= n; k++){
            h[n] += pow(operador,-alpha-n+k)*pow(1.0-operador,n-k)*Binomial_E(alpha,k)*Binomial(-alpha,n-k);
        }
    }

There you allocate L (15) doubles in an array. But then you go on to access array slices 0-15. That's 16 entries in an array of size 15, so you're overflowing it and corrupting other memory.
Also you have no delete to balance the new, so you have a memory leak.  You would be better using:
double h[L+1];

instead of new.

You are right, I avoid using arrays with variable size and works, thanks so much

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


text:
Connect push button to ArduiMU
I've got an ArduiMU V3+ and would like to connect an ordinary push button to it.
How would I connect it to it.

Presumably connect it between ground and an unused input, then activate a pullup resistor on the input.  This really depends on the software you are running, and on any unique requirements of your application (such as acceptability of various types of failure).

May I use analog-inputs as well?

This site realy exists as a fallback for things which are not covered in or not clear in the documentation, not as an alterantive to it.  Please start with http://www.arduino.cc/en/Tutorial/AnalogInputPins


text:
WLAN module compatible with ArduiMU V3+
Current I use my ArduiMU V3+ with a Bluetooth Mate (from Sparkfun) but I've got a lot of connection problems with it.
I'm looking for a better solution involving WLAN and am wondering whether there are compatible modules?


text:
What does a higher clock signal frequency actually mean for my AHRS?
I've got an Arduino with an ATmega328 processor. It can be operated at 3.3V which nets a clock signal frequency of about 12 MHz respectively 16 Mhz at 5V.
I've got an IMU connected to the Arduino and a AHRS algorithm turning accelerometer, gyroscope and magnetometer data into orientation data.
What does the higher frequency of 16 MHz actually mean in this context?
Will the AHRS be calculated faster so I get a lower latency? Can I poll the sensors more often? I want a deeper understanding of what I'm doing here.

What does the higher frequency of 16 MHz actually mean in this context?

The Arduino will run a bit faster (33% faster). Therefore it could calculate things faster. Whether you can poll the sensors more often might depend on the sensor. Limiting factors could be how fast you can communicate with the sensor, how often the sensor takes readings, what you are going to do with the readings, and whether it matters if calculations are a bit slower.
For a better response I suggest you post a link to the particular sensor, the AHRS algorithm you are using, and describe the application you are using it for.

Thanks Nick, this was just about making sure that I "get it". I'm already satisfied with how my AHRS performs. I'm interested in improving the latency of my system but there are worse bottlenecks like the serial communication via Bluetooth, how fast my node.js middleware processes it, how fast that communicates with the actual application I'm using it in.


text:
What does “LSB per degree per second” mean?
I'm currently working with a digital output gyroscope. Its sensitivity is given as 120 least-significant bit per degree per second.
While every single component of that unit is easy to understand I don't quite get what it means altogether.
Can you explain it to me?

Which digital output gyroscope?

There is a similar post in this forum with an answer which I find much easier to understand.

Let us say we have a number, "4025". The "most significant digit" of the number is the 4 in the thousands position, since it tells us the most about the magnitude of the number ("in the four thousands"). Consequently, the "least significant digit" is the 5 in the units position, since it tells us almost nothing about the magnitude of the number. "Most/least significant bit" is the same, except it applies to binary numbers (which the MCU cares about, of course; we can still use any radix we like to talk about them). So the device's output count can change by up to 120 per degree per second.

Isn't the LSB in a binary number always either incrementing the number or not? I mean  the value of the LSB has to be always 1 or 0. I understand what the LSB is but not its roll in the unit.

@Hedge: 125 is 2 LSBs greater than 123.

I don't really understand the question, nor the answer. What does "120 least-significant bit per degree per second" mean? Let's say the gyroscope returns some units. Without knowing the model they could be anything, but let's say it's 100th of a degree. Isn't that just saying it is accurate to 120 units per degree per second? I mean, a least-significant bit is 1, right? So that is 120 x 1 (of whatever units) per degree per second?

@NickGammon: The gyro returns a count. 1 LSB is 1 count.

Didn't I say that? Why doesn't it just say "120 counts per degree per second"? I mean, that's like saying LSB of 1 + LSB of 1 = 2.

@NickGammon: Because long, long ago someone decided to call it that.

OK I will give you +1 LSB of rep for that. :)

Here's a real example for the MPU6050, when set at 250 degrees/sec range. The code says that is 131 LSB/deg/sec. The code returns a signed 16 bit int, from -32768 to 32767. The 250 degree range divides into the 32767. 32767 / 250 = 131. So if the part comes back with 262, take that and divide by 131, and you get 2 deg/sec rotation. 32767 is 250 deg/sec rotation, etc. Back to the original question and the part Hedge is using, and @NickGammon is right, it really translates to "120 counts per degree per second".

With further elaboration on Ignacia's answer:
A gyroscope itself is generally an analog device in the sense that in reality, it will have a continous output. This output is digitized using some form of Analog to Digital A/D converter where the analog output is converted to a digital number. The output from the gyroscope is a measurement of angular speed, generally millidegrees/sec.
The number read by your Arduino from the gyroscope will be a digital version of your current angular speed at the time of measurement. For example, if you're getting an 8bit number back equal to 121, this in binary is equivalent to 01111001, where the '1' furthest to the right is the least significant bit.
The term "lsb per degree per second" means how many bits change with your angular speed. For example, with a gain of 1 (meaning 1 degree/second = 1 bit), an angular speed of 90 degrees/sec will produce a read value of 90 or 01011010. Therefore, 1 bit changes per degree/second. Increasing the essential "gain" (which will most likely be referred to as "dps" will change how many lsb's change per degree/second.

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


text:
Industry Standard for Single-Board Computers?
Do Arduinos, or any other single-board computer, come in any sort of industry-standard form factor? I'm trying to sell management on using Arduino, but they are stuck on the question "what if Arduino goes out of business", and if I could answer "we can just switch over to using brand X because it's the same size and has the same connectors", my life would be much easier.

Arduinos are not single board computers.

@IgnacioVazquez-Abrams - untrue, an Arduino is very much an SBC

I'm going to agree with @IgnacioVazquez-Abrams -- the Arduino is just a microcontroller with a few extra peripherals attached around it to make it easier to develop with. Single board computer is generally a term for a board that has a Microprocessor (i.e. not microcontroller), some RAM, and optionally storage and maybe a GPU built in to the CPU. SBC would more like a Raspberry Pi or BeagleBone Black.

There are standards if you're willing to look beyond Arduino, such as PC/104, but for Arduino (hardware) you're pretty much stuck with whoever is making boards for them. You may want to consider standardizing your own I/O and Arduino libraries, and seeing how they work with the various Arduino-compatible MCUs.

@JakeC - no.  An Arduino has all of the same types of resources as most other SBCs - granted it is less powerful, but not less powerful than some of the first systems to define that term.  That a microcontrontroller puts peripherals such as volatile and non-volatile storage that might have once had to be a on the board on the chip itself doesn't mean that those functions aren't still present on the resulting board.

I guess that the Industruino is the closest you can get to an Arduino in an Industry Standard format; https://industruino.com/. The Arduino core and libraries is the real "standard". This is where the true value is.

Whether or not the Arduino company goes out of business isn't all that relevant. For one thing, there are now two competing companies vying for the Arduino trademark - arduino.cc and arduino.org.
The Arduino has such a ground-swell of popularity that clone boards are widely available on eBay and from other suppliers. While people are willing to buy them, someone will sell them.
The design is open-source, which makes it a safer choice than other designs who keep their design proprietary. For one thing, it guarantees that someone will make compatible boards, even if Arduino(s) fold.
The "heart" of the Arduino is (in most cases anyway) a chip from Atmel - so you really should ask if Atmel will go out of business. Probably not, but in any case, an alternative supplier might just as easily go out of business.
I wouldn't be building an "Arduino board" into a production system anyway - too much chance that wires would fall out of the prototyping sockets. However the prototyping board is good for learning about their capabilities, and testing your code.

Do Arduinos, or any other single-board computer, come in any sort of industry-standard form factor?

I'm not aware of any industry-standard form factor. The Uno design has caused a lot of people to make "shields" that fit onto that form factor, so that is probably the closest you would get to an industry standard.

If you need a real computer, there are nowadays various options based on the Intel NUC concept.
The Gigabyte variant, for example. It also has GPIOS accessible through a normal pinheader, in case you need them.
And, being x86, there is virtualyl no risk of loosing the supplier.

Modern x86 processors are not always perfectly deterministic even if you write to the bare metal, which is a trait desired in many embedded systems.

And where does that requirement come from, exactly?
For sure, not from the question asked.
Btw, the x86 processor is deterministic.
If you think you can write to the bare metal of an x86 machine you are fooling yourself, there is anyway a layer of microcode.
The amount of other SW running on top of it it might not be accurate, but that's a separate story. And, anyway, it was not a requirement.

No one was claiming that it was a requirement for this specific asker, nonetheless it is still worth considering before choosing a solution.


text:
How do I upload sketch (and parameters) through a user interface
I'm pretty new to Arduino and I'm developing my first real-world project.
I have a Arduino Mega with a full working sketch in it which is going to be placed in several distant places and I have a number of "mantainers" that will need to get to the place, connect the board with their Windows (Vista+) laptop (USB), upload a new version of the sketch (if available), download some data from EEPROM and change (if needed) some parameters stored in PROGMEM. This just to give you the full picture, now I come to the questions.
What I'm trying to attempt is to write (in c++) a software that gives non-programmers a UI to do this stuff easily, so I wonder:

How do I load the .hex file to the board? I kinda got I have to use AVRdude: is there any c++ example/tutorial/library I can use not to reinvent the wheel?
When can I write to PROGMEM? When I connect with the serial cable Arduino stops the running sketch, waits for a new sketch and, if it does not arrive, it starts the old sketch back again. I guess that is the time to write to PROGMEM: if there is a running sketch I cannot do it, am I right?

The data in PROGMEM is actually part of your program: it is embedded in the .hex file you upload to the board. If you want to change persistent data without re-uploading the whole program, use the EEPROM instead of PROGMEM.

@Edgar That's bad news, but thank you for pointing it out! This simplifies the process (update the sketch - talk to the sketch through serial - the sketch writes on EEPROM) but EEPROM is little enough as it is... Does it make sense to you to write my parameters in a text file and then compile the sketch on-the-fly (with this data in) through my UI using the CLI of Arduino IDE (which I would include in my software)? Choose one: A - it makes sense; B - no it does not; C - ask a new question for this

I would go for the EEPROM if at all possible. If not, write the parameters to a binary file and link the sketch with that file (c.f. my updated answer). No need to recompile. Not sure the CLI of the Arduino IDE can do that, but avr-ld can.

How do I load the .hex file to the board? I kinda got I have to use AVRdude: is there any c++ example/tutorial/library I can use not to reinvent the wheel?

Yes, you have to use avrdude.  The simplest way is just to bundle avrdude.exe and the avrdude.conf file with your program and call it, along with its required parameters, with system() or some similar (eg execv()) method (or whatever Windows has decided to provide instead of those standard functions - who knows what goes through the minds of Windows developers...).

When can I write to PROGMEM? When I connect with the serial cable Arduino stops the running sketch, waits for a new sketch and, if it does not arrive, it starts the old sketch back again. I guess that is the time to write to PROGMEM: if there is a running sketch I cannot do it, am I right?

When you upload a new sketch you are writing to PROGMEM.  That's really the only time you can do it.  Yes, there are ways you can write pages of data to PROGMEM, and that's exactly what the bootloader does when you upload a sketch, but manipulating individual variables in PROGMEM is not possible without major brain surgery being done in your sketch.  To store these kind of tweakable parameters you would normally use the EEPROM.
It can also be good to use external storage for some of these things to - either an SD card (overkill) or an external SPI or I2C EEPROM or Flash chip.  This keeps all the data completely separate from your sketch so you can never overwrite that data when you upload a new sketch.
It is, of course, up to your sketch to provide some kind of interface to tweak the settings, whether stored in internal EEPROM or an external EEPROM chip.  Creating some kind of serial protocol which your C++ program can interface with will be essential.  Only while your sketch is running will you be able to change those variables.  If you don't want to allow end users access to that interface then one method could be to have a separate sketch which is a "calibration and configuration" sketch which your program uploads in order to adjust the settings.  Once you have finished it then re-uploads the original (or new) sketch to allow normal operation again.

When I'm on air I'm quite comfortable, I already have a serial protocol to communicate with the sketch. It was the upload part I had no clue about! Answer accepted, thanks a lot!

Does it make sense to you to write my parameters in a text file and then compile the sketch on-the-fly (with this data in) through my UI using the CLI of Arduino IDE (which I would include in my softwareas well)? Choose one: A - it makes sense; B - no it does not; C - ask a new question for this

I choose D: it depends on what the data parameters are and how big they are and if it's worth the extra effort.  If you choose to do it that way you will need to include the compiler with your program which will make it much bigger and more complex to install.

1) Why not just
system("avrdude ...");

That's more or less what the Arduino IDE does.
2) If you really want to embed the data in the executable, see
Embedding Blobs in
Binaries.
You would need to re-link and re-upload the program each time you change
that data. You won't need the Arduino IDE, as it's only job is basically
to call avr-g++ and avrdude. You can use the IDE if you find it's CLI
easier than those of the standard tools.
If you put the data in EPPROM instead, the avrdude can upload it without
re-uploading the program.

So I would have to include the avrdude executable into my software installation?

Definitely. It's part of the Arduino installation BTW.

The avrdude/upload part has been fairly well covered by the other answers, but what has not been mentioned yet is that it is fairy trivial to modify program memory contents by modifying the hex file to be uploaded.
Basically, you just write hex-encoded bytes in the correct place in the file, and then update the checksum at the end of each line you modify.  It can help if you put a readily recognizable placeholder sequence in the desired location in your source code, which you can look for in the hex file as an extra verification you are making your substitutions in the correct place.  This is fairly straightforward string processing and unsigned byte math which you can accomplish in the language of your choice.  There are also tools which can convert between hex files and binary images, and probably tools or libraries which can fix the checksums for you.
Do pay attention to the license terms of avrdude and any other non-original code or tools you distribute.

I'll keep this possibility very much into consideration, thanks


text:
How to test Arduino board?
A little history: I have two Arduino Uno and I couldn't program them by IDE, I got these errors:
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00

So I googled it for a while and I suspect of missing bootloader on atmega micro on the board, as I don't have AVR programmer I programmed both Arduinos with Raspberry Pi and Arduino IDE tool through ICSP pins.
It (burning bootloader) runs perfectly on both Arduino. One of them got fixed and got back to normal, but the other one gave me same error, so I changed their Atmega micro, but same result. Second Arduino (bad one) can't transfer program to AVR even with other one (good one) AVR so both AVRs on the boards are good.
The program (blink LED) run even on the bad Arduino and pin 13 blink.
My questions are:
How could I test the suspected Arduino board? Is the second Atmel micro near usb female port need bootloader too?

Update 1: I follow this tutorial but my Arduino couldn't go to DFU
  mod by shorting the pins. When I connect those pins led pin 13 not blink and lsusb command show Arduino not Atmel.
Update 2 : I went through this question and this
  troubleshoot to upload bootloader to Atmel USB device but my
  second Arduino (bad one) didn't respond and gave me this error :

Atmega chip detector.
Written by Nick Gammon.
Version 1.17
Compiled on Jul 13 2015 at 11:14:35 with Arduino IDE 105.
Attempting to enter ICSP programming mode......................................................
Failed to enter programming mode. Double-check wiring!
Programming mode off.

Is it possible my Atmega16U2 chip is burned?
Update 3 : I do reach the point that I am pretty sure Atmega16U2 is
  dead and it isn't responding to its ICSP pins and it blocks any USB to AVR connection. I check the wiring and I
  test it on good Arduino and its sequence are correct and it works on good one. Now what can I
  do, as Atmega16U2 is not rechangeable, should I throw bad Arduino away?

See http://arduino.stackexchange.com/questions/13292/have-i-bricked-my-arduino-uno and see if that helps.

Do you have anything connected to the serial? (Pins 0 and 1)

@TheDoctor No sir, all pins are free.

This answer is for your 3dr Update - should you throw it away?
I'd say no, if you are comfortable with using the Raspberry PI as programmer, as you already did.
You will not be able to use the USB-based programming, nor you will be able to emulate USB peripherals, but that's it.
Everything else will (or should) work normally, so why would you throw it away? :-)
I also suggest you grab the stronger magnifying lens you can find and have a look at the soldering of all the components. Especially those connected to the Atmega16U and the chip itself. Maybe it's not broken, but there is some short caused by conductive debris or by some excess of soldering material. If that's the case, it might be easy to remove it.

The problem is i can only upload bootloader with rasberry pi but i can't upload sketch into it. I don't know why ?

I don't know either (although it might have to do with the bootloader interfering with further uploads), but I see 2 options, at roughly the same price: either throw away the arduino and buy a new one (3-4 euros on ebay) or buy an USBASP (about 4-5 euros on ebay). The USBASP should be able to program the main AVR, as long as it is alive. And it might be useful if you do - on another board - something which requires reprogramming the Atmega16U, so you can simplify the upload process.

Btw, the USBASP would also enable you to save a bit on future purchases of arduinos: with the USBASP you can program also the mini-pro flavor of arduino, which is basically the same micro on a much smaller PCB, without USB connector. Price < 2 euros.

does the built-in arduino LED light up?? If yes try connecting your arduino in another uno usb port or try pressing the reset button on your arduino uno.

The power LED light and i test it with other cable and i even used reset button trick, non of them works.


text:
Building a digital camera?
Does anyone know of a way to DIY a digital camera by buying a sensor and lens and processing the image using an Arduino?

I assume you know that you can purchase a sensor that captures images and libraries exist to process that signal into an image file (such as a .jpg file)? There are tons of tutorials online for this... but maybe you are wanting something specific? Please clarify if so

can you be more specific please? what do you want to build, why don't you use a sensor, as Ben said?

You can buy a camera module for the Arduino, and you can interface it fairly simply.  There are numerous modules around - ask Google, it knows more than me.
But I have yet to work out why people do it.  All you can do with an Uno is to pass the data through to something else like a PC to process the image - so why wouldn't you just use a simple webcam?
The Arduino UNO has 2KB of RAM.  A 24-bit 640x480 image (VGA) requires (640*480*3)/1024 = 900KB to store it in memory.  If you really wanted to process an image on an Uno then you would be limited to (say 8-bit grayscale) 48x32 pixels (1.5KB) which is pretty pointless really.
Even a Due would only allow (again grayscale) around 320x240 (which is better) but nothing colour unless you want to start messing with CLUTs which aren't fun when receiving a truecolour (24-bit) image from a camera.
For this kind of task you are better off with an embedded computer with plenty of RAM such as a Raspberry Pi or maybe a Galileo or something.


text:
Options for turning on/off an output at a specific time?
I am building a night light that will turn on when it detects motion using a Passive Infrared (PIR) sensor. I only want the light to turn on overnight, between specific hours that I specify. Outside of this time the Arduino will sleep.
For my Arduino to check the time, there are a couple of options:
1. Real-time clock
Description: A small add-on board powered by a cell battery (lifetime usually a couple of years). The user sets the time manually after the battery is inserted. Communicates with the microcontroller via SPI, I2C, etc. Upon request from the microcontroller (using a supplied real-time clock library function), the real-time clock sends back the current time (in a specified format).
Advantages

Completely offline

Disadvantages

The clock time can drift (due to electronic component manufacturing tolerances, temperature cycles and oscillator ageing).

To account for daylight saving, a "daylight saving" switch could be used that is manually set by the user.
2. WiFi link to an Internet time server
Description: A WiFi add-on board that allows access to the Internet. A time server could be requested for a specific time.
Advantages

Daylight saving is taken into account automatically
Clock would not need resyncing periodically

Disadvantages

Dependent on connection to the Internet
Dependent on availability of time server

Questions

Before I invest hours of time into making something work, are there any other options?
How much could a real-time clock be expected to drift after a year? (I'd be happy with +/- 15 minutes).
Are there any pitfalls with trying to obtain the time from an Internet time server?

I guess a third option is a combination: an Internet time-syncing Real-Time Clock that conducts synchronisation every week or so!
Note: I am planning on using my Arduino Pro Mini, but I wouldn't be against investing in other hardware.

A DS3231 RTC is quite accurate. Check this page for its test result on time drift. http://www.switchdoc.com/2014/12/benchmarks-realtime-clocks-ds3231-pcf8563-mcp79400-ds1307/

Other options: GPS receiver (should get rough time even with only 1 satellite in view), radio time signal (DCF77, WWVB, etc., depending on your location) or maybe even forget completely about time and use an LDR to know when it's dark enough for the light to be useful. BTW, the DS3231 is good to ±2 ppm, i.e. 63.1 seconds per year.

authors: Евгений Онегин


text:
2,5m cable too long for LCD connected to Arduino UNO?
So i got that 2,5m cable wired with the LCD and the arduino, but i keep getting those weird characters showing up on the LCD. Clearly there is a signal loss between the components but there has to be a solution to the problem. Perhaps by connecting capacitors/resistors to the wires will help? Is there any solution other than not using this long cable?

Try shielding the cable. Wrap it in tin-foil or something.

2.5m of what cable? What interface are you using for the LCD?

I'm presuming this is I2C or SPI, because a Serial cable of 2.5 m should still work.
You can slow both I2C and SPI down.

In the case of SPI you can call something like this:
SPI.setClockDivider(divider);

Where "divider" is one of:

SPI_CLOCK_DIV2
SPI_CLOCK_DIV4
SPI_CLOCK_DIV8
SPI_CLOCK_DIV16
SPI_CLOCK_DIV32
SPI_CLOCK_DIV64
SPI_CLOCK_DIV128

The default is SPI_CLOCK_DIV4, so try a larger divider.

In the case of I2C you can change the clock speed and the prescaler. The default frequency is 100 kHz, but you could make it slower.
TWBR   prescaler   Frequency

  12       1       400   kHz  (the maximum supported frequency)
  32       1       200   kHz
  72       1       100   kHz  (the default)
 152       1        50   kHz
  78       4        25   kHz
 158       4        12.5 kHz

For example, to run at half the frequency (50 kHz) use:
  Wire.begin ();
  TWBR = 152;

To run at 25 kHz you also need to change the prescaler, eg.
  Wire.begin ();
  TWBR = 78;
  TWSR |= bit (TWPS0);

In the case of I2C make sure you have pull-up resistors on SDA and SCL in order to get a clean signal. 4.7 k is a reasonable value to try (for both of them) with the other ends connected to +5 V.

Sorry. I probably should have mentioned hat my LCD is connected to an arduino expander - a mcp23017 to be specific - which is connected to the arduino. Therefore I guess that I use I2c?

Yes, the MCP23017 is I2C. The MCP23S17 is SPI. You should have four wires in that case: +5V, Gnd, SDA, SCL. Make sure you have the 4.7 k pull-up resistors on SDA and SCL (at the Arduino end). Also try dropping the I2C frequency as shown above.

If the interface you're using is I2C(only two cables from arduino to lcd, vice versa)you have a problem,you need to pull up the sda-scl channel with appropriate resistors, you could (maybe) boost the I2C signal using ti-p82b715 bus extender, I just assume you use I2C (2,5m length?), what interface do you use? SPI? I2C?


text:
Sharing data between M4 and M7 on a Giga R1 at high speeds
I'm working on a project to implement an attitude controller for a quadcopter. Loop times are extremely important as you can imagine.
I already have tested code for a cascading controller (inner loop does angular rate, outer does attitude) for a single-axis on a see-saw-like physical setup.
My worry was that implementing for 3-axis would slow loop times to lead to system instability. Thus, I purchased a Giga R1 which features two cores to share the load.
One way I could implement the code is to collect all sensor/RC signals on the co-processor, while the main processor does all the PID computation and generates PWM signals for the motors.
This obviously means sharing data between the two cores. I tried using the RPC method the Arduino guide suggests to share data. However, I timed how long a remote call to return an integer takes and I'm getting around 20 milliseconds. This is far too slow.
Is there a faster way to share data between the cores? I'm open to changing how the system is configured (i.e. which core does what) if that helps.


text:
Problem with sending a GET request using the WiFiEsp library
Hello I am trying to make a request using WiFiEsp library but even the examples not working, I have searched a lot but never solved it. most of the solutions are outdated and do not solve anything, I am using Arduino Mega 2560 and ESP8266
the problem as shown in the log is that it's not connected to google.com and I have tried my APIs and I got the same response.
code:
/*
 WiFiEsp example: WebClient

 This sketch connects to google website using an ESP8266 module to
 perform a simple web search.

 For more details see: http://yaab-arduino.blogspot.com/p/wifiesp-example-client.html
*/

#include "WiFiEsp.h"

// Emulate Serial1 on pins 6/7 if not present
#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(6, 7);  // RX, TX
#endif
char ssid[] = "IOT";          // name
char pass[] = "60606060";     // password
int status = WL_IDLE_STATUS;  // the Wifi radio's status

char server[] = "www.google.com";

// Initialize the Ethernet client object
WiFiEspClient client;

void setup() {
  // initialize serial for debugging
  Serial.begin(115200);
  // initialize serial for ESP module
  Serial1.begin(9600);
  // initialize ESP module
  WiFi.init(&Serial1);

  // check for the presence of the shield
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue
    while (true)
      ;
  }

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

  // you're connected now, so print out the data
  Serial.println("You're connected to the network");

  printWifiStatus();

  Serial.println();
  Serial.println("Starting connection to server...");
  // if you get a connection, report back via serial
  if (client.connectSSL(server, 443)) {
    Serial.println("Connected to server");
    // Make a HTTP request
    client.println("GET / HTTP/1.1");
    delay(100);
    client.println("Host: www.google.com");
    delay(100);

    client.println("Connection: close");
    delay(100);

    client.println();
  }
}

void loop() {
  // if there are incoming bytes available
  // from the server, read them and print them
  while (client.available()) {
    char c = client.read();
    Serial.write(c);
  }

  // if the server's disconnected, stop the client
  if (!client.connected()) {
    Serial.println();
    Serial.println("Disconnecting from server...");
    client.stop();

    // do nothing forevermore
    while (true)
      ;
  }
}

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

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

  // print the received signal strength
  long rssi = WiFi.RSSI();
  Serial.print("Signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

and this is the log
23:21:51.468 -> ----------------------------------------------
23:21:51.468 -> >> AT+CIFSR
23:21:51.533 -> +CIFSR:STAIP,"192.168.1.4"
23:21:51.533 -> +CIFSR:STAMAC,"e8:db:84:df:8b:46"
23:21:51.575 ->
23:21:51.575 -> OK
23:21:51.575 -> ---------------------------------------------- > 192.168.1.4!h=
23:21:51.575 ->
23:21:51.575 -> IP Address: 192.168.1.4
23:21:51.575 -> > getCurrentRSSI
23:21:51.575 -> ----------------------------------------------
23:21:51.575 -> >> AT+CWJAP?
23:21:51.607 -> +CWJAP:"IOT","b4:f5:8e:b5:2f:d9",1,-51
23:21:51.653 ->
23:21:51.653 -> OK
23:21:51.653 -> ---------------------------------------------- > 512
23:21:51.653 ->
23:21:51.653 -> Signal strength (RSSI):-512 dBm
23:21:51.653 ->
23:21:51.653 -> Starting connection to server...
23:21:51.653 -> [WiFiEsp] Connecting to www.google.com
23:21:51.653 -> > startClient www.google.com 443
23:21:51.653 -> ----------------------------------------------
23:21:51.653 -> >> AT+CIPSSLSIZE=4096
23:21:51.700 ->
23:21:51.700 -> OK
23:21:51.700 -> ---------------------------------------------- > 0
23:21:51.700 ->
23:21:51.700 -> ----------------------------------------------
23:21:51.700 -> >> AT+CIPSTART=3,"SSL","www.google.com",443
23:21:52.018 ->
23:21:52.018 -> ERROR
23:21:52.018 -> ---------------------------------------------- > 1
23:21:52.018 ->
23:21:52.018 -> > getClientState 3
23:21:52.018 -> ----------------------------------------------
23:21:52.050 -> >> AT+CIPSTATUS
23:21:52.050 -> 3,CLOSED
23:21:52.050 -> STATUS:4
23:21:52.050 ->
23:21:52.050 -> OK
23:21:52.050 -> No start tag found: 0
23:21:52.050 -> ---------------------------------------------- >
23:21:52.092 ->
23:21:52.092 -> Not connected
23:21:52.092 ->
23:21:52.092 -> Disconnecting from server...

AT firmware doesn't support TLS 1.3 encryption used by most sites now.. try Jiri Bilek's 'fake' AT firmware https://github.com/JiriBilek/ESP_ATMod Best with my WiFiEspAT library


text:
ArduinoModbus / RS485 conflict between Serial and Serial1
I am attempting implement ArduinoModbus on my STM32 Poternta H7 using the breakout board.
Its well documented that in ArduinoRS485 that the RS485 object is hardwired. If you are using the PH7/Breakout board you need to reconfigure to make sure that the RS485 is set to Serial1/Uart1.
After i have reconfigured, when i run my code i intially can write debug messages to the Serial monitor via Serial (Onboard USB C). But once i start using RS485 on Serial1 i can no longer print to the serial monitor via Serial and the code freezes.
What i did to re configure the RS485 obj. I implemented the following based on this work around from Arduino ArduinoModbus for other shields and with different Serial port - MKR SHIELDS - Arduino Forum 1
Then saved my updated ArduinoRS485 in /lib.
In ArduinoRS485.cpp
void RS485Class::setSerial(HardwareSerial* serial) {
  _serial = serial;
}

In ArduinoRS485.h
void setSerial(HardwareSerial* serial);

In my setup code i defined;
#define UART1_TX_PIN PA_9       // J1 header 33 (LPUART) = SERIAL1_TX  = R0
 #define UART1_RX_PIN PA_10      // J1 header 35 (LPUART) = SERIAL1_RX   = DI
 #define UART1_RTS_PIN PI_14     // J1 header 37 (LPUART) = SERIAL1_RTS  = REn pin
 #define UART1_CTS_PIN PI_15     // J1 header 39 (LPUART) = SERIAL1_CTS  = DE
 #define SERIAL_PORT_HARDWARE Serial1

My ModbusClient set up
void modbusClientSetup() {

   while (!Serial);
     Serial.println("");
     Serial.println("Modbus RTU Client Test");

     RS485.setPins(UART1_TX_PIN, UART1_RX_PIN, UART1_RTS_PIN);
     RS485.setDelays(50,50);
     RS485.setSerial(&SERIAL_PORT_HARDWARE);

     if(!ModbusRTUClient.begin(9600,SERIAL_8N1 )){
     //Serial.println("Failed to start Modbus RTU Client!");
     while (1);
   }
 }

The line Serial.println("Modbus RTU Client Test"); works fine.
Then i run this code to test my Modbus

 void writeCoilValues() {

   // set the coils to 1 when counter is odd
   byte coilValue = ((counter % 2) == 0) ? 0x00 : 0x01;

   Serial.print("Writing Coil values ... ");

   // write 10 Coil values to (slave) id 1, address 0x00
   ModbusRTUClient.beginTransmission(slaveID, COILS, 0x15, 10);>   for (int i = 0;
     i < 10; i++) {
     counter = i;
     coilValue = ((counter % 2) == 0) ? 0x00 : 0x01;
     ModbusRTUClient.write(coilValue);
     delay(100);

   if (!ModbusRTUClient.endTransmission()) {
     Serial.print("failed! ");
     errClient = ModbusRTUClient.lastError();
     Serial.println(errClient);
   } else {
     errClient = "All Good";
     Serial.println("success");
   }
 }

The line Serial.print("Writing Coil values ... "); does not print but the code does not freeze.
But once i get to Serial.print("failed! "); the code just freezes at write_op.wait(NULL); within USBCDC.cpp below.
bool USBCDC::send(uint8_t *buffer, uint32_t size)
 {
     lock();

     AsyncWrite write_op(this, buffer, size);
     _tx_list.add(&write_op);

     unlock();

     write_op.wait(NULL);
     return write_op.result;
 }

I have been stepping thru this for the last days, but i still cant find where if fails. if anyone has an idea or a better method please let me know.
Cheers

Its well documented that in ArduinoRS485 that the RS485 object is hardwired.

I don't know where you get the "well-documented" information from, both ArduinoRS485 library and ArduinoModbus library allows you to pass-in the serial port that you are going to use through Class construct. You can see the source code of RS485 Construct and ModbusRTU Construct.
So what you need to do to use the Serial1 is to create an instance of the Class and pass-in the serial port that you are going to use.
#include <ArduinoRS485.h>
#include <ArduinoModbus.h>

#define UART1_TX_PIN PA_9       // J1 header 33 (LPUART) = SERIAL1_TX  = R0
#define UART1_RX_PIN PA_10      // J1 header 35 (LPUART) = SERIAL1_RX   = DI
#define UART1_RTS_PIN PI_14     // J1 header 37 (LPUART) = SERIAL1_RTS  = REn pin
#define UART1_CTS_PIN PI_15     // J1 header 39 (LPUART) = SERIAL1_CTS  = DE

RS485 rs485(Serial1, UART1_TX_PIN, UART1_RX_PIN, UART1_RTS_PIN, UART1_CTS_PIN);
ModbusRTUClient mbClient(&rs485);

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

  // start the Modbus RTU client
  if (!mbClient.begin(9600)) {
    Serial.println("Failed to start Modbus RTU Client!");
    while (1);
  }
}

void loop() {
 // access various ModbusRTUClient methods with the mbClient object
}

Thanks
this worked (almost, i had to make a few changes but it got me there,  i have added the required changes below).   I had attepted a version of this approach before but for some reason i couldnt get it to work.
#include <ArduinoRS485.h>
#include <ArduinoModbus.h>

#define UART1_TX_PIN PA_9       // J1 header 33 (LPUART) = SERIAL1_TX  = R0
#define UART1_RX_PIN PA_10      // J1 header 35 (LPUART) = SERIAL1_RX   = DI
#define UART1_RTS_PIN PI_14     // J1 header 37 (LPUART) = SERIAL1_RTS  = REn pin
#define UART1_CTS_PIN PI_15     // J1 header 39 (LPUART) = SERIAL1_CTS  = DE

// These next two lines are different.
RS485Class rs485(Serial1, UART1_TX_PIN, UART1_RX_PIN, UART1_RTS_PIN);
ModbusRTUClientClass mbClient(&rs485);

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

  // start the Modbus RTU client
  if (!mbClient.begin(9600)) {
    Serial.println("Failed to start Modbus RTU Client!");
    while (1);
  }
}

void loop() {
 // access various ModbusRTUClient methods with the mbClient object
}

RS485Class is not necessary, RS485 should work, see source code. Same for ModbusRTUClient.

Hi and thanks again.  Tried it again, and i can only get the code working when i use RS485Class and ModbusRTUClientClass to define my mbClient obj.


text:
Can arduino be used in industrial projects?
I'm developing an industrial project and my programming knowledge is limited to arduino.
I'm planning to use either Atmega328 or STM32F103C8T6 chip in my pcb and to program it using arduino IDE. My plan is just to use Arduino IDE to create sketches and programming the chip after burning arduino bootloader.
Is this concept viable for industrial environments? Are there any problems/challenges using this method?

I don't think there are any major problems with your proposal. The chips themselves will have documented limitations (specifications) that you would need to be aware of. I think you would find that most manufacturers of washing machines, toasters, TVs etc. do not also manufacture processor chips, so they too would be relying on commercially-available chips such as the ones you mentioned.
This brings us to the IDE. It is basically a "wrapper" around a C++ compiler which is available for anyone to use in any project. The Arduino libraries themselves may have licensing you would need to be aware of, the same as if you used a library not associated with the Arduino.
See this page: Licensing for products based on Arduino:

Note:

You can freely use Arduino hardware and software for your personal purposes, or within your company or organization, with no restrictions. The rules described in this document apply only when you distribute products based on Arduino to third parties or you make them public in any form.
If you comply with the open-source licenses of Arduino, you can distribute your software/hardware products for free or commercially. This document provides a summary of such rules for your convenience and does not waive the need to get professional legal advice.

I am not a  lawyer, and if you are worried about the legal aspects I suggest you get legal advice. However I doubt that a small-scale project would warrant anyone getting their lawyers involved. For one thing, it would be hard to prove that the 0s and 1s on your chip were produced using the Arduino IDE, or any of its libraries.

You don't talk about Arduino hardware. Your concern is the Arduino IDE.
Which is a lawyer's licensing topic. Might depend on the libraries you plan to use. And whether you want to hide the fact you're using (selling ?) open source software.

The chips should work fine, however it depends on how things are assembled, what parts are used, ambient temperature, cooling and electronic protection. For reference here is what I use:
Hobby: 0°C to 50°C
Commercial: 0 ° to 70 °C.
Industrial: −40 ° to 85 °C.
Military: −55 ° to 125 °C.
Automotive: -40°C to 175°C, location dependent.
Without a complete set of specifications, schematic, and component information I cannot give you a yes or no answer.
At this point you should realize it will not be a slam dunk simple project.

Industrial environments can be hostile to electronics that aren't "hardened" against the potential hazards. There is no one answer to this without knowing the specific environment. Will it be controlling heavy electrical machinery (even if not switching the power). You'll need to know more about the intended environment to know whether and how you can harden your electronics to it.
But if nothing else, Arduino is terrific for prototyping things that, once the concept is proven, might then have to be re-built to a higher standard for production use.

If the project is also going to have a commercial aspect to it you may also want to look at some of the licensing models applicable to Arduino projects.


text:
Arduino Uno RFID-RC522 won't scan any card or tag
So I bought a RFID-RC522 module with a blue tag and a white card, and I searched for tutorials and found this library that I used it.
and here is my code :
#include <MFRC522.h>
#include <SPI.h>

#define SAD 10
#define RST 9

MFRC522 nfc(SAD, RST);

void setup() {
  SPI.begin();
  // Read a fast as possible. There is a limit for how long we are
  // allowed to read from the tags.
  Serial.begin(115200);

  Serial.println("Looking for MFRC522.");
  nfc.begin();

  // Get the firmware version of the RFID chip
  byte version = nfc.getFirmwareVersion();
  if (! version) {
    Serial.print("Didn't find MFRC522 board.");
    while(1); //halt
  }

  Serial.print("Found chip MFRC522 ");
  Serial.print("Firmware ver. 0x");
  Serial.print(version, HEX);
  Serial.println(".");
}

byte keyA[6] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, };
byte keyB[6] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, };

void loop() {
  byte status;
  byte data[MAX_LEN];
  byte serial[5];
  int i, j, pos;

  // Send a general request out into the aether. If there is a tag in
  // the area it will respond and the status will be MI_OK.
  status = nfc.requestTag(MF1_REQIDL, data);

  if (status == MI_OK) {
    Serial.println("Tag detected.");
    Serial.print("Type: ");
    Serial.print(data[0], HEX);
    Serial.print(", ");
    Serial.println(data[1], HEX);

    // calculate the anti-collision value for the currently detected
    // tag and write the serial into the data array.
    status = nfc.antiCollision(data);
    memcpy(serial, data, 5);

    Serial.println("The serial nb of the tag is:");
    for (i = 0; i < 3; i++) {
      Serial.print(serial[i], HEX);
      Serial.print(", ");
    }
    Serial.println(serial[3], HEX);

    // Select the tag that we want to talk to. If we don't do this the
    // chip does not know which tag it should talk if there should be
    // any other tags in the area..
    nfc.selectTag(serial);

    // Assuming that there are only 64 blocks of memory in this chip.
    for (i = 0; i < 64; i++) {
      // Try to authenticate each block first with the A key.
      status = nfc.authenticate(MF1_AUTHENT1A, i, keyA, serial);
      if (status == MI_OK) {
        Serial.print("Authenticated block nb. 0x");
        Serial.print(i, HEX);
        Serial.println(" with key A.");
        // Reading block i from the tag into data.
        status = nfc.readFromTag(i, data);
        if (status == MI_OK) {
          // If there was no error when reading; print all the hex
          // values in the data.
          for (j = 0; j < 15; j++) {
            Serial.print(data[j], HEX);
            Serial.print(", ");
          }
          Serial.println(data[15], HEX);
        } else {
          Serial.println("Read failed.");
        }
      } else {
        // If we could not authenticate with the A key, we will try
        // the B key.
        status = nfc.authenticate(MF1_AUTHENT1B, i, keyB, serial);
        if (status == MI_OK) {
          Serial.print("Authenticated block nb. 0x");
          Serial.print(i, HEX);
          Serial.println(" with key B.");
          status = nfc.readFromTag(i, data);
          if (status == MI_OK) {
            for (j = 0; j < 15; j++) {
              Serial.print(data[j], HEX);
              Serial.print(", ");
            }
            Serial.println(data[15], HEX);
          } else {
            Serial.println("Read failed.");
          }
        } else {
          Serial.print("Access denied at block nb. 0x");
          Serial.println(i, HEX);
        }
      }
    }

    // Stop the tag and get ready for reading a new tag.
    nfc.haltTag();
  }
  delay(2000);
}

and I connected the module like this :
===================================
|   RFID-RC522   |  Arduino Uno   |
___________________________________
|      SDA       |       10       |
|      SCK       |       13       |
|      MOSI      |       11       |
|      MISOI     |       12       |
|      RQ        |     Skipped    |
|      GND       |       GND      |
|      RST       |        9       |
|      3.3V      |       3.3V     |
===================================

and when I virify and uplaod the code, the RFID-RC522 module turned the light D1 to On (red light)
and in the serial it show :
Looking for MFRC522.
Didn't find MFRC522 board.

and when i try to scan the card or the tag nothing happened in the serial, I searched in google and i found that Arduino uno 3.3V pin is too weak, so i changed the 3.3V to 5V, and click in reset button of arduino uno board and check the serial and it showed :
Looking for MFRC522.
Found chip MFRC522 Firmware ver. 0xFF.

But still not scaning the tag or the card (also tried another tag and another card that i bought them from the same seller and still not working)
any help please, and thanks

use an external power supply that can deliver the necessary current ... please review the RFID-RC522 module datasheet for minimum power requirement

What is external power? a battery ? or resistor... and thanks for reply

a resistor is not a power supply ... do not use the Arduino to supply power... use anything that is able provide the required voltage to the RFID reader at the necessary current level ... 5 Vdc power supply is probably the most suitable


text:
Error while trying to connect CH341 driver
I'm trying to connect an Arduino board to IDE on Ubuntu, and I have the following driver log:
[  543.412356] usb 1-2: USB disconnect, device number 3
[  549.593729] usb 1-2: new full-speed USB device number 7 using xhci_hcd
[  549.748438] usb 1-2: New USB device found, idVendor=1a86, idProduct=7523, bcdDevice= 2.54
[  549.748449] usb 1-2: New USB device strings: Mfr=0, Product=2, SerialNumber=0
[  549.748454] usb 1-2: Product: USB2.0-Serial
[  549.750234] ch341 1-2:1.0: ch341-uart converter detected
[  549.750859] usb 1-2: ch341-uart converter now attached to ttyUSB0
[  550.347356] input: BRLTTY 6.4 Linux Screen Driver Keyboard as /devices/virtual/input/input20
[  550.462814] usb 1-2: usbfs: interface 0 claimed by ch341 while 'brltty' sets config #1
[  550.463418] ch341-uart ttyUSB0: ch341-uart converter now disconnected from ttyUSB0
[  550.463437] ch341 1-2:1.0: device disconnected

As a result no ports are found, any suggestion?

Solved, thanks to this [article][1]
sudo apt autoremove brltty

remove the conflict and now the board is visible
[1]: https://0xsuk.github.io/posts/2022-07-19-how-to-install-ch340-on-ubuntu-22.04/


text:
Joystick library not reading potentiometer
I am using Joystick Library to make a HOTAS system for flight simulators. When I load the test program I can get all the simulated controller inputs to register in windows. I can also get the value from my slide potentiometer to read in the serial monitor. But it will not change the value of the input function i pass it to. my guess is its the wrong kind of integer but I don't know very much about int types. Joystick.setThrottle has an int32_t as a parameter. Windows reads the value of throttle at 49% when its connected.
What I have tried:
changing the range (the default is 0 to 1023 I want it to be 0 to 255)
changing the type of throttle_ to int, unsigned int, and int_32_t
changing initAutoSendState
using the pin number instead of the macro throttle
passing throttle_ directly into Joystick.setThrottle without the updateThrottle function
I have some programming experience from my high school class so I just tried different approaches but I am new to Arduino.
#include "Joystick.h"
//define input pins
#define throttle A0
//include hid, type, button count, hat count, x axis, y axis, z axis, Rx axis, Ry axis, Rz axis, rudder, Throttle, Accelerator,  Brake, Steering
Joystick_ Joystick(JOYSTICK_DEFAULT_REPORT_ID,JOYSTICK_TYPE_JOYSTICK, 0, 0, false, false, false, false, false, false, false, true, false, false, false);
const bool initAutoSendState = true;

int32_t throttle_ = 0;
void updateThrottle (int32_t value)
{
Joystick.setThrottle(value);
}
void setup() {
  // put your setup code here, to run once:

Serial.begin(9600);
pinMode(throttle, INPUT_PULLUP);
Joystick.setThrottleRange(0, 255);

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

  throttle_ = analogRead(throttle);
  throttle_ = map(throttle_, 0, 1023, 0,  255);
updateThrottle(throttle_);
Serial.print(throttle_);
Serial.print("\n");

}

Looking through the examples turns out I needed to add Joystick.begin(); to the setup


text:
Starting Off Low-Level Port Access
   I'm trying to teach myself some low[er] level code, but I just can't get it to work. I've tried OR-ing stuff in, AND-ing stuff in, and just straight up defining stuff, but it's not blinking! What am I doing wrong here?
I am using an Arduino UNO R3 DIP for this. I am just using the on-board LED, (on pin13/PORTB_5)
Current code:
#define STATE B00001000
#define ZERO B00000000
void setup() {
    DDRB = STATE;
    }

void loop(){
    PORTB |= STATE;
    delay(500);
    PORTB &= ZERO;
    delay(500);
    }

It would probably help if you were using the right pin.  In the pins_arduino.h file for the Uno is this diagram:
//                  +-\/-+
//            PC6  1|    |28  PC5 (AI 5)
//      (D 0) PD0  2|    |27  PC4 (AI 4)
//      (D 1) PD1  3|    |26  PC3 (AI 3)
//      (D 2) PD2  4|    |25  PC2 (AI 2)
// PWM+ (D 3) PD3  5|    |24  PC1 (AI 1)
//      (D 4) PD4  6|    |23  PC0 (AI 0)
//            VCC  7|    |22  GND
//            GND  8|    |21  AREF
//            PB6  9|    |20  AVCC
//            PB7 10|    |19  PB5 (D 13)
// PWM+ (D 5) PD5 11|    |18  PB4 (D 12)
// PWM+ (D 6) PD6 12|    |17  PB3 (D 11) PWM
//      (D 7) PD7 13|    |16  PB2 (D 10) PWM
//      (D 8) PB0 14|    |15  PB1 (D 9) PWM
//                  +----+

That shows that pin D 13 is PB5 which would be a binary value of 0b00100000 not 0b00001000 as you have, which would be PB3, or pin D11.
The only way I can come up with 0b00001000 is if I count from the left (wrong) and start at 1 (wrong) rather than count from the right (right) and start at 0 (right).

Yeah, that's exactly what I did... I'm used to the other bit order, so that's what screwed me up. And also counting from 1... Oops. But thanks!

The other bit order? There is only one bit order. All numbers count from the right. After all, 5 + 7 isn't 21, it's 12. The same applies to all bases - base 2 (binary), base 16 (hexadecimal), base 60 (sexagecimal)...

I was thinking of MSBF vs LSBF haha

That only makes any sense in the scope of serial communication.

Oh, by the way - your logical operators are pretty pointless.  The OR is OK since it just turns on one pin, but the AND is bad, since it turns off ALL pins.  You should be ANDing with 0b11011111 to maintain the state of all the other pins.  That would be equivalent to PORTB &= ~STATE.


text:
I2C or SPI to control 6 motors?
I am a hobbyist & know little about electronics.
I am making a robot arm, like this one. For which I will need 2 stepper motors (for elbow & shoulder joint) & 4 simple DC motors.
Which means I will need to allocate a lot of pins on my board (Uno).
So I was just reading about I2C & then eventually SPI. My question is:

Is it possible to control 6 motors (or atleast 2 steppers) with I2C or SPI (assuming the motors are powered by seperate source), if so can you point me to someone's example code.
If not possible, how do I overcome the shortage of pins, because I have already dedicated them to many sensors.

For the stepper motors, the easiest way to work with them is by using a very common A4988 board which is widely used with 3D printers. The controls are very easy and for them I send you this question which I answered some time ago.
Then, you say that you haven't got a lot of connections left on your UNO board, so I think that SPI would't be very useful, as it takes 3 pins for the data transmission (SCLK, MOSI, MISO) plus one pin for every device you connect.
The best way (even if it is a little slower that SPI) is to use I2C, which needs that you leave unused analog input pins A4 and A5, as they are the I2C BUS. Unfortunately I haven't any knowledge about I2C DC motor drivers.
For the steppers, I suggest to take a look at this, but it depends by your budget for what you can buy.
You could fix the pin shortage problem by adding some 74HC595 shift registers. They aren't very expensive (less than a dollar, or if you live in europe, .5€) and they can be daisy-chained. To control them, see the Arduino website tutorial.
Finally, if the pins that you use are inputs, use a 74HC165, which is the opposite of a 595. As always, see the Arduino website tutorial.


text:
How to control 2 servos at same time in sync?
For overcoming torque issues, I have attached 2 identical servos on a certain part of my robot arm and because I saw someone do the same.
Now, while writing code I realize:
#include <Servo.h>
...
...
shoulder1.write(map(analogRead(p1), 0, 1023, 0, 179));
shoulder2.write(map(analogRead(p1), 0, 1023, 0, 179));
...

will turn shoulder1 by 20* and then shoulder2 by another 20*, ie. an overall turn of 40*; that too with too much load on servos, as the other servo would be inactive at the time first is active.
I want to achieve 20* fully-sync.ed turn on both servos, how do I accomplish this? Any arduino libraries or walkthrough?

Can I possibly move them both at the same time - something like multithreading on arduino? Here's what I tried:
void rotateTwoServoInSync(int angle) {
    for(int i = 0; i<angle; i++) {
        shoulder1.attach(9);
        shoulder1.write(i);
        shoulder1.detach();
        shoulder2.attach(10);
        shoulder2.write(i);
        shoulder2.detach();
    }
}

Will it work? Is this approach recommendable?

you do know that all of that code executes WAAAAY faster than the response time of the servos, and they will, for the most part, operate at the same time?

if you write both outputs at the same time (two lines of code sequentially) it is enough for them to operate in sync.

If you have two RC servos that are always required to move together you can simply connect both control inputs to a single output.

So do I need a NPN transistor to amplify the signal?

Nope. Just connect and drive them together.

Spehro's answer is the most obvious. But note that there is no such thing as identical servos. You may stress them if you connect them through a stiff connection.
If you want to have two mechanical parts make the same movement the proper solution is to connect them mechanically, rather than have two servos doing the same action.

analogRead() and map() are slow; only perform them once.
unsigned char rot = map(analogRead(p1), 0, 1023, 0, 179);
shoulder1.write(rot);
shoulder2.write(rot);

I will implement your advice - but still if rot is 150* then wouldn't shoulder1's 150* movement w.r.t. shoulder2's stationary position break/burn the setup?

Only if your setup is made of diamond. Otherwise it will have plenty of flexibility to handle the few hundreds of nanoseconds of difference.

I don't know if I agree to that - but torque issue is still unsolved.

Then your servos aren't identical.

To operate two or more servos at the same time you need to interpolate their movements, first moving one servo a little, then moving the next one, back and forth until all servos arrive at their destination point. I haven't seen a library yet that accomplishes this for you so you probably need to write your own routine. Here is a project where I interpolated three servos and includes the code: https://www.instructables.com/id/MonkeyBot-3-Servo-Climbing-Robot/


text:
Adding a steering servo
I got a Sparkfun Redbot Kit a while back. I ended up building it vanilla and it was a good introduction to the board (the board is basically Uno and a motor shield in one) and the toys that came with it. I figured if could scavenge an RC car, I'd get a more robust redbot. I found an old RC Rock Crawler, it has a basic suspension, two motors, and a steering servo.
Unfortunately, I encountered a problem. The steering servo only has two wires. I loaded the Servo -> Sweep example that is default in the Arduino IDE to see if I could make it work regardless. I tried all the different all the different wire/header combinations on the servo headers:

When I attach the wires to gnd and # I get a buzzing noise.
When I attach the wires to gnd and pow the servo turns left or, if I swap the wires, it turns right.
When I attach the wires to pow and # nothing happens.

I currently can't take advantage of the servo headers on the board (or at least I don't know how to). I was hoping that I could that there might be a work around, I just don't know what it is.
The obvious answer is that I could run both motors off of only one of the headers and use the other to control the steering (thats how the original board from the car was wired), but I can get a faster car if each motor has its own header, and I'm all about the vroom vroom...
I'm running the whole thing off the default 6v (4 AA) battery pack. I might be able to wire in the extra 2 AA's for the extra 3v but I don't want mess with the wiring on the pack unless I know it's going to work.
I have an accelerometer connected to the A4 A5 header block and the motors connected too (I checked w/o them connected but there was no difference).

Image courtesy of https://learn.sparkfun.com/tutorials/getting-started-with-the-redbot
More info on the redbot board https://www.sparkfun.com/products/12097

If the motor you are using has only two wires, and as you described it's response to the direct connection to the power, it can't be a servo. The motor is a normal dc motor.
If you want to control the amount of the turns on your rc car you should try to play with the pwm signal, I don't know if it will work or not but at least you will have tried. And remember not to connect the motor directly on the micro's pin if there no motor pins on your red board.


text:
interrupt and/or other ressources used by Time functions micros() and delayMicroseconds()
I want to use Arduino Uno (Rev. 3) resp. Arduino Nano for time critical ignition control of a combustion engine. Software is developed under arduino rev. 1.6.2.
The only Arduino system functions i use are micros()  and delayMicroseconds(). I suppose they are implemented by a timer interrupt, which may fire within time critical port polling regions of the program.
What's the maximum runtime for the ISR i have to expect? As long it stays within the range of a few microseconds, say 10 or like, it would be tolerable.
Are there other time ressources used in the background by the arduino system i have to cope with?

Here is the The ISR code.
Here is the obj-dump:
000008f6 <__vector_16>:
#if defined(__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
ISR(TIM0_OVF_vect)
#else
ISR(TIMER0_OVF_vect)
#endif
{
 8f6:   1f 92           push    r1
 8f8:   0f 92           push    r0
 8fa:   0f b6           in  r0, 0x3f    ; 63
 8fc:   0f 92           push    r0
 8fe:   11 24           eor r1, r1
 900:   2f 93           push    r18
 902:   3f 93           push    r19
 904:   8f 93           push    r24
 906:   9f 93           push    r25
 908:   af 93           push    r26
 90a:   bf 93           push    r27
    // copy these to local variables so they can be stored in registers
    // (volatile variables must be read from memory on every access)
    unsigned long m = timer0_millis;
 90c:   80 91 a0 01     lds r24, 0x01A0
 910:   90 91 a1 01     lds r25, 0x01A1
 914:   a0 91 a2 01     lds r26, 0x01A2
 918:   b0 91 a3 01     lds r27, 0x01A3
    unsigned char f = timer0_fract;
 91c:   30 91 9f 01     lds r19, 0x019F

    m += MILLIS_INC;
    f += FRACT_INC;
 920:   20 e3           ldi r18, 0x30   ; 48
 922:   23 0f           add r18, r19
    if (f >= FRACT_MAX) {
 924:   2d 37           cpi r18, 0x7D   ; 125
 926:   20 f4           brcc    .+8         ; 0x930 <__stack+0x31>
    // copy these to local variables so they can be stored in registers
    // (volatile variables must be read from memory on every access)
    unsigned long m = timer0_millis;
    unsigned char f = timer0_fract;

    m += MILLIS_INC;
 928:   40 96           adiw    r24, 0x10   ; 16
 92a:   a1 1d           adc r26, r1
 92c:   b1 1d           adc r27, r1
 92e:   05 c0           rjmp    .+10        ; 0x93a <__stack+0x3b>
    f += FRACT_INC;
    if (f >= FRACT_MAX) {
        f -= FRACT_MAX;
 930:   23 eb           ldi r18, 0xB3   ; 179
 932:   23 0f           add r18, r19
        m += 1;
 934:   41 96           adiw    r24, 0x11   ; 17
 936:   a1 1d           adc r26, r1
 938:   b1 1d           adc r27, r1
    }

    timer0_fract = f;
 93a:   20 93 9f 01     sts 0x019F, r18
    timer0_millis = m;
 93e:   80 93 a0 01     sts 0x01A0, r24
 942:   90 93 a1 01     sts 0x01A1, r25
 946:   a0 93 a2 01     sts 0x01A2, r26
 94a:   b0 93 a3 01     sts 0x01A3, r27
    timer0_overflow_count++;
 94e:   80 91 a4 01     lds r24, 0x01A4
 952:   90 91 a5 01     lds r25, 0x01A5
 956:   a0 91 a6 01     lds r26, 0x01A6
 95a:   b0 91 a7 01     lds r27, 0x01A7
 95e:   01 96           adiw    r24, 0x01   ; 1
 960:   a1 1d           adc r26, r1
 962:   b1 1d           adc r27, r1
 964:   80 93 a4 01     sts 0x01A4, r24
 968:   90 93 a5 01     sts 0x01A5, r25
 96c:   a0 93 a6 01     sts 0x01A6, r26
 970:   b0 93 a7 01     sts 0x01A7, r27
}
 974:   bf 91           pop r27
 976:   af 91           pop r26
 978:   9f 91           pop r25
 97a:   8f 91           pop r24
 97c:   3f 91           pop r19
 97e:   2f 91           pop r18
 980:   0f 90           pop r0
 982:   0f be           out 0x3f, r0    ; 63
 984:   0f 90           pop r0
 986:   1f 90           pop r1
 988:   18 95           reti

I'll let you calculate how many clock cycles that is. My guess is that it's less that 160 clock cycles (i.e. 10S).
But I'm unsure if the accuracy of micros is good enough in your application.


text:
Shift Register on ATMEGA328p
I want to learn more about the shiftout function used with Arduinos and used the implementation with my ATMEGA328p.
The Setup
This is the original shiftout function used in Arduino Programming, except that I replaced 1 with HIGH.
#define F_CPU 1000000UL
#define BAUD 9600UL
#define LSBFIRST 0
#define MSBFIRST 1
#define HIGH 0x1
#define LOW  0x0
#define INPUT 0x0
#define OUTPUT 0x1

#include <avr/io.h>
#include <util/delay.h>
#include <USART.h>
#include <pinDefines.h>

#define DATA PD7
#define LATCH PB2
#define CLOCK PB0

void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val)
{
    uint8_t i;
    for (i = 0; i < 8; ++i) {
        if (bitOrder == LSBFIRST) {
            PORTD |= (!!(val & (HIGH << i)) << DATA);
            } else {
            PORTD |= (!!(val & (HIGH << (7 - i))) << DATA);
        }
        PORTB |= (HIGH << clockPin);
        PORTB &= ~(HIGH << clockPin);
        }
}

Main
int main(void)
{
    initUSART();
    DDRD |= (HIGH << DATA);
    DDRB |= (HIGH << LATCH) && (HIGH << CLOCK);

    PORTB |= (HIGH << LATCH);
    shiftOut(DATA, CLOCK, LSBFIRST, 1);
    printBinaryByte(PIND);
    PORTB ^= (HIGH << LATCH);

    /* Replace with your application code */
    while (1)
    {

    }

    return (0);
}

I created an example to understand more about the function, but the outcome does not add up to what I expected to see.
Szenario
PORTD |= (!!(val & (HIGH << 0)) << DATA);

This is what I expect for val = 1

(HIGH << 0) = 00000001
val & (HIGH << 0) = 00000001 & 00000001
!!(val & (HIGH << 0)) = 1
PORTD |= (1 << DATA)

As PORTD is the data pin on the shift register, it should get 00000001.
When I print the binary number within PORTD I get: 10000111 and my LED Array connected to the 74HC595 displays: 10101111
I am really lost.... I checked the connections to the LEDs and they are all good. Can you explain to me why I receive this awkward result?

This is what I expect for val = 1
PORTD |= (1 << DATA)
As PORTD is the data pin on the shift register, it should get 00000001.

your deduction is correct and the code is correct -> remember this is the case for LSBFIRST. so "val = 0x01" should be sent out as "0b1000 0000", which is precisely what the code is doing.

!(val & (HIGH << 0))

the "!!" operator is often used to turn a logic value into either '1' or '0'.
the code for shiftout() can be greatly improved.

First of all, PORTD represents the current output state of 8 physical GPIO pins (I think some devices have fewer pins on a port but usually there's 8).  I think what you're trying to do is shift a sequence out of a single pin. So just reading it will only tell you what each of the 8 pin states are at that moment, not what you shifted out.  I think Arduino's way of doing things is actually harder than just writing the plain C code so I'll ignore it (what is the '!!' ???).
So taking a step back, here's code for pushing an 8bit number serially out of a pin:
uint8_t serialData = 0b10011101;  // random data to shift out
uint8_t pin = 3;                  // the pin on PORTD we want to toggle

uint8_t i;
uint8_t nextBit;
for (i = 0; i < 8; i++) {

  // Find the nextBit value to set by shifting our input data by our index
  //   and clearing the other values.  E.g. if serialData == 0b10011101 and
  //   i == 2 then (0b10011101 >> 2) == 0b00100111.  0b00100111 & 1 == 1
  nextBit = (serialData >> i) & 0b00000001;

  // If the next bit is a one, we "or" it to set it
  if (nextBit) {
    // The 'or' operator can only set bits to 1
    PORTD |= 1 << pin;        // in this case, (1 << 3) == 0b00001000
  } else {
    // The 'and' operator can only clear bits to 0
    PORTD &= ~(1 << pin);    // in this case, ~(1 << 3) == 0b11110111
  }
}

If you want to add a "clock" pin to go along with the data (like the arduino code) then you can set the clock pin to whatever state before the "for" loop then use an "xor" operator to toggle it each time through the loop:
clockPin = 4;

// just before the 'for' loop set the clock to whatever starting state you
//   want.  In this case I'll start it at 0.
PORTB &= ~(1 << clockPin);
.
.
.
// Now in the 'for' loop (at the bottom for example)
PORTB ^= (1 << clockPin);

If you want the clock to toggle up then down in a sing loop cycle then you can just repeat the 'xor' twice in a row or force the state using 'or' and 'and' operators.  Also, pay attention to timing, you might be toggling things too quickly if the microcontroller clock is fast.  You can add delays to the loop to shape the timing of the pattern.

That is some ugly and needlessly slow code!
Nonetheless, I think the main point you need to keep in mind is that when you OR the value 00000001 into PORTD, you are only changing the bottom bit to a 1 - all other bits will be left untouched to whatever value they already had.
So, it seems that PORTD had the value of either 10000111 or 10000110 before you executed PORTD |= (1 << DATA) (which is the equivalent of PORTD |= 0b00000001)....
   10000110
OR 00000001
===========
   10000111

The output of your shift register is also just an artifact of whatever the most recent series of bits that you sent to it was. Each time you send a new bit, whatever was there will get shifted over and only the single new bit will be shifted in.
Make sense now?


text:
I cannot resolve the errors with attachInterrupt() (error: invalid use of non-static member function)
I have been trying for days to get this code to work, but I cannot find a solution. Can anyone please help me find what I am missing here?
My sketch:
#include <ControlInterrupt.h>

const int commonPin = 2;
const int buttonPins[] = {4,5,6,7,8};

ControlInterrupt controlInterrupt(commonPin, buttonPins);

void setup() {
  // put your setup code here, to run once:
  controlInterrupt.configureCommon(); // Setup pins for  interrupt
  attachInterrupt(digitalPinToInterrupt(commonPin), controlInterrupt.pressInterrupt, FALLING);
  controlInterrupt.begin();
}

void loop() {
  // Empty
}

.h
/*
  ControlInterrupt.h - A library for handling multiple buttons using a single interrupt.
                       This is done by using an interrupt pin effectively as the ground,
                       eliminating the need for additional components.
  Authors: Svizel_pritula 05/05/2019
           TheCodeGeek 01/13/2024
*/
#ifndef ControlInterrupt_h
#define ControlInterrupt_h
#include <Arduino.h>
class ControlInterrupt
{
public:
  ControlInterrupt(int commonPin, int buttonPins[]);
  void begin();
  void pressInterrupt();
  void configureCommon();
  void configureDistinct();
  //void getCommand(int button);

private:
  int _commonPin;
  //int _arrLength;
  int _buttonPins[];
};
#endif

.cpp
/*
  ControlInterrupt.h - A library for handling multiple buttons using a single interrupt.
                       This is done by using an interrupt pin effectively as the ground,
                       eliminating the need for additional components.
  Authors: Svizel_pritula 05/05/2019
           TheCodeGeek 01/13/2024
*/
#include <Arduino.h>
#include <ControlInterrupt.h>

unsigned long lastFire;

ControlInterrupt::ControlInterrupt(int commonPin, int buttonPins[])
//, String commandOrder[]
{
  _commonPin = commonPin;
  _arrLength = sizeof(buttonPins);
  _buttonPins[arrLength] = buttonPins;
  //_commandOrder[arrLength] = commandOrder;

  lastFire = 0;
}

void ControlInterrupt::begin()
{
  Serial.begin(9600);
}

void ControlInterrupt::pressInterrupt()
{ // ISR
  if (millis() - lastFire < 200)
  { // Debounce
    return;
  }
  lastFire = millis();

  configureDistinct(); // Setup  pins for testing individual buttons

  for (int i = 0; i < (sizeof(buttonPins)/sizeof(int)); i++)
  { // Test each button for press
    if (!digitalRead(_buttonPins[i]))
    {
      getCommand(i);
    }
  }

  configureCommon(); // Return to original  state
}

void ControlInterrupt::configureCommon()
{
  pinMode(_commonPin, INPUT_PULLUP);

  for (int i = 0; i < (sizeof(buttonPins)/sizeof(int)); i++)
  {
    pinMode(_buttonPins[i], OUTPUT);
    digitalWrite(_buttonPins[i], LOW);
  }
}

void ControlInterrupt::configureDistinct()
{
  pinMode(_commonPin, OUTPUT);
  digitalWrite(_commonPin, LOW);

  for (int i = 0; i < (sizeof(buttonPins)/sizeof(int)); i++)
  {
    pinMode(_buttonPins[i], INPUT_PULLUP);
  }
}

void ControlInterrupt::getCommand(int button)
//String ControlInterrupt::getCommand(int button)
{               // Our handler
  String label; // This stores the string to print when controls are used

  Serial.print(button + 1);
  Serial.print(": ");
  switch (button)
  {
  case 0:
    // statement
    label = "UP";
    break;
  case 1:
    // statement
    label = "DOWN";
    break;
  case 2:
    // statement
    label = "CLEAR";
    break;
  case 3:
    // statement
    label = "BACK";
    break;
  case 4:
    // statement
    label = "LEFT";
    break;
  case 5:
    // statement
    label = "ENTER";
    break;
  case 6:
    // statement
    label = "RIGHT";
    break;
  default:
    // statement
    break;
  }
  Serial.print(label);
  //return label;
}

It's all based on the code that I found here: https://projecthub.arduino.cc/Svizel_pritula/10-buttons-using-1-interrupt-6e0896

Please edit your post to show the error message you get.

The solution is covered in my post here.
However, to avoid link-only answers, the brief explanation is that a class method has a hidden argument "this" which refers to the instance of the class. In your case the instance is controlInterrupt.
If you are only ever going to have one instance of the class you could replace it with a namespace. Otherwise, make yourself a glue routine as described in that post.

Member functions (here pressInterrupt) in C++ are special. You cannot use them where normal function is required (atrachInterruot). For explanations refer to any good book on C++.
In this particular case, just strip all C++ specific constructs off. They make your code neither shorter nor understandable. All the data for ISR is global anyway.

Hi Matt, could you please explain what you mean by "just strip all C++ specific constructs off"?

@TheCodeGeek Don't use class at all. As an it pro you should be able to figure out how to rewrite the code in plain C, aren't you?


text:
Bad symbols in the serial monitor when connected via USB 3.0
I tested DHT11 + Arduino Uno with a very basic example sketch.
The Arduino board was connected to USB 3.0 and sometimes I saw incorrect symbols in the serial monitor, e. g. "Humidit?: _7%" instead of "Humidity: 37%". This strange effect disappears when I connected the board to USB 2.0. Baudrate in code was always same as baudrate in the terminal settings.
When I increase baudrate I see less bad symbols but they not disappear while Arduino connected to USB 3.0.
The OS is Ubuntu 20, this was the first time I connect the board to USB 3.0. Is this behavior normal?
The sketch:
/**
 * DHT11 Sensor Reader
 * This sketch reads temperature and humidity data from the DHT11 sensor and prints the values to the serial port.
 * It also handles potential error states that might occur during reading.
 *
 * Author: Dhruba Saha
 * Version: 2.1.0
 * License: MIT
 */

// Include the DHT11 library for interfacing with the sensor.
#include <DHT11.h>

// Create an instance of the DHT11 class.
// - For Arduino: Connect the sensor to Digital I/O Pin 2.
// - For ESP32: Connect the sensor to pin GPIO2 or P2.
// - For ESP8266: Connect the sensor to GPIO2 or D4.
DHT11 dht11(4);

void setup() {
  // Initialize serial communication to allow debugging and data readout.
  // Using a baud rate of 9600 bps.
  Serial.begin(9600);

  // Uncomment the line below to set a custom delay between sensor readings (in milliseconds).
  // dht11.setDelay(1500); // Set this to the desired delay. Default is 500ms.
}

void loop() {
  int temperature = 0;
  int humidity = 0;

  // Attempt to read the temperature and humidity values from the DHT11 sensor.
  int result = dht11.readTemperatureHumidity(temperature, humidity);

  // Check the results of the readings.
  // If the reading is successful, print the temperature and humidity values.
  // If there are errors, print the appropriate error messages.
  if (result == 0) {
    Serial.print("Temperature: ");
    Serial.print(temperature);
    Serial.print(" °C\tHumidity: ");
    Serial.print(humidity);
    Serial.println(" %");
  } else {
    // Print error message based on the error code.
    Serial.println(DHT11::getErrorString(result));
  }
}

You are using the UNO's internal serial transceiver, right?

@timemage I guess yes, in this moment I don't know communication variants except default

That really sounds like either a bad cable or a bad USB port on the PC.  The Arduino itself isn't aware of the difference whether it is 2.0 or 3.0.  When you change from 2.0 to 3.0 are you using the same cable just in a different port on the PC?

@Delta_G yes I'm using the same cable. USB 3.0 is on a PCI-E extension board but other devices (BT & WiFi dongles, flash cards) work correctly with this cable, this port and its neighbours. Much better than with built-in 2.0 ports of motherboard.

I still think the issue is going to be on the PC end of the connection somewhere.

Please check if there is any baud rate mismatch. I mean, you have defined serial.begin(9600) in your code. Open the serial monitor selecting the same baud rate please. If that is not the problem, please check the cable. If you have any other operating system, like windows, please check your whole setup with that too.


text:
Why Digispark can be a HID but Arduino Uno/Nano can't?
I tried to make a project with a Nano as a head which was based on a V-USB-like library EasyHID. For unknown reasons this try was unsuccessfull and I couldn't make the Nano run correctly. It's normal: guys wrote, this venture has lesser 50% success because 328p works at the edge of its capabilities when emulate USB protocol.
Later I found that some people uses Digispark as base of their HID projects and it is more stable than Nano. Please explain what are the key differences that make the Attiny win in HID projects? And besides is there a way to recieve signals from 8 and more buttons (analog keyboard?) when P4 and P3 are busy as USB+ and USB-?
P.S. I have no Digispark yet for tests so this interest is hypothetical. This board has very limited functionality so I doubt that I will be able to apply it in other projects.

why do you want to use virtual USB? Arduino Micro/Leonardo has native USB peripheral

@Juraj I'm lookig for cheap and supercompact solution

Micro is as small as Nano

You could use a multi-channel analogue to digital converter, connected to the Attiny via I2C. The ad7606 would give you 8 separate analogue inputs, using just two pins to connect to the I2C bus. As an alternative you could use an ADS1115. This again is an analogue to digital converter chip. It only has 4 channels, but you can connect two to the same I2C bus to give you 8 input channels. The ADS1115 is available on ebay in a neat breadboard-compatible package.
I have rechecked your suggestion of using a PCF8574P. This is not in fact an analogue to digital converter, but an IO bus expander - which means that it gives you 8 digital input/output pins (not analogue). This part is out of producion, but has the advantage that it is a DIP package, so is easy to breadboard.
As to your question about what board to use for HID devices, the Arduino Nano does not have a built-in USB controller, so it cannot be used to emulate a USB device, but the ATtiny85 and the Arduino Leonardo do.

I guess, an I/O bus expander is more suitable in my case, seems it is easier to use with a 16k matrix keyboard I have. And may be you can answer first question about hardware specificity too?

I have added a bit to my answer re the ATtiny and the Nano - and yes - it sounds like you would be better off with a bus expander rather than a multi-channel A to D converter.

In response to the headline question 'Why Digispark can be a HID but Arduino Uno/Nano can't?', the main difference is that the ATtiny85 processor on the DigiSpark is directly connected to the computer via USB, while the Nano/Uno have another chip in between.
The second chip on the Uno/Nano is programmed to be a USB-serial device, so the Uno/Nano cannot be a HID device without reprogramming that chip.
The Nicohood firmware (no affiliation, this is just one example I have heard of) https://github.com/NicoHood/HID is a project that aims to add features to Uno boards by upgrading the firmware on the USB-serial chip on an Uno.
Note that not all USB-serial chips can be upgraded; the ones that I understand are supported are the ATmega16u2 versions.