text:
HTTPS with ESP8266WebServer?
I see many ESP8266HTTPClient examples, pasting in a fingerprint from an outside website, but I want to host an html page from the ESP8266 in AP mode using HTTPS.
Judging by the lack of examples, and the lack of a domain for a cert in AP mode, I'm thinking this is impossible, but would like confirmation before I give up.
Is it impossible to get the browser's green padlock on an AP-served web page?

The ESP8266 just doesn't have sufficient CPU power to do this reliably.
It is possible, since the EPS8266 SDK docs have an "SSL User Manual" which describes this scenario.
In my experience, using the Arduino core for ESP8266, it doesn't work reliably.
Consider using an nginx reverse-proxy and having that proxy handle SSL negotiation. Understand that this is more for situations where the ESP8266 is local, in a network sense, to the nginx proxy, and you consider your WLAN secure enough.
On the plus side, you have room to grow in key sizes and/or complexity.

thanks for the link, that does help. sadly it's not the arduino core, but i guess i could use 2 ESPs, pretending one's an arduino like the noobs setup...


text:
Serial communication PC to Arduino using C and send via NRF
I'm trying to communicate my PC with an Arduino Mega via serial and after send the message via NRF to another Arduino.
But I don't know if the message is send correctly or if it even send the message. Because I can't debug using Serial Monitor. If it is opened the serial port appear as busy.
When I execute the code the TX led on the Arduino blinks, but nothing is send via NRF.
I made some tests using only the NRF between the Arduinos and it's working, but when I try using the PC - Arduino serial communication, nothing happens.
C Code
#include <stdio.h>
#include <string.h>

char arduinoPort[] = "/dev/ttyACM0";

int main() {

  char buffer[] = {'1'};
  int error = 10;
  FILE *usb_port;

  usb_port = fopen(arduinoPort, "rwb");

  if(!usb_port) {
    perror(arduinoPort);
    return 1;
  }

  //memcpy(buffer, &error, sizeof(error));
  fwrite(buffer, sizeof(char), sizeof(buffer), usb_port);

  fclose(usb_port);

  return 0;
}

Arduino Code
#include <nRF24L01.h>
#include <RF24.h>
#include <printf.h>
#include <RF24_config.h>

RF24 radio(7, 8); // CE, CSN

uint64_t address = 0xF0F0F0F0E1LL;

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

  radio.begin();
  radio.openWritingPipe(address);
  radio.setPALevel(RF24_PA_MIN);
  radio.stopListening();
  radio.printDetails();

}

void loop() {

  if(Serial.available() > 0) {

    char byteLido = Serial.read();

    radio.write(&byteLido, sizeof(byteLido));
    delay(1000);
  }
}

Did you stty /dev/ttyACM0 to the correct baud rate?

hmm.. i dont know how to do it on C code

could you give me some tip on how to do it?

First try from the command line, just to make sure this is the actual issue.

Sorry, but how can I do it from command line?

stty -F /dev/ttyACM0 raw -echo 9600

shows nothing on terminal but the TX led turned on for a while

Working with serial in C on Linux is not as simple as opening a file and reading from it (though in some circumstances that can work).
You should open the file using open() not fopen(), then use tcgetattr() and tcsetattr() etc to configure the port.
For example:
#include <stdio.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
#include <stdlib.h>

struct termios oldsettings, newsettings;
int fd;

// This signal handler will close the port cleanly leaving
// it in the same state it started in
void sighandler(int sig) {
    if (sig == SIGINT) {
        if (fd >= 0) {
            // Restore the settings to original
            tcsetattr(fd, TCSANOW, &oldsettings);

            // Close the port
            close(fd);

            printf("Program teminated. Thank you for playing.\n");
            // Exit the program
            exit(0);
        }
    }
}

int main(int argc, char *argv) {

    // Trap CTRL-C to close the port properly
    signal(SIGINT, &sighandler);

    fd = open("/dev/ttyACM0", O_RDWR);
    if (fd < 0) {
        fprintf(stderr, "Error opening serial port: %s\n", strerror(errno));
        return 10;
    }

    // Save the settings
    tcgetattr(fd, &oldsettings);
    // Grab the current settings again to modify
    tcgetattr(fd, &newsettings);

    // Set the baud rate
    cfsetispeed(&newsettings, B9600);
    cfsetospeed(&newsettings, B9600);

    // Make it a raw port
    cfmakeraw(&newsettings);

    // Apply the settings
    tcsetattr(fd, TCSANOW, &newsettings);

    char c;
    printf("Press CTRL-C to terminate\n");

    while (read(fd, &c, 1) == 1) {
        printf("Got character 0x%02x\n", c);
    }

    fprintf(stderr, "Reception terminated: %s\n", strerror(errno));

    return 0;
}

No one ever said programming C was easy. It makes you appreciate just how much work the Arduino API does behind the scenes for you...
Also you need to be aware that the Arduino resets (if you use an Uno, Mega, or other board with a separate USB interface chip) when you open the serial port. You need to wait about 2 seconds after opening the port before you ever send anything, or whatever you send will be completely ignored.  You can do that with:
sleep(2);

after you have opened and configured the port.

Thank you so much!

source: Stack Exchange

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

sort: votes


text:
Serial communication between PC and Arduino using C
I'm trying to send some data to my arduino mega 2560 using serial communication.
I'm using the exemple that I found here without success.
Every site I read say that I can send data to the arduino board like writing to any file on ubuntu.
But I alway get Segmentation fault
Here is my code
#include <stdio.h>
#include <string.h>

char arduinoPort[] = "/dev/ttyACM0";

int main() {

  char buffer[] = {'1'};

  FILE *usb_port;

  usb_port = fopen(arduinoPort, "rwb");

  fwrite(buffer, sizeof(char), sizeof(buffer), usb_port);

  fclose(usb_port);

  return 0;
}

why are you not using the arduino IDE?

@jsotola, because they write for PC

Your program works flawlessly on my Ubuntu 18.04. I would guess that you
have a problem with your setup (flaky USB port, permission problems...)
rather than the program itself. Still, I would recommend you add some
error checking: right after the fopen() call,
if (!usb_port) {
    perror(arduinoPort);
    return 1;
}

I would expect you see something like
/dev/ttyACM0: No such file or directory

or
/dev/ttyACM0: Permission denied

that could help you pin down the real problem.

Thank you so much. It wasn't working because i opened the serial monitor and because the message i could see it. When serial monitor is opened the serial is busy.

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


text:
Bypass a function error
I have a long code written in Arduino101 that works fine. I use a prepared function (connected to a library) in my code that I have not written it. My input to this function is an array. In 99.9999..% of the time, the function works great. However, it might stops due to an unknown reason, maybe because of my wrong input. This causes the program to stop.
My question is: how to bypass this function if it fails for any reason? Something like 'on error' function in normal programming.
Thanks a lot in advance,

If it is because of your input being bad, then you need to check and validate that input.

Please add more info to your question, mention that this is a follow-up of: https://arduino.stackexchange.com/questions/61867/problem-with-variables

Thanks, friends. I will focus on my code to find the root cause.

If your function is crashing then there is no way to recover. Arduinos are unprotected real mode devices. If your code does something invalid, your program crashes and the device will likely either hang or restart.
You need to debug your function, or find the invalid data you are passing into it.

Thanks for your comment, Duncan. I will do so.


text:
How can I read a piezo sensor and have it output a fixed voltage?
I'm trying to creature an instrument out of a few boards I have. The plan is to have piezo sensors wait for a hit, then be read by a digital pin, then execute code based on what piezo sensor was hit.
I know how to make a note play, but I don't know how to read a signal from a piezo that's between 3V and 5V. I'm not worried about velocity measurements, I just want there to be a hit, register the hit through arduino, then relay the pin number to a track number.
I read that pin change interrupts can read a signal instantly.
Below is some example code for my audio output board that plays audio files. This specific bit of code is for "notes" on an instrument.
          wTrig.masterGain(-8);                 // Lower main volume
          wTrig.trackPlayPoly(6);               // Play first note
          delay(1000);
          wTrig.trackPlayPoly(7);               // Play second note
          delay(1000);
          wTrig.trackPlayPoly(8);               // Play third note
          delay(1000);
          wTrig.trackFade(6, -50, 5000, 1);     // Fade Track 6 to -50dB and stop
          wTrig.trackFade(7, -50, 5000, 1);     // Fade Track 7 to -50dB and stop
          wTrig.trackFade(8, -50, 5000, 1);     // Fade Track 8 to -50dB and stop

I don't have experience with code, but this is how I think activating a note would work:
wTrig.trackPlayPoly(pin number)
delay(100);
wTrig.trackFade(pin number, -50, 5000, 1);

As far as limiting voltage, don't I just need to put some resistors in circuit with the piezo sensors?
In psuedo-code, this is what I want to make happen:
Listen for signal from any pin
Store that pin number as a variable
wTrig.trackPlayPoly(pin number)
delay(100);
wTrig.trackFade(pin number, -50, 5000, 1);

If the piezo is mounted to a surface, and you're hitting the surface to create vibrations, it is complicated as mentioned in the other answer, and it would be a good idea to connect piezo brass to a stable 2.5V and use rail clamping diodes on the pin.  For this purpose, you may be okay with just a couple 100 ohm resistors as a divider and a capacitor between ground and the 2.5V.  The proper audio way is more involved.
But if you're tapping the piezo directly with your finger, or tapping a thin plate and foam on top of the piezo, it's a lot simpler.  I've done this with a 100k ohm resistor in parallel (better response and consistency than 1 M ohm) and 5V zener diode in parallel for a 5V processor.  An analog pin with AnalogRead function can determine the voltage.  Brass wired to ground, center area wired to pin.  I've found that placing thin foam underneath everything gets rid of the crosstalk, especially if you don't need velocity sensitivity.
I would avoid using the delay function because it will prevent other piezos from working during that time.  Millis() calculations allow other actions to be performed.

Perhaps you could use the schema editor to enhance the answer?

Perhaps.  I searched for this schema editor (here and Google) and did not find it.

A piezo will output a decaying sinusoid when you feed it an impulse (a hit on the attached surface). Problem with a high frequency sinusoid is that one: half the time it's negative, and two: it forces a near-real-time monitoring of the analog voltage there, ie no or small delays in your code.
I've made a pattern recognition 'drum' with piezos, and the general approach was to first start with plotting the analog voltage of the piezo. This is done by putting the positive of the piezo to an analog pin and the negative to ground, and a 1M resistor between the leads (this value worked for me, play with different values to see what works best). Then do a serial plot (ctrl shift L in the IDE) and observe:

how high the peak is for different distances and strengths of 'knocks'
how many times a significant peak occurs before decaying.

Your end goal is to have the Arduino recognize a peak by seeing when the analog reading is above a threshold value , then have a dead period where it ignores subsequent peaks (so it doesn't read multiple events on a single sinusoid), and then play your note. Longer dead period means less false-positives, shorter means more responsive.
I apologize for the long-windedness of my somewhat ambiguous response, I'll try to remember to paste my code when I'm at my computer tomorrow.

I actually found a tutorial on how to plot a serial plot of a piezo before, but that's as far as I've gotten. I understand what you're saying.

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


text:
Evaluating delay for Xbee
I will explain my task in a simplified way. I'm communicating among 3 Xbee's.
The attached code is for the sender Xbee. This Xbee actually sends multiple values of value1 (here for simplification I assigned it to constant value 10). For finding the value1 it does some other calculations as well and then assigns it.
But I find that if I reduce or remove the delay(100) I end up receiving improper values. I guess delay gives a buffer time for data transmission but my question is how to do I calculate the minimum delay or how can justify that this is the delay needed ?
I hope you can understand my question. If not please comment I will give some more pertinent details.
  // Sender Xbee
    void setup()
    {
    Serial.begin(9600);
    }
    void loop()
    {
    int value1 = 10; // some hardcoded values to send
    Serial.print('H'); // unique header to identify start of message
    Serial.print(value1,DEC);
    Serial.print(","); // note that a comma is sent after the last field
    Serial.print('\n'); // send a cr/lf
    delay(100);
    }

If timing is critical (and assuming you do not want to loose any message), you probably need some notification back that the message has been received correctly (possibly with a checksum value).

Based on my experience with Xbee, I would say the limit is 50ms as Xbee can do the lowest sampling rate of 50ms.

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


text:
Arduino IDE - Maximum serial COM ports
What is the maximum number of serial ports (com) can Arduino IDE detect ?
I need to connect 6 Arduino UNO Wi-fi at a time to make a small network and I use a 7 port USB hub for the same. The device manager shows 6 com ports detected but Arduino shows only 4 serial ports detected. Is there a limitation on the serial ports interfaced with the Arduino IDE ?

You could run 6 copies of the IDE to allow a Serial Monitor per board.

I've never had any success connecting the IDE to multiple boards, it seems to use a global for the Serial Port and so all instances program the same board.  It might have changed with the latest IDE, I haven't tried for a few months.

Thanks for your comments. I found the solution.
Inside the My computer -> Properties -> Device manager under ports I found that multiple Arduino's where assigned same COM values.
Therefore, just go to properties of the COM and change them to COM values that are not used.

Thanks for your comments. I found the solution. Inside the My computer -> Properties -> Device manager under ports I found that multiple Arduino's where assigned same COM values. Therefore, just go to properties of the COM and change them to COM values that are not used

Cool! Indeed, a valid solution was to try another OS ;)

According to the last version of code for Arduino IDE, there are no limits of discovered Serial or Network devices since they are stored in a list (not limited as an array).
To discard problems, try with another operating system.

Thanks a lot for your reply. From my findings, if I'm not wrong the maximum detectable serial port for Windows 7 is 255.


text:
SN74HC595 Shift Register Issue
I'm trying to use the popular SN74HC595 Shift Register, but I think something isn't right because when the bits are submitted to the register it comes out with something similar but not the same.
#define Latch 9
#define CLK 10
#define DATA 8

byte led = B10110111;

void setup()
{
  pinMode(Latch, OUTPUT);
  pinMode(CLK, OUTPUT);
  pinMode(DATA, OUTPUT);

  digitalWrite(Latch, LOW);
  shiftOut(DATA, CLK, MSBFIRST, led);
  digitalWrite(Latch, HIGH);
}

void loop()
{
  //LOOP
}

After this completes I receive an output of 10110101 instead of 10110111. Has anybody had the same area? Any fixes? Could my chip be faulty inside?
Schematic:

is a specific bit failing?

I guess you have just forgotten to draw the gnd and 5V lines to the breadboard?

Lack of decoupling capacitors?

@jsotola It can be any bit that fails but usually within the last 3

@Wirewrap Yes I forgot to draw the GND, and 5V to the breadboard, but they are connected

I so not know if this helps, but I had a similar "random data" problem with my shift register. It turned out that there wasn't a tight connection between one of the data in/enable pins and VCC. So I made sure all my jumpers were firm in the breadboard (bent the pins just a tiny bit) and tried another breadboard.

I'm with Magenko, you need  a 0.1uF cap from the shift register's Vcc pin to the nearest Gnd.  I've strung up 9, 18, 27, 36, 45 shift registers and clocked in data a 8 MHz use SPI and not had issues. Check your connections and add a cap.  Make sure the clear pin is pulled high and the output enable pin is pullled low.


text:
NodeMCU V3 - Troubleshooting basic TMP36 circuit
If I follow this example using my Arduino Uno https://learn.adafruit.com/tmp36-temperature-sensor/using-a-temp-sensor
(using the 3.3V code example at the bottom of the page), I get reasonable temperatures from the readings over serial.
However, if I try this w/ a LoLin NodeMCU V3 (same circuit layout), my readings seem to be consistently higher than what I get running essentially the same code on the Uno. (Only difference in code is omission of analogReference(EXTERNAL), as the Node V3 appears to run on 3.3V as standard )
I'm fairly new to the whole electronics thing, so any pointers are much appreciated...
Circuit is:
      ----- |---------------- GND on breadboard with jumper to MCU
     | TMP36|---------------- AD0 pin on MCU
      ----- |---------------- breadboard power w/ 3.3V jumper to MCU

if you have two sensors, try reading them one each on the uno and node v3 placed side by side. see if the readings are actually different. then swap the sensors around and recheck if it still consistent. also it might sound silly, but could the ambient temperature have actually changed between the two runs ?

also this might be relevant... https://arduino.stackexchange.com/a/54906/16898.

the link is not relevant. the NodeMcu has a voltage divider to read to 3.3 V on A0


text:
How can I fix my HRLV-MaxSonar-EZ ultrasonic sensor so it does not give gibberish feedback?
I have hooked up my ultrasonic sensor to my Arduino correctly, I know this because I am getting feedback from it, but when I run this code:
int mode = 2;
double distance;
double calibration;
void setup()
{
  Serial.begin(9600);
  pinMode(12, INPUT);
}
void loop()
{
  if(mode == 1)
  {
  //Read duration in microSeconds
  long duration = pulseIn(12, HIGH);
  //58 uS per cm for MB1240 XL-MaxSonar
  //Operation Range: 20 cm min (50 cm for accurate)
  distance = duration / 58.0;
  calibration = -20;
  }
  else if (mode == 2)
  {
  //Analog In .49 mV per unit
  double voltage = analogRead(5)*.0049;
 //.49 mV per cm;
  distance = voltage/.0049;
  calibration = 0.0;
  }
  double cmToInch = 0.393701;
  //Analog Seems to be More Accurate due to PWM timing
  Serial.print((distance+calibration)*cmToInch);
  Serial.println(" in");
  delay(100);
}
I get sporadic results when it is just sitting there without anything moving in front of, let alone around it at all:

What is wrong here? Is it my code, is the sensor just very sensitive, or is it something else?
Thanks in advance.

so, what is at 148 or so inches from the sensor?

That's exactly it, nothing is.

so absolutely nothing for 12 feet, not even a wall?

Nope, and it changes without anything around it moving; it was in the middle of an empty room. Also, it doesn't change much when I move my hand in front of it.

voltage = analogRead(5)*.0049; distance = voltage/.0049 is just a long winded way of doing distance = analogRead(5) - I think your logic is messed up


text:
Arduino should check the same way like a USB keyboard or a USB mouse, if turned on notebook is connected
I have a USB HUB and have connected to it a USB keyboard and a USB mouse. As long I have not connected a Notebook to it those devices don't turn on. 5V is always turned on! So I could charge my phone. How do they know there is no notebook connected? My Arduino is always on. I want to emulate this with an Arduino. Without the need of extra software on a notebook, the Arduino should be able to tell if a notebook is connected to the USB Hub or not. Please help.

On the Nano, the FT232RL chip does the USB communication. This chip has a PWREN option. When you configure the chip for this, the selected pin will be HIGH if there is no USB host. You could carefully solder a wire from the selected pin (CBUS0-4) to one of the Arduino pins, so the ATMega328 can read it out.

just monitor the current of the hub, it will increase a lot if everything turns on.

I want to understand how a cheap USB mouse is doing it, and do the same thing with an arduino.

those devices don't turn on .... how do you know? .... you have no way to test that

Sure! The usb mouse does not light up (the red laser beneath) and on the keyboard you can not get any lights to light up (for example the numpad light)

With Arduino Nano, you don't have control over the USB, because it is handled by the USB-to-TTL-Serial chip on the board. The MCU is to this adapter connected only with RX and TX of the Serial interface.
With Arduino Micro you could retrieve the state of the USB connection, because he MCU ATmega32u4 has a build in USB support an handles the USB connection from application (sketch).

So the digispark would work, too?

ATtiny doesn't have native USB but Digispark has circuit for V-USB (software USB)

@Alexander_Projects, did the answer help?


text:
How to execute operation once till a condition then restart it from start
I am making a project using IR sensor,servomotor and Push button.
I am not able write code for the logic as stated:
it will execute the operation when it reads the digital value of IR high and rotates the servomotor till a threshold and then rotates the servo reverse  on using push button.It will perform no actions till the push button is used altough IR sensor is reading value.Then it will again perform the same action after push button is used.

I am not able write code for the logic - so, you want someone to do it for you for free? Sounds fair

logic as stated .... you have not clearly stated the desired behavior

My suggestion is, even if it seems to be a simple example, to start with an analysis of what you really want to achieve. In this example I would try to start with an state diagramm. With this you could clarify simple questions, e.g. what happens if the IR goes low while the motor is turning. In my draft, the motor would keep running, but maybe the IR is for safety reason and you want to stop motor if something approaches. If that is your intention, you can easy add aditional transitions at all states to return to state 00.
Such an approach helps you in creating code easy to maintain and change to new requirements

After having your state diagramm finished it is often easy to start programming with switch/case sturctures for first learning experiences.
Switch(state) {
  case 00:
  // if IR set state = 10;
  break;
  case 10:
  // if button was pressed set state = 11
  break;
  case 11:
  // turn motor
  // if treshold set state = 12
  break;
.
.
.

}


text:
L293D with arduino's 5V
I am trying to use L293D with relay to power a 12V DC motor. Can I use arduino's 5V to provide L293D inputs 4 and 8 such as in the drawing? Or do I need to use a separate source, e.g. a power module?

I have to ask... why the relay...?!

@Majenko I am following the guide https://www.elegoo.com/tutorial/Elegoo%20Super%20Starter%20Kit%20for%20UNO%20V1.0.2019.03.04.zip page 150. Say I wanted to power some other device, with AC current, I would need a relay anyway.

That "guide" seems completely pointless. Nothing more than a demonstration of what a relay is. Throw that whole thing away. You don't want to use a relay to control a DC motor, especially when you already have a motor driver chip, and the previous "guide" shows you how to use it. Why they included that relay thing in there is anyone's guess. Yes, if you wanted to control something AC, or very high voltage, then a relay would be used. You wouldn't use a motor driver to control it though - you'd just use a simple transistor.

it looks like that motor controller chip has separate logic level and motor power inputs.
VCC1, at pin 16, is a low current logic level power input. You should be able to drive that from the Arduino's power supply.
VCC2, at pin 8 is the motor power input. You should NOT drive that from your Arduino's power supply. You should have a separate power supply for that (+5V with enough current for all the motors you are powering - 600mA is the max that chip can drive for a single motor, so a 1A power supply for VCC2 would be fine.
It looks like you are feeding the Arduino's +5V line into VCC2. DON'T DO THAT.


text:
Arduino Zero to Arduino Zero SPI configuration
I am in the planning stage of chaning two ATSAMD21 with a Zero or Nano 33 bootloade r in a SPI connection. The rational for this is that i am in need of 30 pin GPIO expansion and using 2 mcp23s17 takes a fair bit amount of space and also slightly bit more expensive. Since the ATSAMD21 has theoretical 37 GPIOs why not use that. having not owned a zero board yet, i would like to know if:
Is it easily doable, just connecting the appropriate pins?
If so, i have read in the Arduino SPI documentation that the zero doesnt have any Slave Select for Master and Slave, does this mean i can use whatever i want? And just code it to detect that pin
Does the built in SPI library capable of handling the slightly higher clock speed of the zero ?

A zero has the same number of IO pins then a UNO, they use the same header layout. So I believe you want to use the chips on a self made PCB. (?)
Based on this, I think a second SAMD21 is not the best solution.
They are easily connectable as they use the same Voltage. I used the SPI lib on a zero, so yes, I think its programmable with Arduino techniques. And you can use a CS pin of your choice. The SPI lib uses Arduino header files for the selected platform. So the MCU clock speed shouldn't be a problem.
But you have to program the master and the slave and maintain this firmware. An MCP23(s/0)17 is ready to use.
Two MCP23S17 (QFN packages) don't take that much space.
SAMD21 is capable of driving max. 3.6 V; MCP can handle 5.5 V. (But if you want to use 5V you have to level shift the connection between your Arduino zero and the MCP.
And adding two more MCP23S17 is way easier that adding a third SAMD21, when even the old firmware must be reprogrammed.
A MCP23S17 can drive and sink 25 mA on each pin.
A SAMD21 can handle 14 mA source current and 19.5 mA sink current per IO cluster (there are 6 clusters each of them has between 2 and 16 pins).
On the other hand, if you are sure, you don't need more than 3.6 volts and ~1 mA per pin and the number of the additional IO pins is enough, there is no reason not to use a second SAMD21.
If you need capacitive  touch pins, or more I2S ports or other capabilities of the SAMD21, then the second SAMD21 is even the better choice.
Have you seen the Arduino DUE? It has all the features of a zero and way more IO pins (54) and 12 analog inputs and 2 real analog outputs.

Correct i will use it on a custom PCB. I am still in the planning phase and evaluating my options, I really like your arduino DUE suggestion this will make things a lot mor easier, It even has a faster clock speed ! Will check the chip its using, and how complicated is its minimal components

If you have experience using the DUE. do you know what is the purpose of the ATMEGA16U2 microcontroller? and can it be removed?

The DUE has two USB ports. The native port is directly added to the SAMD Controller and the programming port is connected to the U2 chip. The U2 chip is responsible for the programming over the serial port and also for ICSP programming over the ICSP1 header. It is also possible to program the DUE over the native port. The SAMD of a DUE can only be programmed if the FLASH has been erased before. And the boot loader on the U2 chip does this for you automatically. If you use the native port it's up to you to erase the Flash memory.

Hello i made some progress since my last reply and would like to talk about it more in chat

unfortunately im having a difficult time creating one, I will just replying here until the pop up  pops up.
About that erasing the flash memory on the arduino due's documentation you have to open and close serial at 1200bps, how can this be simply achieved in hardware?


text:
Reading multiple pins via registers on the Arduino Due
I would like to read multiple pins at once in Arduino Due via registers just like PINB, PINC, PIND of the arduino uno. I know that the pins will be scattered to multiple registers, but i deduce it would still be faster this way since there for sure there will be multiple pins on a single register rather than call digitalRead 40 times.
Arduino shared the documentation for what digital/analog pins corressponds to the what ports to the actual sam chip, i just need that snippet of code that reads via registers.
So if any can give me the equivalents to these, It would be greatly appreciated:

DDRx - The Port C Data Direction Register - read/write
PORTx - The Port C Data Register - read/write
PINx - The Port C Input Pins Register - read only

i just wrote x because there are three of those e.g. DDRB,DDRC,DDRD. basing from that there should be port A but i guess they dont use those

You will find a good introduction on using port registers here. It also mentions some cons and pros of using port manipulation.

that documentation only applies to arduino boards using ATmega8 and ATmega168 chips, It does not apply to the due which uses a  SAM3x ARM chip

You are right. I didn't read your headline carefully enough. But apparently this question has been asked (and answered before): https://arduino.stackexchange.com/questions/9117/sam3x8e-arduino-due-pin-io-registers

Wow I did not see that, it will be useful to me in future projects. Unfortunatly they are only talking about writing to the pins and not reading the pins. I could not find a mention on reading pins. Although I may have found a hint from a answer of this question, I will have to start from there i guess


text:
What is the fastest way to data to another Arduino SAMD21 boards
Hello I would be needing to transmit data from one arduino to another as fast as possible? how do I achieve this?
Since my application need a lot of pins (its a compact system so mega and due are not suitable) i am going to use 2 arduino nano 33 IOT (basically a SAMD21 uC) and one of them is just going to read from the sensors convert it to binary ( around 32-40 bits long) and send it to the other arduino.
So parameters are:

must be sent via wires
maximum number of pines used is 6
must be able to repeatedly send data ( like this is the only job the arduino does read from sensors and send it to the other one, repeatedly and endlessly)
must be reliable enough

Thank you Very much !

SPI is probably the fastest.

@Majenko Does SPI communication affect/interrupts PWM ?  because  I need to use PWM  on the "master" arduino, and the PWM must not be intterrupted

No, PWM is (unless the board is crap and uses software PWM) hardware driven and runs in the background.

what do you mean by "the board is crap"? i mean replica to the arduino boards are using the same chip and schematics as arduino right? they have the schematics on their site

I mean I am not familiar with the samd21 and how it is used for Arduino.

can't you use port expanders or multiplexers with one MCU? btw. Nano 33 IoT has two MCU connected by SPI. a SAMD21 and a ESP32

@juraj It is a custom Nano 33 , so i only have the SAMD21 left, and removed the Nina. Port expanders first time i have hear of those. Do you want to post that as an answer? Because i think it solves my problem and as a bonus making my circuit less complex

then it is a MKR Zero and not Nano 33 IoT like board

You are right, but i am following the nano 33's schematics just without the nina. I am not really sure if its the same as the zero. for example i dont have a bms.

So when looking for port expanders what should i look out for? (exempt for the number of pins)


text:
Is analogWrite() not affected by blocking codes and/or Interrupts?
Well just as the question say, is the analogWrite() function will continue generating near-consistent PWM when it encounters blocking codes or signal interrupts?
Is it the same case for both the classic arduinos(atmega chips) and the new arduinos(SAMD21 chips).
If analogWrite() does get affected by blocking codes, is there a way to create a uninterruptible PWM signal?

is the analogWrite() function
  continue generating near-consistent PWM when it encounters blocking
  codes or signal interrupts?

Yes for 'hardware' PWM used by analogWrite on AVR and SAMD Arduinos. The hardware PWM is handled by wave output of Timers, which are MCU peripherals running independently from CPU and other MCU peripherals.

Is it the same case for both the classic arduinos(atmega chips) and
  the new arduinos(SAMD21 chips).

yes

If analogWrite() does get affected by blocking codes, is there a way
  to create a uninterruptible PWM signal?

N/A


text:
Is it possible to use the Arduino Due's specials pins for digital writing and reading?
Hello the arduino documentation on the due specifies the pin mapping of the pins.I am making a custom board using the dues schematics and i am running still a bit low on pins. Also some of the special pins offer a better position for traces.
So is it possible digitalWrite()/digitalRead() the specials pins such as:

RX (0-3)
TX (0-3)
SDA (0-1)
SCL (0-1)
CANRX
CANTX
LED RX
LED TX
MISO
MOSI
SCLK

As for the SPI and i2c lines i will be using them for the original purpose,but i would like to take the opportunity to know anyway.
I do not own a due so unfortunately i can not test it

Yes, although you may need to modify the variant files to allow access to them.
Every function on the SAM3X8E is a "multiplexed" function. That is, it shares pins with other functions.  For example CANTX0 is an alternative function on pin PA0.
You can find all the alternative function mappings on page 40 of the datasheet.
You may find that many of these pins already have an Arduino pin number assigned to them in the variant file. If that is the case then you can just use it as you would any digital IO pin.
I have included the comments from the variant files here for quick reference:
/*
 * DUE Board pin   |  PORT  | Label
 * ----------------+--------+-------
 *   0             |  PA8   | "RX0"
 *   1             |  PA9   | "TX0"
 *   2       TIOA0 |  PB25  |
 *   3       TIOA7 |  PC28  |
 *   4       NPCS1 |  PA29  |
 *           TIOB6 |  PC26  |
 *   5       TIOA6 |  PC25  |
 *   6       PWML7 |  PC24  |
 *   7       PWML6 |  PC23  |
 *   8       PWML5 |  PC22  |
 *   9       PWML4 |  PC21  |
 *  10       NPCS0 |  PA28  |
 *           TIOB7 |  PC29  |
 *  11       TIOA8 |  PD7   |
 *  12       TIOB8 |  PD8   |
 *  13       TIOB0 |  PB27  | LED AMBER "L"
 *  14       TXD3  |  PD4   | "TX3"
 *  15       RXD3  |  PD5   | "RX3"
 *  16       TXD1  |  PA13  | "TX2"
 *  17       RXD1  |  PA12  | "RX2"
 *  18       TXD0  |  PA11  | "TX1"
 *  19       RXD0  |  PA10  | "RX1"
 *  20             |  PB12  | "SDA"
 *  21             |  PB13  | "SCL"
 *  22             |  PB26  |
 *  23             |  PA14  |
 *  24             |  PA15  |
 *  25             |  PD0   |
 *  26             |  PD1   |
 *  27             |  PD2   |
 *  28             |  PD3   |
 *  29             |  PD6   |
 *  30             |  PD9   |
 *  31             |  PA7   |
 *  32             |  PD10  |
 *  33             |  PC1   |
 *  34             |  PC2   |
 *  35             |  PC3   |
 *  36             |  PC4   |
 *  37             |  PC5   |
 *  38             |  PC6   |
 *  39             |  PC7   |
 *  40             |  PC8   |
 *  41             |  PC9   |
 *  42             |  PA19  |
 *  43             |  PA20  |
 *  44             |  PC19  |
 *  45             |  PC18  |
 *  46             |  PC17  |
 *  47             |  PC16  |
 *  48             |  PC15  |
 *  49             |  PC14  |
 *  50             |  PC13  |
 *  51             |  PC12  |
 *  52       NPCS2 |  PB21  |
 *  53             |  PB14  |
 *  54             |  PA16  | "A0"
 *  55             |  PA24  | "A1"
 *  56             |  PA23  | "A2"
 *  57             |  PA22  | "A3"
 *  58       TIOB2 |  PA6   | "A4"
 *  69             |  PA4   | "A5"
 *  60       TIOB1 |  PA3   | "A6"
 *  61       TIOA1 |  PA2   | "A7"
 *  62             |  PB17  | "A8"
 *  63             |  PB18  | "A9"
 *  64             |  PB19  | "A10"
 *  65             |  PB20  | "A11"
 *  66             |  PB15  | "DAC0"
 *  67             |  PB16  | "DAC1"
 *  68             |  PA1   | "CANRX"
 *  69             |  PA0   | "CANTX"
 *  70             |  PA17  | "SDA1"
 *  71             |  PA18  | "SCL1"
 *  72             |  PC30  | LED AMBER "RX"
 *  73             |  PA21  | LED AMBER "TX"
 *  74       MISO  |  PA25  |
 *  75       MOSI  |  PA26  |
 *  76       SCLK  |  PA27  |
 *  77       NPCS0 |  PA28  |
 *  78       NPCS3 |  PB23  | unconnected!

Well PA0 is kinda okay since it does not share with other pins. Digital 10 and 4 are have shared pins(PA29), how does that work ? if write high to D10 and LOW to D4, how will that work ? wont both of them short out?

Also if i access the pins via register manipulation do i still need to modify the variant files? They do have an arduino number (69 for CANTX) so i was thinking it should theoretically work, just needing confirmation

D10 is PA28 isn't it?  If there is a number assigned in the variant files then you can just use that as you would for any other digital pin. If you use port manipulation then the variant files don't come into play at all.

If you look at the link in the question thats from the official arduino page, pin 4  connected to both PA29 and PC26  and  pin 10 connected to both PA28 and PC29 .

I would like to take your comment as an asnwer good sir. especially this line If there is a number assigned in the variant files then you can just use that as you would for any other digital pin if you may include it in the answer. Also a link to the variant file for the lazy people that might read this thread

@Jack Done and done

Thank you very much!

@Jack, here is how you can make your own board variant referring the official SAM boards package https://arduino.stackexchange.com/questions/54484/adding-a-custom-board-to-the-arduino-ide/60660#60660

As far as I know you can use them as GPIO too (I know for sure for Arduino Uno/Mega etc., I know for STM32, I would be very surprised if it's not possible for Arduino Due.
Other solutions are using shift registers like:

74HC595: For adding upto 32 outputs using SPI
74HC565: For adding upto 32 inputs using SPI

Or you can use GPIO extenders using either SPI or I2C.

Yes my worst case scenario is using a GPIO extender MCP23S17

I can imagine, the shift registers are easier (enough documentation available for the Arduino Uno/Mega, probably will work on Due as well). Why don't you try to write to a pin directly, or you don't have a Due at hand?

I dont have a due at hand unfortunately, there are no store that i could find that sells them, there are online stores buy they charge a pricey 30$ for shipping.

You can try aliexpress but than you have to wait very long.


text:
Is the arduino nano 33 IOT schematic wrong?
As am i was copying the schematics of the arduino nano 33 IOT from the Official arduino schematic i noticed something was wrong in the schematic, specifically in the PRTV5V component
Here is a snip on the schematic

It would seems that the pin numbering on the PRTR5V is wrong. Here are snippits from the PRTR5V Datasheet

The sample schematic does look like the same of the arduino but if you look at it using the pin number it is different.For example on the arduino schematic pin 2 is at the middle of the two diodes, while on the datasheed pin 2 is before the diodes.
Now which one should i follow? Did arduino intentionally pin it that way ?

It is correct. You are looking at the wrong datasheet.
This is the correct one:

https://assets.nexperia.com/documents/data-sheet/PRTR5V0U2X.pdf

Thank you good sir ! you just saved me from buying the wrong part :)


text:
Convert serial value into hex using in Genuino zero
hello there my code is here.
/* Simple Serial ECHO script : Written by ScottC 03/07/2012 */

/* Use a variable called byteRead to temporarily store
   the data coming from the computer */
byte byteRead;

void setup() {
// Turn the Serial Protocol ON
  Serial.begin(9600);
}

void loop() {
   char a[8];
    int b;
   /*  check if data has been sent from the computer: */
  if (Serial.available())
  {
    /* read the most recent byte */
    byteRead = Serial.read();
    Serial.print(byteRead,HEX);
  }

now when i send '12' from terminal, it prints 3132. means it is ASCII value. but i want to print 12. can you help me?? how to do it??

You need to convert the ASCII characters to a number.

how?? can i use atoi ??

how about strtol? is allows a base.

i use it this way. but i am getting compiler error.....

ret = strtol(byteRead, &ptr, 10);

i tried atoi(byteRead). but it is also giving me compiler error

No no no. Read the whole string into a buffer (a[8]), null terminate and pass to the functions. You cannot use byteRead that is a single byte!

i tried that way too. but its not giving me any value

void loop()
{
if (Serial.available())
{
char* readString;
for(int i=0; i<4; i++)
{
readString[i]=Serial.read();
}
int a = atoi(readString);
Serial.println(a);
}
}

There are several issues with your sketch. The most important is the lack of understanding for the difference between internal and external representation.
The sketch reads a single character from Serial and prints the value as a hexadecimal number. The character is ASCII; a number that represents symbols in our alphabet.
Your goal is to read characters into a string and then convert the string to a number assuming that the string represents a hexadecimal number ('0'..'9' and 'a'..'f' or 'A'..'F').
The sketch should be 1) scan string, 2) parse and convert string to number, 3) print the number.
Scanning the string requires skipping whitespace and then collecting characters until a whitespace.
The sketch could look something like this:
void setup() {
  Serial.begin(57600);
  while (!Serial);
  Serial.println(F("Serial started..."));
}

void loop() {
  const size_t BUF_MAX = 16;
  char buf[BUF_MAX];
  char* bp = buf;
  char c;

  // Skip whitespace
  do {
    while (!Serial.available());
    c = Serial.read();
  } while (c <= ' ');

  // Scan token until whitespace
  *bp = c;
  do {
    while (!Serial.available());
    c = Serial.read();
    *++bp = c;
  } while (c > ' ');
  *bp = 0;

  // Print scanned token
  Serial.println(buf);

  // Convert to number and print
  const int BASE = 16;
  long val = strtol(buf, &bp, BASE);
  if (*bp == 0)
    Serial.println(val);
  else
    Serial.println(F("not a number"));
}

This allows scan of hexadecimal numbers with possible sign (as defined by strtol). By changing the BASE to zero strtol will use the notations for base definitions (prefix '0' for octal, '0x' for hexadecimal). Last, please observe the parse error handling provided by strtol(*bp != 0).
Cheers!

To convert Decimal or Integer value to Hexadecimal you can go this way..
byteRead = Serial.read();  //Read your value
myValue =  String(byteRead, HEX); //Convert it into Hexadecimal
Serial.println(myValue); //Print in serial Monitor
myValue1 = String(byteRead,DEC); //Convert it ino Decimal
Serial.println(myValue1); //Print in serial Monitor

Comments are not for extended discussion; this conversation has been moved to chat.


text:
How can I send integer from arduino to another arduino by FS1000A / XY-MK-5V 433Mhz TX/RX Module (WIFI)?
I'm trying to send and receive some data from arduino to another arduino and I'm using arduino UNO and FS1000A / XY-MK-5V 433Mhz TX/RX Modules.
For transmitting I use the library VirtualWire and It works very well for this code:
#include <VirtualWire.h>
void setup()
{
// Initialize the IO and ISR
vw_setup(2000); // Bits per sec
}
void loop()
{
  char msg[7] = {'h','e','l','l','o',' ','!'};
  vw_send((uint8_t *)msg, 7);
  vw_wait_tx(); // Wait until the whole message is gone
  delay(1000);
}

I was wondering if I want to send some string or int data how I can do that.
I tried to use it for string data but I couldn't because the Input of function vw_send(...) is char and I couldn't use int or string.
finally I run this code:
#include <VirtualWire.h>
void setup()
{
// Initialize the IO and ISR
vw_setup(2000); // Bits per sec
}
void loop()
{
  char msg[11]="Hello there";
  vw_send((uint8_t *)msg, 11);
  vw_wait_tx(); // Wait until the whole message is gone
delay(1000);
}

and I could send Hello there !, but I'm looking for the correct way for sending string and int.

Have a look at the Easy Transfer library.  I haven't used the particular modules you have, however I did successfully use the EasyTransfer library with Ciseco wireless modules.  In essence the EasyTransfer library transmits the data as a structure with the same format on each module.  The structure can contain any data type.

Would you please give me the link of this library?

How can I choose the library? there is a lot of library about one subject!

Hi, just Google Arduino EasyTransfer library that will provide links to the actual library and other various questions / comments / answers.  There is only one EasyTransfer library.  Study the available on line information and I am certain you will achieve your objectives.


text:
missing some data after data is sent by FS1000A / XY-MK-5V 433Mhz TX/RX Module (WIFI)
I miss some data ( mostly, the latest characters of one data) when I want to send several messages from arduino to another arduino.
I'm trying to send and receive some data from arduino to another arduino and I'm using arduino UNO and FS1000A / XY-MK-5V 433Mhz TX/RX Modules. If I only want to sent Hello there It works very well but if I want to send several things I miss something. for example for this code, it works very well :
Transmitter:
#include <VirtualWire.h>
void setup()
{
// Initialize the IO and ISR
vw_setup(2000); // Bits per sec
}
void loop()
{
  char msg[11]="Hello there";
  vw_send((uint8_t *)msg, 11);
  vw_wait_tx();
  delay(1000);
}

receiver:
#include <VirtualWire.h>
void setup()
{
// Initialize the IO and ISR
vw_setup(2000); // Bits per sec
}
void loop()
{
  char msg[11]="Hello there";
  vw_send((uint8_t *)msg, 11);
  vw_wait_tx(); // Wait until the whole message is gone
delay(1000);
}

the result is :
Device is ready
Received: Hello there
Received: Hello there
Received: Hello there
Received: Hello there
Received: Hello there
Received: Hello there
for this code I missed some data:
transmitter:
#include <VirtualWire.h>
void setup()
{
// Initialize the IO and ISR
vw_setup(2000); // Bits per sec
}
void loop()
{

char msg[11]="Hello there";
  vw_send((uint8_t *)msg, 11);
  vw_wait_tx();
  char msg2[7]="Goodbye";
  vw_send((uint8_t *)msg2, 7);
  vw_wait_tx();
delay(1000);
}

The result is :
Device is ready
Received: Hello there
Received: Goodbye
Received: Hello t
Received: Goodbye
Received: Hello t
Received: Goodbye
Received: Hello t
Received: Goodbye
Received: Hello t
Received: Goodbye
Received: Hello t
Received: Goodbye
Received: Hello t

Your array is too short. "Hello there" is char[12] because of the implicit null terminator. so you are corrupting your program. same applies for goodbye. also the receiver code is identical to the transmitter code.

Also,  the delay(1000) in the loop() of the receiver could cause the receiver to be in a wait state while the transmitter is sending something.

Thank you,I did both of these, but it doesn't work


text:
Arduino not running the sketch with external power supply of 9v, but runs the program when connected to pc
Can anyone please help me figure out/ point the reason of this arduino problem? I uploaded a simple arduino sketch (blink an LED ) just to test if my real program was the reason of the "abnormality" of this board. It works fine when I connected it to PC via arduino cable, but doesn't run the program when I use an external power supply(9v) and connected it to the Vin pin of arduino.
Need help and hoping for fast replies. I will be having a competition tomorrow, this is very urgent. please guys.
for the schematic diagram, there are no other parts inserted to the arduino board, aside from the 9v battery. I was able to say that the program work on "LED blink" by observing the lights of "TX" LED on the board. please help me. :(

1.) What Arduino do you use? Each Arduino can have different voltage regulator. 2.) Use another method to observe your Arduino. TX LED is blinking because of communication. It wont blink if there are no communication from Arduino. You can use LED_BUILTIN pin to observe it

https://www.youtube.com/watch?v=QyseW-sm6ig

that link for video is complete the same situation as mine. (that is not me on the video)
I used arduino uno. thanks :)

Try this, and tell if its blink or not when you used external power supply : https://www.arduino.cc/en/tutorial/blink

Thanks! It worked. LED blinks with 9V external power supply. hope that this would work with my program as well?

Hopefully yes, if there are no problem on electronics. Good luck on your competition!

Note that 9V batteries can't supply a lot of current.

TX LED is blinking because of communication (indicating data transmit via serial). It will not blink if there are no communication from Arduino through USB cable.
For simple observation, use LED_BUILTIN pin. Its a build in-LED indicator on Arduino.
pinMode(LED_BUILTIN, OUTPUT);

then
digitalWrite(LED_BUILTIN, HIGH);
delay(500)
digitalWrite(LED_BUILTIN, LOW);
delay(500)

Arduino fail on external power supply is usually because of voltage drop or your system draw too much current.

There is a possibility that you blew the regulator circuit with too much current while supplying your Vin pin with the 9V source. This would depend on your system power draw; something that you were using the board with before the blinker program - and also what kind of board you have.
To check this, try another similar board with the blinker program and the same 9V source. Don't forget to make the changes as suggested in the previous answer.
The other problem could be your power source: to check whether your power source supplies the desired volts, measure the power source terminal voltage while connected to the board. Most boards will have the minimum voltage requirement on Vin, depending on their regulator design.

A 9V battery can't supply enough current to blow up a regulator.

Would be interesting to know what facts you based that claim on. A 9v battery has enough juice to supply 0.5A for an hour so do the math. For the Uno's regulator 1A is enough, even if for a millisecond.

I think you are looking at the mAh rating, not the A. Duracell's 9V will drop to 5V after almost 2 hours at 250mA. You need at least 6-7V for the regulator.

Agreed, but the point is to damage the protection diode on the regulator you just need a transient high current.


text:
How to control multiple leds independently with arduino but they share a 12v external power source
I have a project with many components.  I'd like to use 12v adapter from wall.
I have a simplified experiment to apply to the actual project.  I can't find any info on the internet after days of searching.
I want to control each of 6 leds independently with an arduino. They all have different forward voltages.  But I would like them to be powered by the same 12v external power supply.  I suspect I would use transistors, Could someone point me in the right direction to wire these up?
I can figure out the code myself.

yes. use an N-channel MOSFET and ignore it when calculating resistors. google" mosfet as a swtich". The code you need is contained in the blink example.

Thanks.  That's simple!

The basic schematic for one LED is:

simulate this circuit – Schematic created using CircuitLab
Make sure that:

R1 is the right resistance for the supply voltage, forward voltage, and desired current
M1 has a threshold low enough that the Arduino turns it fully on.

Just duplicate the circuit for each LED you want to control. The code is no different to having an LED directly attached to the Arduino.

Thanks! Very easy.  Obviously I'm a newbie.  So each led will be in parallel, right?

Not each LED, no. Each complete circuit.

Yeah, I meant circuit.  Thank you!


text:
Menu on Serial Monitor
I'm trying to make a menu through serial monitor, but it always on a infinite loop... My question is where i call this function? On Setup or on Loop?
The menu:
  int controle_opera = 0;

  void menu() {

  int i = -1;
  do {
    char opcao = '\0';
    Serial.println("\nQual operação deseja realizar?");
    Serial.println("\n1 - Cadastro");
    Serial.println("\n2 - Validação");
    Serial.println("\n3 - Deletar");
    Serial.println("\n4 - Apagar database");
    if (Serial.available()) {opcao = Serial.read();}
    switch (opcao) {
      case '1': controle_opera++;
      i++;
      break;
      case '2': controle_opera += 2;
      i++;
      break;
      case '3': controle_opera += 3;
      i++;
      break;
      case '4': controle_opera += 4;
      i++;
      break;
      default: Serial.println("Opção desconhecida, tente novamente!");
              delay(100);
              break;
    }
  } while(i != 0);
}

You would run your menu from loop() - but not that menu since it is fundamentally flawed in many many ways.

Even when there're many others functions that need, for example, the value of "controle_opera"? There's any easy way to correct this menu?

Learn how to write a proper finite state machine.

@Mdsp take a look at this link for a correct format of switch case example.

https://github.com/neu-rah/ArduinoMenu works over serial


text:
Stepper motor release L298N
I'm Driving a stepper using a L298N driver and an arduino mega. I want to release the stepper after the movement so it can swing freely, because it gets hot, and it doesn't need to hold position.
Anyone know how to do it? I'm using just the basic stepper library.
Thank you.

Set Enable A; Enable B to LOW.

Usually you should set Enable (A and B) pins on L298 to LOW, effectively turning off the driver.


text:
Can't use two SPI devices at the same time
I can use the MFRC522 using the following code:
#include <SPI.h>
#include <MFRC522.h>

MFRC522 mfrc522(10, 9);

void setup() {
    SPI.begin();
    mfrc522.PCD_Init();
}

void loop() {
    if (  mfrc522.PICC_IsNewCardPresent() && mfrc522.PICC_ReadCardSerial() ) {
         // Do stuff
    }
}

And it works great. I can also use the dot-matrix (8x8) using the following code:
#include "LedControl.h"

LedControl lc = LedControl(12,11,8,1);

void setup() {
    lc.shutdown(0,false);
    lc.setIntensity(0,3);
    lc.clearDisplay(0);

    lc.setLed(0,2,5,true);
    lc.setLed(0,5,5,true);

    lc.setLed(0,2,2,true);
    lc.setLed(0,3,1,true);
    lc.setLed(0,4,1,true);
    lc.setLed(0,5,2,true);
}

void loop() {
}

And it works just fine as well. However, when I try to use both of them using the following code:
#include <SPI.h>
#include <MFRC522.h>
#include "LedControl.h"

LedControl lc = LedControl(12,11,8,1);
MFRC522 mfrc522(10, 9);

void setup() {
    SPI.begin();
    mfrc522.PCD_Init();

    lc.shutdown(0,false);
    lc.setIntensity(0,3);
    lc.clearDisplay(0);

    lc.setLed(0,2,5,true);
    lc.setLed(0,5,5,true);

    lc.setLed(0,2,2,true);
    lc.setLed(0,3,1,true);
    lc.setLed(0,4,1,true);
    lc.setLed(0,5,2,true);
}

void loop() {
    if (  mfrc522.PICC_IsNewCardPresent() && mfrc522.PICC_ReadCardSerial() ) {
         // Do stuff
    }
}

In that case only one of them works (the MFRC522). I know that since they are connected in SPI mode they need to have different SS pins, so I used pin 10 for MFRC522 and pin 8 for dot-matrix. So, what's wrong? Why dot-matrix doesn't work at the same code with MFRC522??

The LedControl doesn't use SPI library but it's using shiftOut internally. So you can't use them both at the same pins as the SPI interface takes over them.
Basically SPI.begin() takes over the control on its pins and that means when you use digitalWrite or pinMode on those pins, it'll be ignored (at least on some of them).
If you add SPI.begin() into the second example (LedControl one) it'll stop working. However you can change pins for LedControl to other (free) pins and it should be working again.
And also there are mixed signals between both devices:
HW SPI wiring:
13  CLK    output
12  MISO   input
11  MOSI   output
9   SS     output

and LedControl wiring is:
12  MOSI   output (not really)
11  CLK    output

Something from the datasheet about alternate pin functions:

SCK/PCINT5 – Port B, Bit 5
  SCK: Master Clock output, Slave Clock input pin for SPI channel. When the SPI is enabled as a
  Slave, this pin is configured as an input regardless of the setting of DDB5. When the SPI is
  enabled as a Master, the data direction of this pin is controlled by DDB5. When the pin is forced
  by the SPI to be an input, the pull-up can still be controlled by the PORTB5 bit.
  PCINT5: Pin Change Interrupt source 5. The PB5 pin can serve as an external interrupt source.
MISO/PCINT4 – Port B, Bit 4
  MISO: Master Data input, Slave Data output pin for SPI channel. When the SPI is enabled as a
  Master, this pin is configured as an input regardless of the setting of DDB4. When the SPI is
  enabled as a Slave, the data direction of this pin is controlled by DDB4. When the pin is forced
  by the SPI to be an input, the pull-up can still be controlled by the PORTB4 bit.
  PCINT4: Pin Change Interrupt source 4. The PB4 pin can serve as an external interrupt source.
MOSI/OC2/PCINT3 – Port B, Bit 3
  MOSI: SPI Master Data output, Slave Data input for SPI channel. When the SPI is enabled as a
  Slave, this pin is configured as an input regardless of the setting of DDB3. When the SPI is
  enabled as a Master, the data direction of this pin is controlled by DDB3. When the pin is forced
  by the SPI to be an input, the pull-up can still be controlled by the PORTB3 bit.
  OC2, Output Compare Match Output: The PB3 pin can serve as an external output for the
  Timer/Counter2 Compare Match. The PB3 pin has to be configured as an output (DDB3 set
  (one)) to serve this function. The OC2 pin is also the output pin for the PWM mode timer
  function.
  PCINT3: Pin Change Interrupt source 3. The PB3 pin can serve as an external interrupt source.
SS/OC1B/PCINT2 – Port B, Bit 2
  SS: Slave Select input. When the SPI is enabled as a Slave, this pin is configured as an input
  regardless of the setting of DDB2. As a Slave, the SPI is activated when this pin is driven low.
  When the SPI is enabled as a Master, the data direction of this pin is controlled by DDB2. When
  the pin is forced by the SPI to be an input, the pull-up can still be controlled by the PORTB2 bit.
  OC1B, Output Compare Match output: The PB2 pin can serve as an external output for the
  Timer/Counter1 Compare Match B. The PB2 pin has to be configured as an output (DDB2 set
  (one)) to serve this function. The OC1B pin is also the output pin for the PWM mode timer
  function.
  PCINT2: Pin Change Interrupt source 2. The PB2 pin can serve as an external interrupt source.

"So you can't use them both at the same pins" But I don't use them both at them same SS pin. I use pin 8 and pin 10.

@DimChtz: You have configured HW SPI interface (on pins 10,11,12,13), so it just can't be used with software implementation of SPI (by LedControl int pins 11 and 12). Maybe just try to add SPI.begin() into the second code example (LedControl only one)

I am confused. Does this mean I can't use 2 spi devices in the same code? That's weird. And if I add SPI.begin() into the ledcontrol only code leds won't work.

@DimChtz You can use more SPI devices with HARDWARE SPI (just with different SS). But you can't combine libraries that uses HARDWARE SPI with libraries that uses SOFTWARE SPI on same pins.

@KIIV, you could edit info from comments into answer.

Is there any solution or it's impossible to use both dot matrix and mfrc at the same time?

@DimChtz yes, there is a solution - use LedControl on other pins than 11,12,13

Okay, I changed ledControl 11,12 to 6,7 and it works. THanks !!


text:
ADXL345 accelerometer doesn't work
I just got the ADXL345 accelerometer module. I tried everything I could find online but I can't get it work. Here's how I connect the pins to the arduino uno:
ADXL345    ->     ARDUINO
  VCC               3.3V
  CS                3.3V
  GND               GND
  SDA               SDA
  SCL               SCL

I also use 2 10kOhm resistors from SDA, SCL to 3.3V on arduino. I tried both Adafruit and SparkFun ADXL345 libraries but it doesn't work. Using Adafruit library it says that no adxl345 is connected. I tried to connect SDO to 3.3V pin and then it stopped saying no adxl345 is connected but still didn't work (no x,y,z values displayed). Then I tried SparkFun library without connecting SDO to 3.3V (because it failed) and all I got was 0, 0, 0. I literally tried everything I could find from videos, tutorials, etc. I don't know why it doesn't work. What am I doing wrong? I already ordered the MPU6050. Is it any better?

As far as my experience goes you donot have to connect it to pulldown resistors. If using a 5v Arduino, simply connect it like:
VCC --> 5V  (Arduino)
GND --> GND (Arduino)
SDA --> A4 or SDA (Arduino Uno has dedicated I2C pins beside AREF pin)
SCL --> A5 or SCL
This is all you need. As although the ADXL345 is a 3.3v MEMS, its module comes with a 5v to 3.3v converter and also goes through its startup procedure (Refer datasheet) for you.
As for the library you can use this one here
Also you can refer this article for detailed usage here
And I hope next time you put in some more research and then buy a new part.

SDO should be tied to ground, not 3.3V. That puts it into I2C mode.
VDDIO, VS and CS all need to be on 3.3V.
To communicate with an Arduino at 5V you really need a 5V -> 3.3V I2C level shifter. I use the PCA9306DCUR.

Comments are not for extended discussion; this conversation has been moved to chat.

The ADXL345 module already has a level shifter.

@SupragyMishra How do you know? No specific module has been specified, only the chip that is on the module.

Most modules ship with a shifter and note that he refered VCC not Vdd (digital supply) and Vs (supply voltage)

@SupragyMishra A module having a voltage regulator (common) does not mean that the module has a logic level translator (rare). The Adafruit one is the only one I have found that has a level translator. All the others don't. VCC and VDD don't imply any voltage. One is the collector voltage (from the old TTL days) and the other is the drain voltage (CMOS terminology). Nothing there implies any voltage.

@Majenko Okay. I did my research and yeah the pins DONOT imply any voltage... And the ADXLs I have with me do have a regulator not a SHIFTER. But the 5v logic works okay with the I2c Lines. So i just assumed it would work with Dimchtz's sensor

@SupragyMishra In general I2C is fairly tolerant of differing voltages as it's an open-drain bus system. Pull the bus up to the higher voltage and hope the current through the pullup resistors isn't too high for the ESD diodes in the lower-voltage device. The majority of times that's perfectly fine.

authors: สามารถ ไชยรุณ


text:
Cannot write lock byte on Arduino Pro Micro
I have an Arduino Pro Micro, with atmega32u4 chip and a caterine bootloader. However, every time I (successfully) flash some program over the USB port, the /dev/ttyACM0 device disappears, and I cannot flash it any more over USB.
So I connect it to my stk500v2-compatible ISP programmer (MISO/MOSI/SCK go to pins 14,16 and 15 on the board; VCC,GND,RST to their counterparts). With this setup, I can flash a new Caterina bootloader onto it. The problem with flashing over the board's USB port stays, though.
So I tried to set the lock byte with the ISP programmer, which writes successfully, but then fails at verification:
> avrdude -p m32u4 -P /dev/ttyUSB0 -c stk500v2 -b 115200 -U lock:w:0x0F:m
...
avrdude: verification error, first mismatch at byte 0x0000
         0xcf != 0x0f

Is my assumption correct that the disappearing bootloader is caused by the wrongly set (un-)lock bits? If yes, why can't I set the lock byte via ISP?

Meanwhile, I managed to solve this problem.
The reason for the verification error is that the two most significant bits of the Lock Byte are read-only on my variant of the Arduino Pro Micro. Which means that, if you (try to) write a value of 0x00 = 0b0000 0000, it will result in a value of 0b1100 0000 = 0xC0 on the hardware.
The solution, then, was to simply ignore those two bits.
> avrdude -p m32u4 -P /dev/ttyUSB0 -c stk500v2 -b 115200 -U lock:w:0xCF:m


text:
Optimization Teensy 3.6 Arduino IDE fast I/O Multiplexing Led Matirx
I'm currently working on a 10x10 LED Matrix which is controlled by 5 Shift registers using multiplexing. I've the problem that the Teensy 3.6 is too fast/slow.
One part of my code is the Shiftout function. If I use normal digitalWrite() its working perfectly fine, but its slow. If I use digitalWirteFast() or something like GPIOA_PSOR = (1 << 12); the matrix starts to display crap.
Teensy 3.6 180MHz
74HC595 shift register
SS8050 BJT's to protect the whole thing
scematic here: circuits.io
void ShiftOut(uint8_t myDataOut) {
// This shifts 8 bits out lngMsLoopstartB first,
//on the rising edge of the clock,
//clock idles low
//internal function setup
uint8_t i = 0;
//clear everything out just in case to
//prepare shift register for bit shifting

//digitalWriteFast(dataPin, LOW);//Data aus
GPIOA_PCOR = (1 << 12); // Datapin low

//digitalWriteFast(clockPin, LOW);//Clock aus
GPIOA_PCOR = (1 << 13); // Clockpin low

//for each bit in the uint8_t myDataOut
//This means that %00000001 or "1" will go through such
//that it will be pin Q0 that lights.
for (i = 0; i <= 7; i++)  {

//digitalWrite(clockPin, LOW);//Clock aus
GPIOA_PCOR = (1 << 13); // Clockpin low

//if the value passed to myDataOut and a bitmask result
// true then... so if we are at i=6 and our value is
// %11010100 it would the code compares it to %01000000
// and proceeds to set pinState to 1.
if ( myDataOut & (1 << i) ) {
  //digitalWriteFast(dataPin, HIGH);//Data an
  GPIOA_PSOR = (1 << 12); // Datapin high

} else {
  digitalWrite(dataPin, LOW);//Data aus
  //GPIOA_PCOR = (1 << 12); // Datapin low
}

//register shifts bits on upstroke of clock pin
digitalWrite(clockPin, HIGH);//Clock an
//GPIOA_PSOR = (1 << 13); // Clockpin high

digitalWrite(clockPin, LOW);//Clock aus
//GPIOA_PCOR = (1 << 13); // Clockpin low

//zero the data pin after shift to prevent bleed through
digitalWrite(dataPin, LOW);//Data aus
//GPIOA_PCOR = (1 << 12); // Datapin low
}
}

if somebody needs the complete code, please let me know!

How it looks like when I use GPIO 2.Picture how it should look like: Imgur

Problem
The thing I want is to make the whole multiplexing faster. Currently 1 Time all 10 rows takes about 480 microseconds. Then add a 4 Bit Bit angle modulation (480*16) its: 7680 microseconds (7.68ms). So if you now divide 1000 by 7.68 = 130,2 Hz refresh rate. Thats ok and Im fine with that.
The main problem is that I want 8 bit. so same thing again 480 * 256 = 112880 (112,88ms). So now divide 1000 by 112,88 = 8,86 Hz refresh rate. That looks really bad. I would like to get about 60-100.
The Problem is not the big LED array or setting each value every frame new. This only takes 80 microseconds.

I have also written a driver for LED matrices based on shift registers. To quickly shift out the bits to the shift registers for each scan update, I used SPI. On the Teensy 3.6, this works quite well.
But what I suspect your issue is (since you didn't post your whole code) is that you are calculating each of the bit updates in between each shifting out. If you are doing this, I suggest that you don't. Instead, buffer the bit calculations, and use a timer interrupt to shift out each row update. This approach takes advantage of the fact that you are likely to recalculate the bit layout for the matrix overall at a much slower frequency than the need to send our row updates to effect the multiplexing of the LED rows. I explain this design in much more detail in this Instructable.
Using the interrupt allows you to cleanly do the heavy lifting of recalculating the bit layout into a buffer while the row updates will consistently go out, creating a very stable image. It's the closest thing you'd to true threading on Arduino-like platforms. Also, this approach will allow a much smaller base interval for row updates. In my code, I use a 5 µs update interval, that gets modulated in order to be able to create a 12-bit color palette. I probably could get a richer color depth on the Teensy 3.6 given it's clock speed, but I wanted my code to be universal, so I am able to get the 12-bit color on 8-bit AVR micro controllers too (e.g., Arduino Mega).
You can study (or use) my code at this GitHub repository, and read more about my LED matrices (hardware and software) at my website.

wow! Thanks for that. Will have a look in to that.
Using interrupts makes sense :D. Well in the meanwhile I built a new LED Matrix. But this time with TLC5940 LED Drivers: https://scholliyt.github.io/LED-Matrix-16x16/


text:
Serial.write without a receiver
I'd like to send  a monitoring information (temperature) to a serial receiver periodically. The problem is I don't know if there is any monitoring service (serial receiver) and how fast it is reading. I only need the latest value. The problem is that serial.write will block if the buffer is full. If I skip writing if the buffer is full, a receiver will only get old data on the first connect. How can I replace data in the buffer or make sure there is only one dataset in the buffer?

The problem is that serial.write will block if the buffer is full.

Only until the bytes get sent out through the TX pin.

If I skip writing if the buffer is full, a receiver will only get old data on the first connect.

No it won't. There is no "old" data.

How can I replace data in the buffer or make sure there is only one dataset in the buffer?

You don't need to.
You are showing a fundamental misunderstanding of how serial works.  When you send data it just twiddles the TX pin in the right way with the right timing. If there is something connected to it that understands that twiddling at the speed it's being twiddled then it interprets it as serial data. If there's nothing to see that twiddling it still twiddles.  The "blocking" is only if you try and send more data than the serial port can physically send out in the time you're sending it.
If a serial port transmits in a forest and there is no one there to hear it, yes, it still makes a noise.


text:
Locate devices that can move among multiple connections
I don’t know if this is even doable, but the idea is to have a large board with many (500+) locations where I objects can connect, each object having a single LED, and be able to illuminate the LED on any object, no matter where it is connected on the board.  So the requirement is that the objects can be moved to any of the connections on the board and and that the board can have any number if it’s connections occupied.
It seems obvious that each object would have to be able to identify itself and that each connection would have to be able to supply both a signal both ways and and provide power to light the LED.  On the code side, I’d need to be able to iterate through the connections and identify the desired object by some unique identifier and send a signal to turn the LED on and off.  I’m a .Net developer with little knowledge of electronics, but I’m willing to learn if it’s possible to do this.  I haven’t been able to find any arduino examples similar enough to provide some idea of where to start.  I don’t know if this is something that can even be done with Arduino or what components would be required if it is possible.
I’d appreciate any guidance on how this could be done or even suggestions as to what might be a better approach toward finding the guidance necessary to build this.

Please add some more requirements. Examples, max number of devices connected, power limit, total cost of device, more on the algorithm when connecting, timing of algorithm, respons time, etc. And last but not least, budget of project and max cost of board.

what is "the object" and what signal should it get? is it only some plastic shape with a LED that should be turned on and off?

are the objects addressable? . .. are the locations addressable?

Does the object (or main controller) need to know where it's pushed in? Your question is way too vague, but I was thinking of using audio sockets for the 500 locations and an audio jacks attached to the objects. Some of these jacks have ways to pass though a signal if no jack is inserted. So you could use Addressable LEDs in the objects, and have the sockets wired so the data goes to the led if the jack is inserted, or pass though if not.

The "objects" could be anything - even a block of wood.  Anything that would serve as an object upon which I could mount whatever components that would allow me to   flash an LED on the object no matter where it was located on the board.  I would need to have boards of various sizes, each having a different number of potential locations in a grid layout upon which these objects could be placed and moved from one location on the board to another.  I would need some means of being able to flash the LED of a specific block no matter where that block was attached on the board.

is LED "the object" or "the object" can have two LEDs and a temperature sensor. do you want to create a LED matrix or a network of sensor nodes?

Your question is awfully vague.
There is a protocol called I2C that's commonly used for microcontrollers. It's a serial bus that has a data line, a clock line, power, and ground. That might meet your needs.
Each device on an I2C bus is supposed to have a unique address. You send commands to it using that address, and it doesn't matter where it is located physically.
I2C is designed to be a chain, and each device has 2 connectors that pass the connection on to the next device on the chain.
I2C also uses a byte address, so you could only have 255 unique devices.

This sounds promising except that I would need more than 255 potential addresses.  I would need to be able to have a boards with grids of up to 100 columns and 50 rows where objects could be attached, so such a board would have to be able to support up to 5,000 objects with LEDs that could each be individually flashed no matter where they were on the board.


text:
MEGA I2C and interrupts on 0,1
Looking at the pinout for the Arduino MEGA:

I see that Pins 20 and 21 can be both SDA and SCL or Interrupts 0 and 1.
If I'm using an Adafruit I2C 16x2 RGB LCD Shield connected to the SDA and SCL pins by the USB Jack, is there anything I can do in my code to still use INT0 and INT1 off Pins 20 and 21 for a different purpose?

No, there is nothing you can do.
Both the SCL pins and both the SDA pins are physically connected together by copper tracks. They are in effect the same pin. If you use I2C you can't use INT0 or INT1. You have INT2 and INT3 though (pins 18 and 19), as well as Pin Change Interrupts on a large number of other pins.

I think there 2 other INTs that are brought out to pins as well, and then 2 more that are not, if PCINT won't meet your needs.

There are other INT pins for the MEGA I'm now using one of them. I haven't heard of PCINT though, I'll look into it.


text:
String to unsigned long conversion
I'm trying to use strtoul() to convert an Arduino String to an unsigned long (like the return of millis();) using the following code snippet:
unsigned long foo (String time)
{
  unsigned long mili;
  char Tim[9]="";
  uint16_t timsize = time.length()+1;
  char TIM[timsize];
  time.toCharArray(TIM,timsize);
  mili=strtoul(TIM,timsize,10);
  return mili;
}

The code seems to work. However, I'm getting the following warning:

invalid conversion from 'uint16_t {aka unsigned int}' to 'char**' [-fpermissive] mili=strtoul(TIM,timsize,10);

My question is twofold:

Is there a better way to convert a String to unsigned long without first converting to a C string?
If not, how can I eliminate this error?

unsigned long strtoul(const char *str, char **str_end, int base ); The 2nd parameter is char **. Can be nullptr.

I believe that char TIM[timsize] is bad code.  The size of arrays need to be know at compile time and since the value of time is not constant its length can't be known.  I think you'd need to do a new, if you were still doing it which you aren't because you are using .c_str()

It may be poor code. I do know that it works though (however for a 2D or greater array, only the last value can be a var)

@CodeGorilla char TIM[timsize] usually works on newer compilers:  Declaring an array with a non-constant size variable

VLAs are not part of the C++ standard. They work here because of a compiler extension.

Arduino String class provides method c_str(). So you don't have to convert it to C string, as it's already stored as a C string internally.
And as mentioned in comments, the second parameter of strtoul is:

endptr
      Reference to an object of type char*, whose value is set by the function to the next character in str after the numerical value.
      This parameter can also be a null pointer, in which case it is not used.

Basically you can reduce whole foo to the:  return strtoul(time.c_str(), NULL, 10);

Can you tell me more about how to access the c_str() method of a String? just using sec=strtoul(tim,endptr,10); did not work.

@ATE-ENGE Added to the answer.

Also be aware that strtol() can return 0 or ULONG_MAX if there is a problem, so the calling function should check for these because if you do a delay(ULONG_MAX); you'll think it has locked up :)

@CodeGorilla That would be a problem! Hypothetically, is there a good way to differentiate if a problem occurs? You know, in case a user actually does want to halt the program for 50 days :)

@ATE-ENGE You can use that endptr to check if whole string was parsed. However it returns 0 if there is nothing to parse and ULONG_MAX if the value is out of range so it must be even bigger than 32bit number.

0xFFFFFFFF in decimal is 10 digits, and you were looking at 9 for the size of Tim[] so you could have an issue.  You could look at endptr or you could enforce sensible limits, i.e. if (t < 100) t = 100; if (t>100000) t = 100000;


text:
Write array to serial port
The Code Below now works:
void SendCTRL (String &input)
{
  const char *hin = input.c_str();    // Get character array
  int clen = input.length()/2;
  unsigned char cmd[clen+1]; // Leave a byte for null terminator
  for (int i=0; i < 2*clen; i+=2)
  {
    cmd[i/2] = dehex(hin[i])<<4 | dehex(hin[i+1]);
  }
  cmd[clen] = 0;                     // Null-byte terminator
  digitalWrite(SSerialTxControl, RS485Transmit);  // Enable RS485 Transmit
  for (int i=0; i< clen; i++)
  {
  RS485Serial.write(cmd[i]);   // Send string someplace
  //Serial.write(cmd[i]);
  }
  delay(clen/4);
  digitalWrite(SSerialTxControl, RS485Receive);  // Disable RS485 Transmit
  Serial.println();

}

byte dehex(char c)
{
  // Get nibble value 0...15 from character c
  // Treat digit if c<'A', else letter
  return c<'A'? c & 0xF : 9 + (c & 0xF);
}

byte dehex(char c)
{
  // Get nibble value 0...15 from character c
  // Treat digit if c<'A', else letter
  return c<'A'? c & 0xF : 9 + (c & 0xF);
}

Input is a series of ASCII-encoded hex digits and getting the output to print the byte values of the hex.

There's some logic slightly askew with your length calculations:
int clen = input.length()/2;

Ok, so for a (say) 20 character string you have clen=10.
for (int i=0; i < clen; i+=2)

Ok, so for the first 10 characters of your 20 character string you take alternate ones (0, 2, 4, 6, 8)
What about the last 10 characters?  clen is 10, not 20, since you divided it by 2 at the start.
Decide if you want clen to be half the string length, then count double, or is the whole string length, and you divide it by 2 where you want the final string length. Or have two variables - one before and one after dividing by 2.
Oh, and you should pass your String parameter by reference so you don't duplicate the object and end up fragmenting your heap.
void SendCTRL (String &input)

I haven't gone into depth about the working of your dehex function, but this is the function I always use and works well:
unsigned char h2d(char hex)
{
    if(hex > 0x39) hex -= 7; // adjust for hex letters upper or lower case
    return(hex & 0xf);
}

Also you should or your values together, not add them:
cmd[i/2] = (dehex(hin[i])<<4) | dehex(hin[i+1]);

This would go some way to fixing your current issue, since | has a different precedence to +. At the moment you have effectively:
cmd[i/2] = dehex(hin[i]) << (4 + dehex(hin[i+1]));

since the + happens before the <<, whereas what you want is:
cmd[i/2] = (dehex(hin[i]) << 4) + dehex(hin[i+1]);

However with | instead you get
cmd[i/2] = (dehex(hin[i]) << 4) | dehex(hin[i+1]);

because the << happens before the |
Here is your code written in pure C to run on a PC (faster to debug and test than an Arduino when you're on Linux):
#include <stdio.h>
#include <string.h>

unsigned char dehex(char c)
{
  // Get nibble value 0...15 from character c
  // Treat digit if c<'A', else letter
  return c<'A'? c & 0xF : 9 + (c & 0xF);
}

void SendCTRL (const char *hin)
{
  int ilen = strlen(hin);
  int clen = ilen / 2;
  unsigned char cmd[clen+1]; // Leave a byte for null terminator
  for (int i=0; i < ilen; i+=2)
  {
    cmd[i/2] = dehex(hin[i])<<4 | dehex(hin[i+1]);
    printf("%02x\n", cmd[i/2]);
  }
  cmd[clen] = 0;                     // Null-byte terminator
  for (int i = 0; i < clen; i++) {
    printf("%c", cmd[i]);
  }
}

void main() {
    SendCTRL("010307E40001C549");
}

Ok! that got the writing working. Unfortunately, it just seems to output jibberish.

I have posted my version of a hex to dec converter. It may work better, or may not...

@Majenko,  c<'A'? c & 0xF : 9 + (c & 0xF) will work with a...f as well as A...F as representatives of 0xA...0xF.  Also, Addition vs Or makes no difference here, because the low 4 bits of  dehex(hin[i])<<4 are clear, and so are the high 4 bits of dehex(hin[i+1]).

@JamesWaldby-jwpat7 yes, it should all work fine in this situation - but it's good practice to get into the habit of combining with OR rather than with ADD.

Ok so my issue now is that my input string 010307E40001C549 should return me (as ASCII \code) \01\03\07\E4\00\01\C5I or (as U8) [1,3,7,228,0,1,197,73] Instead I'm getting (as ASCII) \100~@\EE any thoughts?

(as ASCII) \100~@\EE equates to (as U8) [16,48,126,64,238]

Because you're using + instead of | you have a precedence error. See my edit.

Switched to | for 010307E40001C549 I'm still getting
(as ASCII) \100~@\EE equates to (as U8) [16,48,126,64,238]
Updated Code above

Maybe the Arduino compiler is doing it slightly different then. Add brackets around the first part of the combination formula.

Oh, and you are still confused with your counting. You now have i++ instead of i+=2 which is wrong. Check my example (pure c) code for how to do it.


text:
Convert int to char[]
I'm looking to convert an int value to a char array. currently I've found the following will return [number]
int num = [number]
str = String(num);
str.toCharArray(cstr,16);
Serial.println(cstr);

However, per Majenko's The Evils of Arduino Strings I feel like this code would make my Arduino's heap look like swiss cheese. Is there a better way to change an [int] into a char[n] array that avoids the String class?

itoa is the best route:
int num = 1234;
char cstr[16];
itoa(num, cstr, 10);
-> "1234"

You can read more about using it here.
If you want more control over the format of the number (and don't mind the increased PROGMEM usage) you can use sprintf (or the more secure snprintf) to format it:
sprintf(cstr, "%05d", num);
-> "01234"

Or with PROGMEM string constant:
sprintf_P(cstr, (PGM_P)F("%05d"), num);
-> "01234"

Or with more values:
sprintf_P(cstr, (PGM_P)F("%02d:%02d:%02d"), hours, minutes, seconds);
-> "03:23:11"

Nice, I'm looking to take an int value in seconds and convert to hr:min:sec before I strcat([c string],[time]) as I understand, I'll have to stick with itoa since I don't want it to go to serial?

sprintf is a good choice. I'll add an example.

Ok, that looks like it will work for me. how do you go about getting the (PGM_P)F("%02d:%02d:%02d"), section? (specifically the (PGM_P)F part)

The F is documented in the arduino PROGMEM docs. The PGM_P just changes the pointer to the right type for_P variant functions.

You can also use the PrintEX library to give you all the 'printf' capabilities without having to deal with string types.


text:
Any good way to inverse a function?
I'm guessing that the answer to this is "no," but I'm curious if there is any way to save writing some code by specifying a function to do the opposite of whatever another function does. For example the inverse of:
int FW (int in)
{
  int out=2+in;
  Return out
}

would be
int RV (int in)
{
  int out=in-2;
  Return out
}

However, would there be any way to call the inverse of FW() if it was a more complicated function that still had one and only one input for each output?

Ask this question on stackoverflow and use c tag .You will get much better answers there

You could crate a more general function like; MOVE(int in, int direction){}

@Sniper, this is hardly a C question.  More of a theory question.  Per Halting Problem on wikipedia,  “Alan Turing proved in 1936 that a general algorithm to solve the halting problem for all possible program-input pairs cannot exist”, providing an easy answer of No to the question in its general form, and with more effort probably to the  “one and only one input for each output” subquestion as well. ¶ ATE-ENGE, of course there are lots of ways to get function inverses for particular functions, but from Turing's result not in general

lol! Well if Turing said I can't do it, I suppose I shouldn't try XD

Now if it could be used to figure out the original two factors multiplied together to produce a big number, then you would be on to something.

No. A function does what it does and that is all. No other function can know what some other function does.
You could write a function that does different things depending on what parameters you pass to it, but that's the closest you can get, and is pretty pointless when you can just write different functions anyway.

That's what I had thought. Thanks for confirming.

You can trivially see this to be true: imagine a function which returns 1 if the integer argument is odd, 0 if it is even. It's impossible to reverse this in reality, regardless of what you know about the code and what the code knows about the code.


text:
int VS uint8_t VS uint16_t
This question is quite clear. What are the differences between an int, an uint8_t, and an uint16_t. I know it has to do with bytes and memory but can someone clarify me a bit?
Things I want to know:
1- How much memory does each take.
2- When to use what.
3- In the end of the day, are they that different?

Beware that the compiler does not do arithmetic with anything smaller than int. E.g. (uint8_t) 200 + (uint8_t) 200 does not overflow: the terms are promoted to int before the addition and the result is (int) 400.

You can decipher most of them yourself.

A u prefix means unsigned.
The number is the number of bits used. There's 8 bits to the byte.
The _t means it's a typedef.

So a uint8_t is an unsigned 8 bit value, so it takes 1 byte. A uint16_t is an unsigned 16 bit value, so it takes 2 bytes (16/8 = 2)
The only fuzzy one is int. That is "a signed integer value at the native size for the compiler". On an 8-bit system like the ATMega chips that is 16 bits, so 2 bytes. On 32-bit systems, like the ARM based Due, it's 32 bits, so 4 bytes.  Of the three it is the only one that changes.
Personally I rarely use int and always use uint8_t etc., since the variable type is the same no matter what architecture you compile for.  When you use int you can run into problems if you had a program that worked fine on a 32-bit ARM but then doesn't work right on an 8-bit ATMega, since the int can only store a fraction of the range of numbers on the 8-bit system compared to the 32-bit system.

Can I make an uint8_t array?

You can make an array of any data type.

Can I use it like this too: uint8_t function()

Yes. uint8_t is the same as "byte" or "unsigned char".

If you need negative values, you need to use signed integers. E.g. int16_t.


text:
New tab VS OOP : which is better in Arduino
In C++, I understand that you can "multi-file" program and in Arduino, open a new tab. This is what I mean by file. Then, there is Object Oriented Programming or OOP for short (like with a .cpp and .h file.
Which of these 2 is a better method for splitting your code into multiple files? OOP seems more popular, but is also harder, but is there any real benefits for it?
I'm new to the world of OOP so please write an answer like if you would explain it to a newb! Also, I'm quite adventurous and so don't let difficulty change you anwsers bias!
For those that want to close this question as off-topic, note that SO closed it in less then 10 minutes.

Comparing both are like comparing bananas and apples. None is better than the other. Both are complementary. OOP is a real programming paradigm. Multifile is in no way a programming paradigm.

.cpp and .h is not OOP. That is just splitting things into files. OOP is the use of classes and namespaces, etc. Those can be used just in one file alone.
What you are asking is actually is it better to make a Library or to have multiple files in your sketch. This has absolutely nothing to do with OOP.
In general:

If you think you may need the code in other sketches then making it a library can be good.
If it is distinct code that will only ever be used in the one sketch there is no point in going to the effort of making a library.

Once the code is compiled it makes little or no difference if it's in a "tab" or if it's in a "library".

Let's say for a competition robot, with multiple programmers, what would you suggest?

@DatHa That question is meaningless. Libraries can make managing complex code easier since you have distinct modules. But editing libraries means working outside the IDE, which generally makes life harder. If there is no specific reason to make a library then the question "should you make a library" is entirely your own subjective personal choice.

@DatHa If you are working collaboratively then possibly using libraries may make the sharing of code easier, since each library could be unit tested individually and delegation of work to other people can be done on a per-library basis if you like. However much the same can be said of spitting into other files anyway.

These are two different techniques; one of programming, the other of managing files. They are independent of one another; you an apply either, both, or neither, as fits the situation.
A true OO design starts from the beginning of the project, finds the commonalities among the kinds of data that will be managed by the finished product, and abstracts away the most common of those into one or more base classes, from which the more specific classes will be derived. OOP is a whole course of study.
An OK first approximation is simply to create data objects as you go. This lets you hide private information - those details of the object that depend on how you implement that object, but aren't real attributes of the real-world object the data-object represents. This is sometimes called "C with classes".
Based on your statement that you are "new to the world of OOP", I expect this will be your most effective strategy.
Dividing your code into files or modules by grouping those functions dealing with, say, stepper motors into one pair of files (stepper.c++, stepper.h), and those dealing with ultrasonic sensors into another pair (usound.c++/.h), etc. is a perfectly good way to organize your code into files, once your body of code gets too big to keep it one file effectively. This doesn't necessarily hide the private, implementation information although you can do that, too, very effectively with file-level static variables and static functions.
C++ was originally implemented as a pre-processor that emitted pure C constructs from C++ syntax. Which means: Whatever you can do in C++, you could also do in C. The only difference is the details are all right there in the open for anyone to see. C++ puts more of them "behind the curtain".
If you have a good handle on writing C- or C++-with-classes, make good use of static variables and functions, and good choices about what might best be grouped with what into your separate files, you'll be pretty well prepared to take on the additional concepts of OOP.


text:
Soldering Arduino Pro Mini's disaligned pins
I have a couples of Arduino Pro Minis (original from sparkfun) that have those 4 disaligned pin. Unfortunetely, I need to use 2 of them, A4 and A5, because they are the I2C pins and I want to solder them onto a perf board.
Now, I really want to use headers and I do not want to solder any wire directly to it. I also do not want to add headers facing up on the board because I am trying to minimize space. Last, I am not willing to change Arduinos so please do not suggest me to use an Arduino Nano or Pro Micro.

So I would like to know if there is a way to connect those 2 pin to the perf board via headers or is there any alternative pins that I can use to connect and use the I2C interface.

That's indeed quite an problem.
If you don't mind losing 2 analog pin, you could solder some jumper-wires between A4 and A2; and between A5 and A3. Then you could connect your I2C lines to pins A2 and A3.
But you have to be careful to never set pins A2 and A3 to OUTPUT in your software. If you want to be super-duper safe, you could cut the trace from the header pins going to the TQFP-chip. See the image below.

Also for power saving, should I remove the leds?

@canadiancyborg definitely. At least the power-indication led. The pin 13 lid might be useful to keep.

No need to remove the LED. Just unsolder the little bridge next to the GND that is close to pin 2 and it will disable both the regulator and LED

Easy! I like these ProMinis and use them in lots of projects. Simply exchange one of the 12 way header pin strips for a 14 way one (cheap to buy long lengths of these strips from eBay) add small neatly soldered wires to extend A4 and A5 to the extra pins you’ve added and job done.

As you are soldering to perf board, perhaps you don't have a printed circuit board specific to your project. If you did, you could modify it, or could make a little intermediate PCB to accept connections from A4 A5 and shift them onto the grid.
If you have some 90°-angle headers, try removing a couple of pins from the plastic former, and 0.05" or 0.15" out from the line of the short side of the L, bend the long leg 90°.  Point the jog along the X or Y axis to align the pin with your perf board grid.