text:
Use class object inside an ISR
I have to simulate an ADC that behaves as an I2C slave. The simulated values that the ADC shall expose are sent over serial, saved on an attribute and are requested by a master device over I2C.
A simplified solution is the following. I have a struct ADC that describes the converter:
struct ADC
{
  uint32_t register_1;
  uint32_t register_2;

  void write_register_1(uint32_t data){
    register_1 = data;
  }

  void write_register_2(uint32_t data){
    register_2 = data;
  }

  uint8_t read(){
    return register_1;
  }

  // some other methods to setup...
};

In loop(), I read the serial in order to update the ADC::register value and in the onRequest handler I eventually send the requested data by accessing ADC::register:
ADC adc{};

void setup(){
  // setup adc, Wire and Serial here
  Wire.onRequest(slaveTransmitterHandler)
}

void loop(){
  if (Serial.available() > 0)
  {
     // read serial, parse received data and check them
     uint32_t data = parse_serial(); // do anything is needed to check data...

     // update adc attribute
     uint8_t oldSREG = SREG;
     noInterrupts(); // disable interrupts to update uint32
     adc.write_register_1(data);
     SREG = oldSREG;
  }
}

void slaveTransmitterHandler(){
  Wire.beginTransmission(ADDRESS);
  Wire.write(adc.read());
  Wire.endTransmission();
}

void slaveReceiverHandler(){
  uint32_t i2c_received_data;
  while (Wire.available){
    // fill i2c_received_data with Wire.read()
  }
  adc.write_register_2(i2c_received_data);
}

I'm not sure if I have to declare the adc object as volatile (this would mean to declare all ADC methods and variables as volatile). Is it safe to use an object inside the I2C handler called by the I2C interrupt?
As far as I know, it is not (I can find no reason why it should be different from non-class variables), but I have always worked with non-class variables and never with cpp objects. Also, I can't find any information about this topic.
It could be possible that I'm wrong with the whole design, even if it seems to me to be very consistent. I'm open to change it for something better, so please if this design is nonsense, comment on that! I'm here to learn :)
Thanks.
Luca
Edit:
Some clarification, since my question seems not to be clear enough: I'm doing HIL simulation, that is simulating the real hardware with its real interfaces with a simulated environment (that includes sensors and actuators). See here for more info.
One of my sensors measures a voltage and stores it in a register of an ADC (that has multiple registers). I'm simulating the behaviour of ADC registers in Arduino, and they shall communicate via I2C with the real hardware.
Hope this is more clear now.

I don't think the class has to be volatile here.  Nothing in the ISR is changing anything about the class, so there's no chance that the ISR fires in the middle of something else accessing the class and getting corrupted data.  The only possibility for corruption here would be if the ISR fired diring the write function but you seem to have handled that with a critical section around it.  It would be different if the ISR wrote to the object, but as written it only reads from it.  I think you're ok here.

@Delta_G This looks like an answer. Please post one and not a comment. Thank you.

Why are you doing Wire.onRequest(slaveTransmitterHandler)? That looks like you really are using I2C and not simulating it.

@Delta_G thanks! Let's say that I'm also setting some attributes of the adc object in an interrupt. How can I deal with that case? I've edited the original post to include this case (see slaveReceiverHandler). Shall I declare the object (and the whole class attributes and methods) as volatile? I guess so, but it seems that it's not really clear to me what volatile means when used in a C++ class (https://en.cppreference.com/w/cpp/language/cv this page goes above my understanding).

This isn't a forum. If you want to expand on the question please edit the question. Any answers given should address the question (as edited), not the question plus random comments. Nor should the answer be in a comment (not your fault).

If this is a simulation, and not actually using interrupts, then you hardly need to declare anything volatile. However your use of the Wire library makes it look less like a simulation. Personally I think your problem is under-explained. Please post all of your code. If you are simulating you won't need to worry about hardware interrupts. If you are using the Wire library you will.
Your other post Get address of a I2C transaction when multiple addresses are registered seems to be relevant here.

He is using the Arduino to fake an I2C ADC. The I2C link is real. The ADC readings are fake.

@EdgarBonet is right. I've edited the question with some more details.


text:
Can the Arduino Uno use a negative supply voltage (0V & -5V)
I acquired a bread-making machine. See control board image.
I want to use the machine for other purposes and control the buttons, paddle, heater & 7-segment display with an Uno.
As it stands, the machine provides 0V, -5V & -11V to the control board.
Is it possible to connect 0V to Uno VIN and -5V to Uno GND pins?
My initial idea was to replace the PENTALPHA-BV30K with an Uno and mapping the pins accordingly. I couldn't find any datasheet for the BV30K, however I'm reverse engineering the control board anyway.
Control board findings:

-11V is used to drive the A/B/C/D/E/F/G/DP segments of the LED display
BV30K only uses 0V & -5V

I added an image of the transformer based power supply board so that I could check the supply there. The larger heatsink is for the 7905 IC and the smaller heatsink is for the BTA06 Triac.

"0V, -5V & -11V" How do you know your meter probes aren't just swapped?

Voltages measured with Black (COM) meter probe connected to 0V & Red meter probe connected to -5V  & -11V on the larger white header on the control board. The header is also labelled as such.

I saw the - on the header silkscreen. It looks just as easily like a poor choice of punctuation. This is part of why I asked. Is there an ground plane in this thing? Is there a place that strapped the metal parts are strapped together that cross checks as showing -5 when you put your positive probe on the thing that says "5V" or "-5V" depending on how you look at it. If there isn't scarcely makes a difference if your UNO is running in the same system, because -5 to 0 is still 5V. The UNO doesn't much care what you label ground as long as whatever it's talking to agrees with it.

I ask mostly because it may just be a matter of perception and there's much of a question here. I wouldn't expect -5V and -11V in that thing unless maybe it's from the 70s and I guess, for that time, very high end.

I originally thought  that the "dash" was just bad punctuation.
I then started to reverse engineer the control board circuit. Those switching transistors are A1015, PNP. The emitter (in most) is strapped to (what is labelled) 0V. The collector is strapped, through a resistor, to (-)5V. The base is connected, through a resistor to a control pin on the IC BV30K. That's when I realised it must be negative 5V, relative to 0V. Otherwise the switching circuit would not work.
When testing with a meter there does not appear to be a connection between the metal earthed chassis and 0V on the board.

!! CAUTION !! ... the bread maker board may have powerline voltage on it, relative to earth ground

I'm not really sure what would make decent answer to this. What can be said about the Arduino in this context is just true of electronics generally. That circuits, independent of any other concern, care what what voltage difference is applied across them. The UNO is not somehow an exemption to this. So if you have any two voltage numbers that are 5V different, say -7805 VDC and -7800 VDC (to pick something absurd) you can put them in the right order to make a 5V "positive" difference. The thing is I get the sense from your comments you're at least that far along in your understanding.

Thanks for your comments guys. I normally would have just tried it after satisfying my own doubts - I just didn't want to cremate the Uno just yet. Anyway, I connected 0V to Uno VIN and -5V to Uno GND pins and all is well ;) I guess I'll put "yes" as the answer but really not sure why it was designed with the negative supply.

Has this device got a transformer in its power supply to isolate it from the mains voltage? If not, then it will be using some sort of transfomer-less power supply which will probably not be able to supply much more current to drive the Uno and any connections to that board risk bringing mains voltages outside. If in doubt, use optocouplers for any connections and a separate power supply for the Uno. Optocouplers would anyway make the +5v / -5v issue irrelevant.

How far have you reverse engineered the circuit now? What is the -11V good for? As long as all pins of the BV30K are in the 0V to -5V range, I would go on.

@6v6gt It's a transformer power supply - see updated images. I notice there's an optoisolator there too.

@thebusybee The -11V is used to drive the A/B/C/D/E/F/G/DP segments of the LED display. The BV30K only uses 0V & -5V.

The image of the power supply board suggests that there is no separation between powerline and the low-voltage parts. Make sure to protect yourself. However, you can connect the Uno directly. Just prohibit connections to PCs or humans during operation. -- BTW, please add requested information to the question. Down here in the comments other visitors will not read it. ;-)

@thebusybee - Added info to the question. I'm interested in what you said about the powerline separation. There is a large air gap on the underside, there is a transformer and there is an optoisolator, which I haven't looked at yet but will do. Granted, the separation could be better. Once finished the boards will be housed exactly as they were before in the bread machine, separated by about 15cm and a metal plate. Interaction with humans will be the only way the machine will work ;) The make/model is a Ronson 9110. This may be sliding off-topic a bit but it all helps build a good answer.

@thebusybee - Also, I was thinking that I could use the -11V supply instead of the -5V supply and connect the USB to program in situ, overriding the USB power supply. Thoughts on that?

As you describe the system, you can connect the system's ground to 5V of the Uno, and the system's -5V to Uno's ground.
Please note that you cannot reverse-feed 5V through the pin with the same label, it is an output. You can use the USB connector. You might want to solder wires at its pins instead of cannibalizing an old USB cable. Alternatively you can try VIN, as there is a LDO, but measure the resulting voltage. The specification demands at least 7V there.
If you want to power the Uno during development by the USB connection, you can disconnect any of -5V or ground, but not both, because you need a reference connection.
In contrast, you cannot use the -11V supply and use VIN and GND of the Uno, because the Uno's voltage regulator uses the lower level as reference and will set Uno's "high" (5V) to about -6V with reference to the system's ground. See:

Concerning the separation of power-line and the controller: Well, I'm just worrying about your health.
If you are sure that all is done well, go ahead. With a working separation you can even dare to connect the development PC to your Uno while the power-line is connected.

source: Stack Exchange

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

sort: votes


text:
How to configure watchdog for the arduino Nano 33 BLE Sense board?
For the arduino Nano 33 BLE Sense board, the standard avr/wdt.h is not available. And it seems that no standard library provides it. How to use the watchdog system for this board ? I found no full information about it.
I've found the page https://www.mysensors.org/apidocs/group__avr__watchdog.html which allow to configure the reboot mode. And it works. But no way to configure the interruption mode with ISR() function. Moreover, there's no explanation about the manipulation of used register/variables for any fine configuration.
Simple code example with regular asynchronous stuff using the watchdog ISR() mechanism. It which works well with ATmega328 (e.g.UNO). But I do not find equivalent configuration for the Nano 33 BLE using the nRF52840.
# include <avr/wdt.h>

volatile byte led;
int k;

ISR(WDT_vect) {
  Serial.println("Asynchronous stuff in ISR() function");
  digitalWrite(LED_BUILTIN,led);
  led=!led;
}

void setup() {
  pinMode(LED_BUILTIN,OUTPUT);
  led=0;

  Serial.begin(9600);
  while(!Serial) {}
  Serial.println("== R E B O O T ==");

  WDTCSR = ( 1 << WDE ) | ( 1 << WDCE );
  WDTCSR = ( 1 << WDP2 ) | ( 1 << WDP0 ) | ( 1 << WDIE ) ; // Interruption and timeout  1/2 s
}

void loop() {
  Serial.print("Loop #");
  Serial.println(k);
  if (k++%2) {
    Serial.println("Some stuff (even branch)");
    delay(1200);
  }
  else {
    Serial.println("Some stuff (odd branch)");
    delay(4800);
  }
}

Thks.

A little searching gave this link and that code seems to have worked: https://devzone.nordicsemi.com/f/nordic-q-a/53904/nrf52840-watchdog-for-arduino-nano-33-ble-sense

Yes but your link provides the same information as I pointed out. It's only about the set of watchdog with simple reboot, not the set of ISR() mechanism at the end of the counting of the watchdog timer.

I've just added in a simple code example, working with a uno. Looking for equivalent code for the nano BLE.

You did see they used other defines than you? NRF_WDT->CONFIG = 0x01; and so on. I don't see that in your code. Your code in setup directly writes to MCU registers that do not exist on the nano 33 BLE. To configure it, you must take over those parts. If and how the watchdog interrupt can be intercepted on the nRF processor is another question. Typically the watchdog interrupt just does reset - normally it is intended not to happen within your firmware. If your idea is to time the execution of some code you might use a timer interrupt for this - not the watchdog.

In fact, for the RF52940, I'm not sure that the watchdog can provide the needed interruption mechanism despite it exists the INTENSET bit for interruption according to the chipset doc https://content.arduino.cc/assets/Nano_BLE_MCU-nRF52840_PS_v1.1.pdf). But the good way is for sure the use of timers (and one can use more than just one, quite good).
For a similar behaviour as the code given for the UNO before, here is the code one can write for the Nano BLE using a timer interrupt (see https://github.com/khoih-prog/NRF52_MBED_TimerInterrupt for full and usefull doc).
#include "NRF52_MBED_TimerInterrupt.h"

volatile byte led;
volatile uint32_t count=0;
NRF52_MBED_Timer myTimer(NRF_TIMER_1);
unsigned k=0;

void myHandler() {
  digitalWrite(LED_BUILTIN,led);
  led=!led;
  count++;
}

void setup() {
  pinMode(LED_BUILTIN,OUTPUT);
  led=0;

  Serial.begin(9600);
  while(!Serial) {}
  Serial.println("== R E B O O T ==");

  if (myTimer.attachInterruptInterval(500*1000, myHandler)) // each 1/2 second
    Serial.println("myTimer launched");
  else
    Serial.println("Can not set the timer");
}

void loop() {
  Serial.print("Loop #");
  Serial.print(k);
  Serial.print(" and nb times in Handler : ");
  Serial.println(count);
  if (k++%2) {
    Serial.println("Some stuff (even branch)");
    delay(1200);
  }
  else {
    Serial.println("Some stuff (odd branch)");
    delay(4800);
  }
}

Re: "I'm not sure that the watchdog can provide the needed interruption mechanism despite it exists the INTENSET bit for interruption according to the chipset doc"  To clarify: once the NRF52 watchdog ISR has fired you are on a one-way trip to a RESET in little more than about 60uS. It may not do what the OP needs. So if that's what you meant, yup, it's limited compared to what the AVR counterpart lets you do. For anyone that only needs 60uS before the impending reset, INTENSET usage should meet their requirements.

You do not want to update your watchdog in an ISR. It is possible to get stuck but the ISR is continually triggered. I have seen this happen many times especially when a bad transient hits it. I normally use an external one so it will force a reset on the whole package. I do this by power cycling everything. Not all watchdog timers in processors will do an external reset.

I gave above an example working with UNO and I would like equivalent with the nano ble.

It works fine with UNO, Nano, and many others. I am not have a ble to try it.

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


text:
Why is this buffer not being sent to the server?
I'm loading a buffer with different data recorded by sensors and sending them to a server. But I also wanted to log when the data was sent on the client side, so I formatted the time of my RTC clock and tried to include it in the buffer, but this caused a problem. The data returned by the sensors are floating point numbers, but the timestamps are integers. When trying to send the buffer including both the datatypes, it is not received by the server. Under is the code which puts the data into the buffer:
char buffer[256] = {};

sprintf(buffer, "path?myfile.txt,%02d/%02d/%02d %02d:%02d:%02d,Temp=%lf,Humidity=%lf,Pressure=%lf,Light=%lf",rtc.getDay(),rtc.getMonth(),rtc.getYear(),rtc.getHours(),rtc.getMinutes(),rtc.getSeconds(),temperature,humidity,pressure,illuminance);

I am pretty sure the mixing of the data types or the formatting is the problem. I know it's not the buffer size because I have tested it with multiple sizes. The weird thing is that I can print the buffer out in the serial monitor without any problem. It is also formated the right way in the serial monitor:

"path?myfile.txt,10/02/23 17:05:16, Temp=26.863487,Humidity=24.886541,Pressure=99.868286,Light=8.387096

I have never experienced a situation where one buffer is sent successfully and another one is not.
If I for example send this buffer instead:
sprintf(buffer, "/cgi-bin/tof.cgi?zuluz.txt,Temp=%lf,Humidity=%lf,Pressure=%lf,Ligth=%lf",temperature,humidity,pressure,illuminance);

Everything works as it should. What do you think the problem is? And is there a good workaround for this? If this problem comes from the server itself, I can not do anything about it since I have no access to its backend code.
My board is the MKR NB 1500 using a MKR ENV shield to log the data.
Edit:
Here is the full function which actually writes to the server:
void write_server()
{
    Serial.println("Sending the buffer");
    char buffer[256] = {};

    client.print("GET ");
    sprintf(buffer, "path?myfile.txt,%02d/%02d/%02d %02d:%02d:%02d,Temp=%lf,Humidity=%lf,Pressure=%lf,Light=%lf",rtc.getDay(),rtc.getMonth(),rtc.getYear(),rtc.getHours(),rtc.getMinutes(),rtc.getSeconds(),temperature,humidity,pressure,illuminance);
    Serial.println(buffer);
    client.print(buffer);
    client.println(" HTTP/1.1");
    client.print("Host: ");
    client.println(server);
    client.println("Connection: close");
    client.println();
    Serial.println("Buffer sent");
}

The only diffrence from the actual code is the path on the server and the file name in which the data is stored.

the space in the timestamp is the problem. replace it with %20 (correctly escaped for printf pattern). (and path should begin with /, but I guess it is missing just because of the obfuscation for the post)

In addition to what Juraj said, a proper HTTP query string should be in the format as  /test/demo_form.php?name1=value1&name2=value2, so you are missing a key for you datetime string, and , is not a valid delimiter and should be replaced by &.  Try path?<filename>=myfile.txt&<datetime>=10/02/23%2017:05:16&Temp=26.863487&Humidity=24.886541&Pressure=99.868286&Light=8.387096, replace  and  with whatever your server is expecting.


text:
Power Arduino and LED strip
I saw this question about powering Arduino and LED strip. So, I searched for a 5v 4a power supply and foud this one.
How does that adapter provide power for both Arduino and LED strip? I thought I might need DC barrel Plug to alligator clips but I'm not sure as this is the first time I use an external power supply to power multiple components.
So what do I need to make that wall adapter able to power both Arduino and LED strip?

does it provide enough current to power both? ... just sum the current requirement of all of the components

@jsotola I mean the 4A is enough, but when using the DC barrel plug to alligator clips will it still be 4A?

that is not what you asked .... if you meant to ask something different, then edit your post

I assume, that your problem is how to connect everything to the power supply.
You have some different options, depending on your requirements. The linked adaptor (barrel plug to alligator clips) doesn't seem to fit the barrel plug of the power supply. So you cannot use that. Especially it seems, that both are the male part of the connection. For every plug connection you need a male and a female part of the same connector type (much like your power outlet on the wall is a female part, while the power plug on your supply is a male part; in terms of plug systems).

The best way (especially, when you want to not only experiment, but also use it as a fixed product) would be to solder the wires. For this you need a soldering iron, soldering tin and something to clean the iron (sponge for soldering irons for example).

You can buy a barrel jack, solder wires to it and connect them to the Arduinos 5V pin, ground and to the LED strips power lines in parallel (from + pin of the supply one wire each to 5V Arduino and + pin of the LED strip, from - pin of the supply one wire each to ground of Arduino and - pin of the LED strip). Then you can still disconnect the power supply from your project.
If you don't want to buy a barrel jack and you don't need to disconnect the power supply from your project, you can splice up the cable of the power supply (only the LOW VOLTAGE PART!!!). You can use nail scissors, if you don't have other tools for it. Cut off the plug by cutting the cable a few cm before it. Then cut the plastic between the 2 connected parts of the cable for a few cm, so that you get the 2 individual cables (+ and -).  Use the scissors to carefully cut the outer plastic around the cables and remove about 1cm of it, so that you now have 2 cable ends with the bare cable core free. Twist each end, so that it each little copper strand stays in the cable shape. Then solder the cable ends. Now you can take another wire/cable to solder the connections from the two ends to the described parts. Be sure to isolate the connections at the cable (in the best case with shrinking pipes, otherwise you can also use tape).

If you don't want to solder, you can search for fitting connectors for every part. There are breadboard power adaptors, which should work with this power supply. They have pins on them, that you can not only use with breadboards, but you can also connect jumper wires to them. There also exist such adaptors for typical LED stripes, though that depends on the type of strip, that you have. When looking for jumper wires, you should make sure, that they are capable of conducting enough current. The Arduino does not need much current, thus standard jumper wires will be sufficient. But the LEDs can draw much more current, so that the standard jumper wires will start to smolder and catch on fire. Then you need some with a bigger wire diameter.

You can also use alligator clips, but in my experience, they only work for rather specific cases. The connection, that they make, is fragile and can be easily disturbed. They are slipping and rotating easily. When connecting the LED strip, you might easily connect + and - together and destroy the power supply. Also it is almost impossible with most of them to connect to a standard 0.1 inch pin (which are used on the Uno and Nano), without also connecting other pins. Unless you break out these pins with something else (like jumper cables), that is not a good choice.

You can now choose yourself, which way to go. If you plan to do more with Arduino and electronics, I would suggest, that you buy a soldering iron and the needed supplies. You will need it and they only cost a few bucks, if you just buy a simple one (back then I got one for 15€/$, which also had a temperature control, so you can also get it cheaper). If you don't want to buy it, but still want to solder, you could look for a maker space near your location.
I would go for soldering here, because you are very much limiting yourself, when you choose to do not. Then you need to buy fitting parts, which is more difficult.

how do I know what the ground is and the 5v?

For the power supply you can see it on the label. There you will find the following sign:

It means, that the outer shell of the connector is ground (-) and the inner pin is 5V (+). With cables there are 2 possibilities:

Often the wires inside a cable each have an own isolating plastic shell around them, which is color coded. Black is normally ground, while red is 5V/+.

When having a 2 wire cable, the cable is often designed as coaxial cable (which reduces noise on the signal). In that case you have one inner wire, which has it's own isolating plastic shell, and the outer wire, which is laid around the inner wire without any further isolation. The outer wire is normally ground.

When using an extra cable for connecting 2 parts, make sure to use the same wires on both sides (for example the red wire for 5V on both sides).
To be sure, you can check the voltage on the wires with a multimeter (also a very useful tool), when the cable is connected. A multimeter has a positive and a negative lead, which are marked as red and black respectively. When you connect the multimeter to the wires and it shows a positive voltage, you have found the correct association of the wires with their voltage (5V or ground).

Thanks for your answer. That is exactly what I wanted to know. I'm going for the first option but I don't understand where I solder the wires on? For example, I have this one: https://www.adafruit.com/product/327 how do I know what the ground is and the 5v? With the aligator clips it was quite easy to see.

@Helper I added a description about how to find the correct polarity.+

You can feed 5V directly into the 5V pin of the Arduino as ChrisL says. However, that bypasses the protection circuits built into the Arduino. If you ever forget to disconnect the 5V and plug a USB cable into your Arduino then you risk damaging it, since both your external power supply and the USB port will be feeding 5V into the 5V line.
What I decided to do is to cut the end off of USB cable and connect that to my 5V power supply. On almost all USB cables, the +5V wire is red and the ground wire is black. You'd just solder red to +5V and black to ground, then plug the USB cable into your Arduino. Then when you need to connect the Arduino to your computer, you disconnect the USB power cable and plug in a USB data cable. It's impossible to feed power from both sources at once.
If you're going to be doing much tinkering with Arduinos and electronics you should get a decent soldering iron and an auto-ranging multimeter. You can use the multimeter to figure out which wires are which. (See chrisl's on how to use a multimeter to find positive and negative power connections.
Another issue you may face is voltage droop on your power supply as your LED strip turns groups of LEDs on and off. If you draw near the max current from your power supply then there will likely be fluctuations in the power supply voltage as the LEDs turn on and off.
What are the max current requirements for your LED strip? You don't want to draw too close to the full output of your power supply or you might get fluctionations in voltage that could cause your Arduino to malfunction. If you use a power supply with something like 25% extra capacity (Say your LED strip draws 4A and you use a 5A power supply instead) you should be ok.

For the wall adapter, I think to get 5 V  (DC) 4 A, the LEDs 30 will take 50mA so that gives 1.5A, if I ever change to 60 led (3A) then I'm still safe.


text:
Problem reading input data using SoftwareSerial library
I can't read data using SoftwareSerial library, because SoftwareSerial.available() is always 0, no matter what I do.
I'm trying to communicate 2 Arduinos Uno, the 1 Serial (name of the first Arduino Uno) and 2 Serial (name of the second Arduino Uno). The 2 Serial will send data to 1 Serial, and 1 Serial will receive this data through a Software Serial port, and then re-write the data received to Hardware Serial Port, but I can't read this, and when I try to print what is available is software serial port, always shows 0. I know that I can do the otherwise, but I'm testing this, because in my future project I will need to use this software serial port to read input data, so this is just a test.
The pic of my simulation with the circuit is this:
My code is:
For 1 Serial (the data receiver):
#include <SoftwareSerial.h>

SoftwareSerial portOne (7,8);

String str1;

void setup()
{
  // Start the hardware serial port
  Serial.begin(9600);
  portOne.begin(9600);

}

void loop()
{
  while (portOne.available() == 0)
  {

  }
  str1 = portOne.readString();
  Serial.println(str1);
}

For 2 Serial (the data sender):
String str;

void setup()
{
  Serial.begin(9600);   // put your setup code here, to run once:

}

void loop()
{
  Serial.println("Testing from serial port2");
  delay(2000);
}

I have already read in another topics of this forums and in the internet, but any of them worked for me.
Thanks in advance.
EDIT 1: I'm only simulating both of Arduinos on Proteus, I don't have the hardware with me right now. The image wasn't clear enough, so I hope this one is better to see the wiring diagram. I'm using Virtual Terminal at the Serial Ports so I'm able to see what is being written at the Serial Ports.

How should they ever communicate? In your wiring image I don't see any connections between the Arduinos. If that is not thr real wiring diagram, then please show it. Have you connected RX to TX and vice versa? And it seems, that you are currently only using a simulator? Which one are you using? Or do you really use the real hardware? (Thats a big difference)

I'm using Proteus to simulate, because I will only get the hardware in 2 weeks, so I'm trying to finish code before they arrive. Sorry if it isn't clear enough, but in Proteus you can link them with the labels to facilitate the view. I will edit my post with a more clear image with the wiring diagram.

Don’t the simulated Arduinos need their grounds connected, as they would in reality?

@StarCat Doesn't look like that's even possible in proteus... no GND or power pins.

I wonder... is SoftwareSerial even possible in simulation...? It barely works on real hardware.

@Majenko, You’re right. If that’s the level of simulation then I doubt it’s advanced enough to correctly simulate SoftwareSerial.

This article (updated today) says, that it should work.

In Proteus we don't have to connect to power supply or gnd phisically, it is like he is already connected internally.  The thing is Software Serial can be used in simulation to send messages, the thing is, I don't know if it can be used to read the messages received through Software Serial Ports.

@chrisl this article only shows the sent message, and this I can do easy at Proteus, but I couldn't find any article, video or anything simulating the Software Serial to read a message in Proteus. But thank you for your time and effort.


text:
ESP8266 malloc/calloc-related crashes ("segfaults")
This is sort of the continuation of this problem. After getting hints that the problem I had were related to bad memory, I checked all of my heap-allocating code again and found a malloc that didn't allocate enough memory for an array. After fixing that and fiddling around with calloc, which may be safer for array-related stuff, I think I exposed the actual programming errors themselves. The crash message I get now is:
No poison after block at: 0x3fff0fb8, actual data: 0x84 0xf 0xff 0x3f

User exception (panic/abort/assert)
Panic umm_malloc.cpp:422 umm_malloc_core

which sounds to me like some sort of ESP segfault. The code where this happens according to the stack trace is the following:
Menu* createMenuStructure(ace_time::TimeZone* mainTZ) {
  // create an array of all clock faces, i.e. a pointer to an array of function pointers
  void (**allClockFaces)(T_DISPLAY*, ace_time::ZonedDateTime*);
  // funkiest malloc in the world; undefined behavior? I hope not.
  allClockFaces = (void (**)(T_DISPLAY*, ace_time::ZonedDateTime*)) calloc(DESIGN_MENU_SIZE, sizeof(*allClockFaces));
  // initialize array
  allClockFaces[0] = &basicDigitalCF;
  allClockFaces[1] = &digitalWithSecondsCF;
  allClockFaces[2] = &basicAnalogCF;
  allClockFaces[3] = &binaryCF;
  allClockFaces[4] = &fullDayBinaryCF;
  ClockFaceSelectMenu* cfMenu = (ClockFaceSelectMenu*) malloc(sizeof(ClockFaceSelectMenu));
  cfMenu = new ClockFaceSelectMenu((char**)design_menu, (size_t)DESIGN_MENU_SIZE, allClockFaces);

  // time zone select menu
  TimeZoneSelectMenu* tzMenu = (TimeZoneSelectMenu*) malloc(sizeof(TimeZoneSelectMenu));
  tzMenu = new TimeZoneSelectMenu();

  Menu** allMenus = (Menu**) calloc(3, sizeof(*allMenus));
  // initialize first layer of sub menus
  allMenus[0] = cfMenu;
  allMenus[3] = tzMenu;

  OptionsMenu* mainMenu = (OptionsMenu*) malloc(sizeof(OptionsMenu));
  mainMenu = new OptionsMenu((char**)main_menu, (size_t)MAIN_MENU_SIZE, allMenus);

  // for now, manually set the sub menu's parent to the main menu. When all menus are finished, the main menu will do this automatically
  allMenus[0]->parent = mainMenu;
  allMenus[3]->parent = mainMenu;

  ClockMenu* clk = (ClockMenu*) malloc(sizeof(ClockMenu));
  // timeClient is a global NTPClient variable
  clk = new ClockMenu(&timeClient, mainTZ, (Menu*)mainMenu);

  return clk;
}

All names containing Menu are classes derived from that base class, and the top couple of lines allocate an array of function pointers. And just to be clear: This code was working perfectly fine for the last several days of development until I made some changes to the SD card functionality that caused the constant crashes.
I am not very used to working in manual memory management. Is this way of allocating appropriate, and if so, correct? What am I doing wrong, or does the error lie somewhere else in the (~1500sloc) project?
Edit: Although the issue is already solved, thanks to the approved answer, I wanted to clarify that the constants used in the array allocation are all correct and correspond to the string array's length. E.g. main_menu is a string array of length 5 and MAIN_MENU_SIZE is a constant defined right next to the array definition that is also defined to 5. This is of course necessary as C arrays have no way (that I know of) of finding the length of complex pointer arrays such as these.

Where are the matching calls to free?

Not sure if it's related to your problem, but you should never use malloc in C++. It allocates memory without actually creating an object, which results in undefined behavior, which could very well crash your program. You should always be using smart pointers (std::unique_ptr, std::shared_pointer, std::make_unique, std::make_shared) to manage dynamically allocated memory. In the rare case where you do need raw allocations, you can use new/delete, but never malloc/free.

You wrote:

// funkiest malloc in the world

Funky, indeed. ;-) I kind of like its twisted beauty, but not everyone
does. Some may urge you to typedef that function type.

allClockFaces[4] = &fullDayBinaryCF;

Are you sure DESIGN_MENU_SIZE is strictly larger than 4? Maybe an
assert() would be good to use here.

ClockFaceSelectMenu* cfMenu = (ClockFaceSelectMenu*) malloc(...);
cfMenu = new ClockFaceSelectMenu(...);

You are assigning a value to cfMenu twice in a row, which means the
value assigned first is lost. This is a memory leak. You do not need
malloc() here, as new takes care of the memory allocation prior to
initializing the object. This error is repeated several times in this
function.

allMenus[3] = tzMenu;

allMenus has length 3: valid indices range from 0 to 2. This is an
out-of-bounds array access, and the likely cause of the errors you see.

OK, the behavior of new wasn't exactly clear to me, especially because Arduino isn't exactly standard C++. Thank you for clearing everything up for me and hinting me towards typedef.

Re “Arduino isn't exactly standard C++”: It's slightly preprocessed C++. Arduino.h is implicitly included, function prototypes are added for you, and then your code is handed to a regular C++ compiler (namely avr-gcc).

But which C++ standard? I found that some C++ functionality I researched online would not be accepted by avr-gcc, or needed to be modified. I knew about the implicit function prototypes, which I avoid anyways and just put void setup(); void loop(); in the beginning of my main files.

It's C++11 (platform.txt puts “-std=gnu++11” in compiler.cpp.flags) with no exceptions, RTTI or STL. The things that are supported (like new) generally work as expected.


text:
Send ECG signal with NRF24L01 from Arduino to Raspberry Pi 3
I'm using nRF24L01 to send ECG samples from an Arduino to Raspberry Pi, the type of sample is double after denoising, and I stock them in a byte[8] to send 8 by 8 sample. When I print the sample before stockage that show the good results, but if I print data stored in the byte the signal show a lot of fluctuations. In Raspberry Pi, I can read correctly byte data like transmitted, but if I send them in a vector of double or int in reception (python) don't give the same frame transmitted.
#include <IIRFilter.h>
#include <FIRFilter.h>

#include <SPI.h> // Call SPI Library
#include <nRF24L01.h> // Call NRE Version Library
#include <RF24.h> // RF24 Header File

#define CE_PIN  9
#define CSN_PIN 10
const uint64_t pipe = 0xF0F0F0F0E1LL;
RF24 radio(CE_PIN, CSN_PIN);

const int ECG_samplefreq  = 200;//sampling frequcy
const int DC_offset = 511;

const double b_lp[] = {0.0026, 0.0155, 0.0388, 0.0517, 0.0388, 0.0155, 0.0026};
const double a_lp[] = {1.0000, -2.3797, 2.9104, -2.0551, 0.8779, -0.2099, 0.0218};

IIRFilter lp(b_lp, a_lp);
unsigned int i = 0;

void setup() {
  Serial.begin(9600);
  radio.begin();//Intializing NRF24L01 Module
  radio.setPALevel(RF24_PA_MAX);
  radio.setChannel(0x76);
  radio.openWritingPipe(pipe);// For Transmitting Operation, Must OpenWritingPipe
  radio.enableDynamicPayloads();
  radio.powerUp();
  pinMode(7, INPUT); // Setup for leads off detection LO +
  pinMode(8, INPUT); // Setup for leads off detection LO -

}
void loop() {
  const static unsigned long ECG_interval  = round(1e6 / ECG_samplefreq);  //sampling period = 5000 ms => 200 sample by 1 seconde
  static unsigned long ECG_prevmicros = micros();
  byte  s[8] = {0};

  if ((digitalRead(7) == 1) || (digitalRead(8) == 1)) {
    Serial.println('!');
  }

  else {
    for (int i = 0; i < 8; i++)
    {

      if (!Serial) {
        ECG_prevmicros = micros();
      }
      else if (micros() - ECG_prevmicros >= ECG_interval)
      {
        int value = analogRead(A5);
        double filtered = lp.filter( value - DC_offset);

        filtered = round( filtered + DC_offset);
        s[i] =  filtered
        Serial.println( s[i]);
        ECG_prevmicros += ECG_interval;

      }
    }
    radio.write(&s, sizeof(s) ); // sending in real time ECG sample. 8 sample by transmission . 8 => 4 oct of one sampe = 32 oct by transmission.

  }
}

the problem thant i put in s[i] a double of four octs. im searching how can i send them whithout byte array, and receive the correctly. So thankful for your help

I am not a math genius but when I get you right you are trying to send 8 double values as a series of 8 x 8 bytes. My calculator tells me the result is 64 but you can only transmit 32 bytes at once using nRF24L01+. So maybe you should provide us some code and describe its function to us so we will be able to understand your problem and provide some help.

Even if the OP is trying to send one double value per message (8 x 8 bytes), does one really need all that precision?  Perhaps they can round off the double values to fit more data values within a 32-byte data packet.  Show the code and explain a little more what is going on.

I see multiple flaws in your code:

radio.write(&s, sizeof(s)); does not what you think it would. The correct statement would be radio.write(s, sizeof(s)); without the ampersand.
You are using double. Not using floating point numbers at all would be preferable.
Your s is of type byte. Thus it only holds 8 bytes. So your floating point calculations are being truncated to the range [0, 255]. From your problem description this is not what you are trying to achieve, I think.

Yes you're right. I mislaid in the storage in the byte variable s[8]; I changed the type of samples to int32_t; similarly the type of byte emission vector to int32_t s[8]. the problem now at the raspberry level I get a 32-bit list instead of 8 samples int32_t


text:
Aruino UNO not getting programmed on MAC OSX
I am using MAC OSX Mojave and trying to program an Arduino UNO board. However, whenever I start the Arduino IDE, I only find one port in the ports section called: /dev/cu.Bluetooth-Incoming-Port.
When I select that, since there is no other option, I get the following error code on pressing 'Upload' button. The error code I receive is given in image.
My programmer is ArduinoISP and the board is Arduino UNO

Kindly help me resolve this issue.
Note
I have reinstalled CH34x drivers (latest version v.5)

It is either a driver, cable, or physical USB port issue - "/dev/cu.Bluetooth-Incoming-Port" is not an Arduino. Have you tried moving the Arduino and cable to another computer (just to see if it is even recognized)? Substituting another cable?

Mojave is known to be a complete pig. Read this: https://forum.arduino.cc/index.php?topic=570440.0

Your newly installed driver might be quarantined by Mac security, Click on System Preferences -> Security & Privacy to see if it is blocked.

@Majenko Thanks a lot! The first suggestion on the forum that deals with removing the serial files and rebooting worked! Finally, I can actually use my Arduino. Thank you.


text:
ESP8266 + Arduino Mega
I am currently carrying out a project where I am using an Arduino Mega2560, to recover data from two ultrasonics sensors (HC-SR-04).
For the purpose of my project, I must add HTTP requests to this, unfortunately the Arduino Mega2560 does not allow me to connect to a WIFI.
I contacted my school, they gave me an ESP32, but as far as I understand I will not be able to connect it to my Arduino 2560?
I also have an esp8266, I found the documentation for the code, but despite many attempts (ex: connecting ESP8266 to mega 2056), I cannot connect, I cannot connect it to my MEGA 2560.
Anyone have any ideas / advice?
Regards,
David

As this is a school assignment, do you really have to use the Mega for the project? They gave you an ESP32, which is way more capable than the Mega. With a 5V (depending on your exact board for example from USB) source and a voltage divider you can directly connect the HC-SR-04 to the ESP.

https://github.com/jandrassy/WiFiEspAT


text:
Arduino NANO (CH340) error while flashing bootloader
Ok. So I'm close to tearing me hair out on this one.
I have a batch of cheap Arduino Nano clones, that just straight up won't work. (I HAVE gotten one of them to work, but I suspect that was by pure coincidence)
Anyway, I feel like I've tried everything to make them work.
I am consistently getting

Device signature = 0xffffff

errors from avrdude, which I believe is a hardware problem. Up til now I have tried:

Installed CH340 drivers, no difference
Tried to burn bootloader using Uno as an ISP (with 10uF cap between reset and ground!)
Tried the "(Old Bootloader)" option in the IDE

All I have left is to desolder the entire board and troubleshoot each single component, but... no, I want to keep my sanity intact, thaaank you!
Any ideas on how I should move forward here?

Does this answer your question? Arduino Nano clone doesn't upload Linux

was the bootloader burning successful?

Had the same problem on Windows 10, using the CH340 drivers from their website:
http://www.wch.cn/download/CH341SER_EXE.html

@Juraj no, unfortunately :(

@VE7JRO I am running Ubutnu 16.04, with the 4.15.0-76-generic kernal

Realize that my Ubuntu install is severely outdated. The problem is that it wont even flash the bootloader on Windows 10, which is up-to-date

Hit reset randomly in the first few seconds of uploading/burning.

Tried, no change. Thank you though!


text:
Reading sensor with current ouput with Arduino
I am having diffuclt times with this sensor, so I kndliy ask for your help!
The sensor is named "SPUVA-CS-C3535-A", datasheet here.
The sensor I use (cs3535) has just two pins (+ and -).
From my undesrstanding the ouput is a current corresponding on the UV light exposed to this sensor.
Max value of the current is difficult to understand from the datasheet that also do not have a typical suggested circuit. It seems that a medium value is 200nA, it seems really low!
I have connected (+) of the sensor to 3.3V, (-) of the sensor to A0, and a 220ohm resistor from A0 to Gnd. But readings are always 0.
Any help would be really appreciated! Thanks

The "sensor" is just a photodiode that is sensitive to UV. You use it the same as any photodiode.
The simplest (and crudest) way is to use a very large (eg 1MΩ) pullup resistor to 5V on an ADC pin, then connect the sensor (reverse biased) between the ADC pin and GND.

Thanks. I tried your suggestion, I get an high value (about 600) from the analog input, without UV light on the sensor, and it goes down to 100 when it is exposed. Is this normal? I connected 3.3V -- 1mohm -- (+) sensor (-) Gnd.  A0 to (+) of sensor. Also the read value is not instantyl changed, instead it "drifts" to a value during several seconds...

That sounds about right, yes. As light falls on it some small current leaks through it, reducing the voltage across it.

Ok. Thank you very much for your answer.


text:
How to display CAN BUS information on EPS32 web server?
I try to display the transmitted information from CAN bus on ESP32 web server. I saved the CAN.read() in a buffer receivedChars[i] and try to display the data by  client.println(receivedChars[i]);}. However, nothing shows on the webserver... The complete code shows below,
// Copyright (c) Sandeep Mistry. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

#include <CAN.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <WiFi.h>

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 32 // OLED display height, in pixels

// Replace with your network credentials
const char* ssid     = "NGW_2.4G";
const char* password = "NextGW2018";

// Set webserver port number to 80
WiFiServer server(80);

// Variable to store the HTTP request
String header;

// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);

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

  if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    Serial.println(F("SSD1306 allocation failed"));
    for (;;);
  }
  delay(2000);
  display.clearDisplay();
  display.setTextColor(WHITE);

  Serial.println("CAN Receiver");
  CAN.setPins(16, 17);
  // start the CAN bus at 500 kbps
  if (!CAN.begin(500E3)) {
    Serial.println("Starting CAN failed!");
    while (1);
  }

  // Connect to Wi-Fi network with SSID and password
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  // Print local IP address and start web server
  Serial.println("");
  Serial.println("WiFi connected.");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  server.begin();
}

void loop() {

    char receivedChars[10];
  // try to parse packet
  int packetSize = CAN.parsePacket();

  if (packetSize) {
    // received a packet
    Serial.print("Received ");

    if (CAN.packetExtended()) {
      Serial.print("extended ");
    }

    if (CAN.packetRtr()) {
      // Remote transmission request, packet contains no data
      Serial.print("RTR ");
    }

    Serial.print("packet with id 0x");
    Serial.print(CAN.packetId(), HEX);

    if (CAN.packetRtr())
    {
      Serial.print(" and requested length ");
      Serial.println(CAN.packetDlc());
    }
    else
    {
      Serial.print(" and length ");
      Serial.println(packetSize);

      // only print packet data for non-RTR packets
      while (CAN.available())
      {
         for (int i=0; i<5; i++)
         {
           receivedChars[i] = (char)CAN.read();
           Serial.print(receivedChars[i]);
         }
      }
      Serial.println();
    }

    Serial.println();
  }

   WiFiClient client = server.available();   // Listen for incoming clients
   if (client) {                             // If a new client connects,
    Serial.println("New Client.");          // print a message out in the serial port
    String currentLine = "";                // make a String to hold incoming data from the client
    while (client.connected()) {            // loop while the client's connected
      if (client.available()) {             // if there's bytes to read from the client,
        char c = client.read();             // read a byte, then
        Serial.write(c);                    // print it out the serial monitor
        header += c;
        if (c == '\n') {                    // if the byte is a newline character
          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          if (currentLine.length() == 0) {
            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
            // and a content-type so the client knows what's coming, then a blank line:
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println("Connection: close");
            client.println();

            // Display the HTML web page
            client.println("<!DOCTYPE html>");
            client.println("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
            client.println("<link rel=\"icon\" href=\"data:,\">");
            // CSS to style the table
            client.println("
Can bus
");
            client.println("
text: 	");

         for (int i=0; i<5; i++)
         {
           receivedChars[i] = (char)CAN.read();
           client.println(receivedChars[i]);
         }

            client.println(" .
");

            // The HTTP response ends with another blank line
            client.println();
            // Break out of the while loop
            break;
          } else { // if you got a newline, then clear currentLine
            currentLine = "";
          }
        } else if (c != '\r') {  // if you got anything else but a carriage return character,
          currentLine += c;      // add it to the end of the currentLine
        }
      }
    }
    // Clear the header variable
    header = "";
    // Close the connection
    client.stop();
    Serial.println("Client disconnected.");
    Serial.println("");
  }
}

It looks like the CAN-BUS can not be activated in web server session, I save the transmitted information in a buffer before starting the web server session, and print out the information from the buffer.


text:
RTC problems after longer time periods
I'm using the MKR NB 1500 for server sending, an ENV shield for measuring the environment, and an external lithium battery to power the circuit. The internal RTC and WDT on the NB 1500 are used.
The program is trying to measure data, send it to a server, go to sleep, wake up, and repeat the process. Under is a scetch of how the program is set up in main.cpp:
void setup()
{
    setup_watchdog(); //Sets up the watchdog timer with a 32 s bite time
    delay(1000);
    connect_GPRS_NB(); //Connects to the NB network and opens a GPRS connection
    request_NTP(); //Requests epoch1970 from the NTP server and then closes the connection
    timezone_adjustment(); //Adjusts the epoch time to my timezone (in Norway)
    set_RTC(); //Activates the SAMD21 RTC with this timezone adjusted time
    disconnect_NB(); //Disconnects from the NB network
    delay(2000);
    disable_watchdog(); //Disables the WDT in its entirety

void loop()
{
    setup_watchdog(); //Sets up the watchdog timer with a 32 s bite-time
    connect_GPRS_NB(); //Connects to the NB network and opens a GPRS connection
    get_ENV_data(); //Takes measurements using the MKR NB ENV shield
    connect_to_server(); //Connects to the server in which the data will be stored
    write_to_server(); //Writes the data on the server
    disconnect_from_server(); //Disconnects from the server
    disconnect_NB(); //Disconnects from the NB network
    watchdog_reset(); //Resets the watchdog timer

    disable_watchdog(); //Disables the WDT in its entirety
    LowPower.deepSleep(300000); //Goes to deep sleep for 5 minutes
    delay(2000);
}

All the functions above are written in other .cpp files and imported thru header files into the main file. The reason I'm using the RTC is because I want to log the time at which the data was sent to the server on the client side.
I set the circuit outside yesterday night and it actually sent data to the server the entire night. But the RTC did not function as I had hoped. Under is a clip-out of the data which was written on the server yesterday night:
nyktertest1.txt,11-02-23I23:39:40,Temp=22.593750,Fuktighet=31.063698,Trykk=1014.553223,Lys=9.677420
nyktertest1.txt,11-02-23I23:54:40,Temp=26.049343,Fuktighet=27.074978,Trykk=1014.549561,Lys=10.322580
nyktertest1.txt,11-02-23I23:56:34,Temp=24.909540,Fuktighet=29.182085,Trykk=1014.637695,Lys=9.032258
nyktertest1.txt,01-01-00I00:05:14,Temp=24.873356,Fuktighet=29.023129,Trykk=1012.826172,Lys=5.161290
nyktertest1.txt,01-01-00I00:10:29,Temp=22.231909,Fuktighet=34.242844,Trykk=1013.905762,Lys=5.161290
nyktertest1.txt,01-01-00I00:15:43,Temp=15.881580,Fuktighet=38.981991,Trykk=1014.769043,Lys=5.161290
nyktertest1.txt,12-02-23I00:18:39,Temp=19.047699,Fuktighet=38.823032,Trykk=1014.885742,Lys=10.967742
nyktertest1.txt,01-01-00I00:05:15,Temp=18.975330,Fuktighet=34.083885,Trykk=1015.005371,Lys=9.677420
nyktertest1.txt,01-01-00I00:10:30,Temp=20.350330,Fuktighet=33.440662,Trykk=1016.046631,Lys=3.225806
nyktertest1.txt,01-01-00I00:15:45,Temp=21.291119,Fuktighet=36.523697,Trykk=1014.721191,Lys=3.225806
nyktertest1.txt,01-01-00I00:20:59,Temp=15.338817,Fuktighet=43.358864,Trykk=1014.953369,Lys=3.225806
nyktertest1.txt,01-01-00I00:26:15,Temp=10.689146,Fuktighet=47.306919,Trykk=1015.068359,Lys=3.870968
nyktertest1.txt,01-01-00I00:31:30,Temp=8.011514,Fuktighet=48.974121,Trykk=1015.034424,Lys=3.870968
nyktertest1.txt,01-01-00I00:36:44,Temp=6.600330,Fuktighet=49.428818,Trykk=1015.172363,Lys=3.870968
nyktertest1.txt,01-01-00I00:41:59,Temp=5.731909,Fuktighet=49.321609,Trykk=1015.128174,Lys=3.870968
nyktertest1.txt,01-01-00I00:47:14,Temp=5.207238,Fuktighet=48.792984,Trykk=1015.133057,Lys=3.870968
nyktertest1.txt,01-01-00I00:52:28,Temp=4.791119,Fuktighet=48.171944,Trykk=1015.092529,Lys=3.870968
nyktertest1.txt,01-01-00I00:57:46,Temp=4.375002,Fuktighet=47.377159,Trykk=1015.114258,Lys=4.516129
nyktertest1.txt,01-01-00I01:03:01,Temp=4.157896,Fuktighet=46.929855,Trykk=1015.123535,Lys=4.516129
nyktertest1.txt,01-01-00I01:08:15,Temp=4.013159,Fuktighet=46.194218,Trykk=1015.161133,Lys=3.870968
nyktertest1.txt,01-01-00I01:13:29,Temp=3.832237,Fuktighet=45.754311,Trykk=1015.314209,Lys=3.870968
nyktertest1.txt,01-01-00I01:18:43,Temp=3.705593,Fuktighet=45.044548,Trykk=1015.297852,Lys=3.870968
nyktertest1.txt,01-01-00I01:23:57,Temp=3.560856,Fuktighet=44.948437,Trykk=1015.371582,Lys=3.870968
nyktertest1.txt,01-01-00I01:29:11,Temp=3.416119,Fuktighet=44.164742,Trykk=1015.308350,Lys=3.870968
nyktertest1.txt,01-01-00I01:34:25,Temp=3.307568,Fuktighet=43.883793,Trykk=1015.287842,Lys=3.870968
nyktertest1.txt,01-01-00I01:39:39,Temp=3.307568,Fuktighet=43.458672,Trykk=1015.299072,Lys=3.870968
nyktertest1.txt,01-01-00I01:45:10,Temp=3.162830,Fuktighet=42.959621,Trykk=1015.257324,Lys=3.225806
nyktertest1.txt,12-02-23I02:08:19,Temp=3.217106,Fuktighet=42.833935,Trykk=1015.262695,Lys=3.870968
nyktertest1.txt,12-02-23I02:13:33,Temp=3.180922,Fuktighet=42.416210,Trykk=1015.253418,Lys=3.870968
nyktertest1.txt,12-02-23I02:18:49,Temp=3.144737,Fuktighet=42.331184,Trykk=1015.185059,Lys=3.225806
nyktertest1.txt,12-02-23I02:24:03,Temp=2.945724,Fuktighet=42.268341,Trykk=1015.238281,Lys=3.870968
nyktertest1.txt,12-02-23I02:29:18,Temp=2.855265,Fuktighet=41.983696,Trykk=1015.152832,Lys=3.870968
nyktertest1.txt,12-02-23I02:34:32,Temp=2.782896,Fuktighet=42.016968,Trykk=1015.135742,Lys=3.870968

The list goes on until the morning. I was not able to only copy the time column of the datasheet, but you can see the time column on the right side of "nyktertest1.txt" which was the file I was writing the data to at the server. The three numbers on the left represent the date, so 11-02-23 is the 11 of February 2023. And the time is right next to the date, a | was used the separate the time and the date. So the data in the first row was logged at 23:39:40, which would be 11:39:40 PM.
But if you look further down the time column, only the minutes and seconds were logged correctly for a good while. It seems like the RTC values where just zeroed out. But after a while, the time was corrected again.
Here is the function for doing the NTP request:
void request_NTP()
{
    Serial.println("Starting connection to 'no.pool.ntp.org'");

    Udp.begin(localPort);
    sendNTPpacket(); // send an NTP packet to a time server
    // wait to see if a reply is available
    delay(1000);

    if ( Udp.parsePacket() )
    {
    Serial.println("Packet received");
    // We've received a packet, read the data from it
    Udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer

    //the timestamp starts at byte 40 of the received packet and is four bytes,
    // or two words, long. First, esxtract the two words:
    unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
    unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);

    // combine the four bytes (two words) into a long integer
    // this is NTP time (seconds since Jan 1 1900):
    unsigned long secsSince1900 = highWord << 16 | lowWord;

    // Unix time starts on Jan 1 1970. In seconds, that's 2208988800
    const unsigned long seventyYears = 2208988800UL;
    // subtract seventy years:
    UNIX_1970 = secsSince1900 - seventyYears;
    Udp.stop();
    Serial.println("UDP Closed");
    }

    else
    {
        Serial.println("No packets where recieved");
        ///Av en eller annen grunn vil programmet stoppe her dersom en kun lukker UDP tilkoblingen
        Udp.stop();
        Serial.println("UDP Closed");
        Serial.println("Trying again..");
        delay(2000);
        request_NTP();
    }
}

This is the sendNTPpacket() function which was used in the request_NTP() function above:
void sendNTPpacket()
{
    //Serial.println("1");
    // set all bytes in the buffer to 0
    memset(packetBuffer, 0, NTP_PACKET_SIZE);
    // Initialize values needed to form NTP request
    // (see URL above for details on the packets)
    //Serial.println("2");
    packetBuffer[0] = 0b11100011;   // LI, Version, Mode
    packetBuffer[1] = 0;     // Stratum, or type of clock
    packetBuffer[2] = 6;     // Polling Interval
    packetBuffer[3] = 0xEC;  // Peer Clock Precision
    // 8 bytes of zero for Root Delay & Root Dispersion
    packetBuffer[12]  = 49;
    packetBuffer[13]  = 0x4E;
    packetBuffer[14]  = 49;
    packetBuffer[15]  = 52;

    // all NTP fields have been given values, now
    // you can send a packet requesting a timestamp:
    Udp.beginPacket(NTP_server, NTP_port); //NTP requests are to port 123

    Udp.write(packetBuffer, NTP_PACKET_SIZE);
    Udp.endPacket();
    delay(1000);
}

This is the function for adjusting the UNIX time to my own timezone:
void timezone_adjustment()
{
    TimeChangeRule NoCET = {"CET", Fourth, Sun, Oct, 3, +60};
    TimeChangeRule NoCEST = {"CEST", Fourth, Sun, Mar, 2, +120};
    Timezone Norway(NoCET, NoCEST);
    UNIX_adjusted_No = Norway.toLocal(UNIX_1970);
}

This is the function for setting up the RTC:
void set_RTC()
{
    const int RTC_second = second(UNIX_adjusted_No);
    const int RTC_minute = minute(UNIX_adjusted_No);
    const int RTC_hour = hour(UNIX_adjusted_No);
    const int RTC_day = day(UNIX_adjusted_No);
    const int RTC_month = month(UNIX_adjusted_No);
    const int RTC_year = year(UNIX_adjusted_No)%100;

    /// Starter RTC klokken
    rtc.begin();
    //rtc.setTime(RTC_hour, RTC_minute, RTC_second);
    //rtc.setDate(RTC_day, RTC_month, RTC_year);
    rtc.setYear(RTC_year);
    rtc.setMonth(RTC_month);
    rtc.setDay(RTC_day);
    rtc.setHours(RTC_hour);
    rtc.setMinutes(RTC_minute);
    rtc.setSeconds(RTC_second);
}

And this is the buffer being sent to the server:
sprintf(buffer,"/cgi-bin/tof.cgi?nyktertest1.txt,%02d-%02d-%02dI%02d:%02d:%02d,VannTemp=%lf,LuftTemp=%lf,Fuktighet=%lf,Trykk=%lf,Lys=%lf",rtc.getDay(),rtc.getMonth(),rtc.getYear(),rtc.getHours(),rtc.getMinutes(),rtc.getSeconds(),water_temp,air_temp,humidity,pressure,illuminance);

I don't think the RTC is just half its values. I think the watchdog might have bit on the third loop, meaning the program had to do an NTP request at startup to initialize the RTC. But the UNIX time was not successfully received from the server, so the RTC was initialized with all clock values being 0. The program continued to log for a couple of cycles as you can see on the datasheet. But then the watchdog bit again and the circuit was reset. But the NTP request was done successfully this time, and therefore the time was logged correctly until the morning when I picked it up.
This is only my theory though and I am not sure of it. What to you think is happening? And what would be a fix?
Another problem that I noticed in the morning was that the RTC seemed to be lagging over 5 minutes behind the real-time. Is this a normal issue with the SAMD21 RTC? Because im planning to eventually have this Arduino log data for weeks or months without me touching it. Having the clock fall behind after longer time periods would then be a huge problem.
Edit:
Under is the write_to_server() function:
void write_to_NTNU_server()
{
    Serial.println("Sending the buffer");
    char buffer[256] = {};
    client.print("GET ");
    sprintf(buffer,"/cgi-bin/tof.cgi?nyktertest1.txt,%02d-%02d-%02dI%02d:%02d:%02d,VannTemp=%lf,LuftTemp=%lf,Fuktighet=%lf,Trykk=%lf,Lys=%lf",rtc.getDay(),rtc.getMonth(),rtc.getYear(),rtc.getHours(),rtc.getMinutes(),rtc.getSeconds(),water_temp,air_temp,humidity,pressure,illuminance);
    Serial.println(buffer);
    client.print(buffer);
    client.println(" HTTP/1.1");
    client.print("Host: ");
    client.println(NTNU_server);

    client.println("Connection: close");
    client.println();
    Serial.println("Buffer sent");
}

Here is the code for creating the client object from the NBClient class:
NBClient client;

always format all printout as code

please reduce your program to the simplest code that exhibits to problem

Thank you for the tips. I thought all of the code I pasted could give information about the source of the problem. But I will try to reduce it.

that is how code debugging works ... remove parts of the code that may not be causing the problem and test

It looks like Udp.parsePacket() returns the packet size. An incorrect size could give incorrect results. Can you please check that the correct packet size arrives?

Can you post the code for write_to_server which appears to be the code that actually writes the incorrect data?

comment out all of the code in loop() that deals with the database server ... use serial monitor to determine program flow ... add a lot of debugging code to print to serial

I added the write_to_server() code @nick Gammon

what board name shows the Arduino IDE when the MKR is in bootloader mode (after double reset)? If the board got for some reason a Nano IoT bootloader it would be configured as crystalless and not use the external crystal. the RTC on Nano IoT drifts as you describe because it doesn't have the external crystal.

As long as Udp.parsepacket() retrieves a packet the condition will be true (since the packet must have a size) and the code should function as normal, no matter the size of the packet. But if the packet is not retrieved the statement will return 0. And request_NTP() will be called again. So it cant be the specific size of the packet which is the problem (I think so at least).

The board type in the tools section stays as MKR NB 1500 when resetting the board Juraj. But I don't know if that's what you were talking about.


text:
TFT display shows black stripes
I'm new to the field: I'm trying to drive a TFT ST7735S display (this is the model I'm currently using: https://www.amazon.it/dp/B078JBBPXK/ref=pe_24968671_487022601_TE_SCE_dp_1) with an Arduino Mega following this video (https://www.youtube.com/watch?v=iPeukOK6stk&ab_channel=Artigiano2.0-AlessioRomanelli). Once the hardware is set up and the code is written, when I run the example script "graphictest" of the Adafruit library for st7735 and st7789, the display shows stripes on the background as shown in the picture below:

(Note that the strange effect is not camera's fault)
Reading online I thought that the problem could be the fact that the display is powered with 5V instead of 3.3V, but I've also tried powering it with 3.3V (Arduino Mega 3.3V) with little to no changes. I've changed the tft.initR(INITR_BLACKTAB); to tft.initR(INITR_GREENTAB); too, as suggested by a user i this thread (https://forum.arduino.cc/t/bugged-1-8-inch-tft-diplay/1012166/5) and i've also tried powering the display with 5V but using 4.7k resistors in series to reduce the voltage as suggested in the same post, but it still doesn't work.
Moreover the strange effect that the image shows does only appear, if I use a 5V supply, just when the program executes the void setup() function, then becomes sharp (this does not happen if I power the display using the Arduino Mega 3.3V output supply: in fact in this case the stripes are still present even when entering the void loop() function)
As I said before, the program and the hardware setup arethe same as the video I was talking about.
One thing I noticed is that, when I press the reset button on the Arduino Mega, an instant before the program is reloaded, the stripes disappear leaving the image as sharp as it should have been, without any strange background effect. Does anyone have any idea on how to solve this issue?
Thank you in advance for any eventual answer!
EDIT:
This is the picture of the modified verison of the connections, running the graphictest program with the suggested code:
#else
  // For the breakout board, you can use any 2 or 3 pins.
  // These pins will also work for the 1.8" TFT shield.
  #define TFT_CS        10
  //#define TFT_RST        9 // Or set to -1 and connect to Arduino RESET pin
  #define TFT_RST        8 // Or set to -1 and connect to Arduino RESET pin
  #define TFT_DC         9
#endif

// OPTION 2 lets you interface the display using ANY TWO or THREE PINS,
// tradeoff being that performance is not as fast as hardware SPI above.
#define TFT_MOSI 11  // Data out
#define TFT_SCLK 13  // Clock out

// For ST7735-based displays, we will use this call
Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_MOSI, TFT_SCLK, TFT_RST);

Hopefully every connection is visible

why are you trying to power the LCD with 3.3 V supply? ... the diagrams on the Amazon page clearly show a 5 V supply connection

In fact, I did power it with 5V supply, but after reading online it seemed (mainly from the thread I pointed in the question) that 5V could damage the display. Nevertheless I tried it all and even if powering it with 5V the problem remains.

you said that you connected some series resistors ... that's not powering it with a 5 V supply

after the problem showed when supplying 5V directly I both tried powering it using 3.3V and 5V reduced to 3.3V using resistors. But the problem showed by powering it with 5V in the first place

did it ever work correctly?

Just when I tried to restet the Arduino Mega: by pressing the built in button, an instant before the program is restarted the image appear as sharp as it should be, without any kind of problem in the background

Adafruit made that graphictest program for screens that they sell. The screen that you have is not sold by Adafruit and there is no reason why they should support that screen.
Still, you can get it to work, if it is not bricked. After you see enough variants, you get an idea about what you need to get them to work. So, I suggest the following.....
Go here https://www.arthurwiz.com/software-development/177-inch-tft-lcd-display-with-st7735s-on-arduino-mega-2560 and hook up the screen to your mega just exactly as in their table. You will make 8 connections. Download and execute their 'Hello World' program from the tutorial. If that runs ok, then you know that the connections are correct. Note that the constructor is:
Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_MOSI, TFT_SCLK, TFT_RST);
Also, don't worry if the screen is not rotated correctly - you can add one line in setup() to fix that:
  tft.initR(INITR_BLACKTAB);
  tft.setRotation(1); // <---added
  tft.fillScreen(ST7735_BLACK);

Now on to graphictest. Find these lines and change them to how I have them. I left one line commented out to illustrate. You do this to identify which GPIO go with which function. Yes, I could have started here, but going through the first tutorial successfully means you have not bricked the screen and you have the connections correct.
#else
  // For the breakout board, you can use any 2 or 3 pins.
  // These pins will also work for the 1.8" TFT shield.
  #define TFT_CS        10
  //#define TFT_RST        9 // Or set to -1 and connect to Arduino RESET pin
  #define TFT_RST        8 // Or set to -1 and connect to Arduino RESET pin
  #define TFT_DC         9
#endif

You will use Option 2 and the constructor as stated previously - so
// OPTION 2 lets you interface the display using ANY TWO or THREE PINS,
// tradeoff being that performance is not as fast as hardware SPI above.
#define TFT_MOSI 11  // Data out
#define TFT_SCLK 13  // Clock out

// For ST7735-based displays, we will use this call
Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_MOSI, TFT_SCLK, TFT_RST);

// Use this initializer if using a 1.8" TFT screen:
  tft.initR(INITR_BLACKTAB);      // Init ST7735S chip, black tab

Note that even though my screen still has a green tab, if I use the green tab initializer, I will have offset problems.
Make sure you haven't left any other configuration lines uncommented. I have the same screen and just hooked it up and tested all of this and everything works fine.

Let us know how it goes.
Edited to add:
You do not need to add ANY external resistors. Your Mega has connections for both 3V and 5V and you need to use both voltages.
Your initial pic (see below) shows that both pin 2 and pin 8 are connected to the same +V on the rail of the breadboard. This is incorrect. As shown in the table I linked, Pin 2 on the LCD goes to 5V on the Mega and pin 8 on the LCD goes to 3.3V on the Mega.

Thank you very much: I will try and let you know how it goes as soon as possible. In the mean time I have tried something myself: I read online that the screen, even if supplied with 5V requires 3.3V logic, thus I included 1k resistors in series with the SPI pins and the problem seems to be fixed even though the screen has become unstabile (flashy and often decays to a white screen before the end of the executiom of the setup function). I can't tell if this happens because of the fragility of breadboard connections or for any other kind of reason)

I've tried to hooke the LCD up like you suggested, but there are two main problems: the background still isn't fixed and the speed at which the lcd refreshes has significantly decreased. In other words the background that should be black starts as white and slowly becomes grey but never black

@Luke__ assuming you have proper connections and are not using any added resistors and no breadboard / lead problems, I wonder if your screen is not the problem. A nice clear pic of the screen and the mega connections might help. Did the "hello world" program run ok?

@Luke__  Please make sure you are correctly connecting SEPARATELY +5V AND +3.3V from the Mega to the correct connections on the screen - see my edit in the initial answer.

The "hello world" showed the same problems. I've edited the question with the requested picture showing the graphictest program in execution. I think I connected all correctly, tell me if I'm I'm wrong

@Luke__ I painstakingly checked all your connections and NOW I think you have them right. It is possible that you damaged the screen getting to this point because you did not have these connections initially and tried a lot of things - call that tuition for learning. One thing though, that white space on the left is an offset issue and I think you are using the green tab initializer - change it to tft.initR(INITR_BLACKTAB);      // Init ST7735S chip, black tab and see if that doesn't go away. It looks better than at first and me be as good as it gets.

yeah, I did use INITR_GREENTAB, but I've laso tried using BLACKTAB: nothing better. At this point if the screen is damaged, have you some better suggestions about some low budget ST7735 displays that are easy to use and 1.8'' (at this point I think it is easier to just use a 1.8'' display rather than a 1.77'' one), maybe that is also 5V, as it is easier to use with Arduino pin outputs ?

@Luke__ Sorry we don't really recommend products here, but I think you have something that is working and a much better idea about how careful you have to be with these connections. Keep plugging away :)

I understand. Thanks a lot for your effort and time in answering me, I really owe you a favour! XD

I had the exact same issue, and tested the things here but it did not help.
Then I pressed the reset button on my UNO with the same result as Luke__ had (the screen looked nice as long as I pressed the reset). After doing that a few times the display started to work as it should.
Strange, but resolved my issue.

I experienced the same problem. I bought an ST7735S from Amazon, labelled as 'ST7735S 3.3V'. It showed banding even when powered with the 3.3V pin from an Arduino Nano so I realised that the digital outputs from the Nano were also at 5V. I used a TXS0108E logic level converter to bring the outputs from the Nano down to 3.3V and the display works perfectly - problem solved.
I can show you my circuit on Fritzing if it would help.


text:
Maduino (Arduino Zero) at91samd21g18 - Unable to connect to the serial port
I have been using this device very little but it was use to work, and it also gave me the same issue in the past, the somewhat I was able to upload again.
I tried to use the reset button, and short GRD with RST pins, but nothing helped.
The device is recognised as Arduino MRK1000 and connected.
I also tried to specify Arduino Zero (Native USB Port).
Under Tools > Get Board Info I get:
BN: Arduino MKR1000
VID 0x2341
PID: 0X804E
SN: 414C4E1[...]

My issue:
When I try to upload the sketch (even empty) it hangs forever, or some times it shows the same message shown when you unplug the device while uploading.
No device found on COM5
Failed uploading: uploading error: exit status 1

The serial monitor is unable to connect
Sketch uses 33108 bytes (12%) of program storage space. Maximum is
262144 bytes. Global variables use 3552 bytes (10%) of dynamic memory,
leaving 29216 bytes for local variables. Maximum is 32768 bytes.
No device found on COM5 Failed uploading: uploading error: exit status 1

Attempted resolution actions:
I tried to use the reset button, and short GRD with RST pins, but nothing helped.
I tried multiple USB ports, different PC, different cable.
For information about the device:
https://github.com/Makerfabs/Maduino-Zero-4G-LTE
https://wiki.makerfabs.com/Maduino_Zero_4G_LTE.html
Requests:
If you could guide me, maybe I can try to "factory reset" the MCU, or maybe try to connect in a different way.
I read about the bootloaders but I don't know how they work and I don't want to try alone and make worse.
The manufacturer didn't reply to my messages,on GitHub I didn't receive any reply either, so this is one last attempt before I throw this into the bin.
If anyone can recommend al alternative board with GPS and LTE/4G connectivity would be a plus.

windoz computer? Try turning it off then on again, then plug in the Arduino.

use double reset to activate the bootloader. the led should pulsate when bootloader waits for upload

@Juraj how do I do the double reset? I tried in different machines, with different cables, it is definitely the sketch I uploaded that broke it.

press the reset button twice?

As suggested by Juraj (thank you), pushing the reset button twice allowed me to upload an empty sketch and "revive" an otherwise unusable device.


text:
Leading Zeroes on Arduino Ethernet MAC Address
How can I pass the MAC address to Ethernet shield with leading zeroes?
I change the default MAC address from DEADBEEFFEED to something like DEADBEEFFE01. So I only change the last number from 0xED to 0x01. My board is communicating to a separate server and when I look at the MAC in that server, my board is listed as DEADBEEFFE1.
It's not as simple as printing the MAC address with padded zeroes as the board is actually removing it.
I've looked at the Ethernet library and I saw that the mac is passed as an array of uint8_t. I think that's why, the last number is read as 1 (which is correct) but passed as just that.
Is there a way for the MAC to pass leading zeroes?

0x01 is 1. the server prints it wrong

Yep, apparently, found out that it is the server that has a problem.

Writing this in case someone in the future might be interested.
The values passed in the Ethernet library is correct. The last value, 0x01 must be 1 and is written correctly, 0x01 in the registers of the W5500 inside the Ethernet shield.
Where I've got it wrong is how I pass the MAC address to the server. I'm basically creating a string for a json message. In there, I've put %02x to make sure that zeroes are padded.


text:
No Device Found On Bare-bones SAM3X Chip
0
I've been trying to make my own board with a SAM3X and W5500 (Arduino Ethernet Shield) on it with those two chips connected via SPI.
From the Arduino Due Board, most of the stuff, we don't need. So obviously, almost everything went off. Particularly, I remove the power switching circuits since we won't be varying power anyway. The native USB Programming also went off as well as the Programming port circuit.
I've only left headers so I can connect the 16U2 (with 16MHz crystal) circuit externally. Headers are VIN (5V from USB), RX (from a level shifter), TX and Ground. I'd not included the reset signal so from the 16U2 pin, I connected a 1kohm resistor (R23) to the reset line in my board.
The 16U2 I have externally is programmed with the new file in
https://github.com/arduino/ArduinoCore-sam/tree/master/firmwares/atmega16u2
When I connect the 16U2 circuit to my USB Port, I was able to see it as the programming port correctly. However, when I try uploading a sketch to the board (sample blink), the IDE says No Device Found on the COM port.
I've tried using bossac and modifying the COM port thru command prompt but I still get the same result.
I've checked the SAM3X checklist and it says there that for SAM-BA to boot, I only need to have the correct supplies and the 12 MHz Crystal Oscillator. I've checked everything using multitester and all the supplies are in the correct voltage. I've checked the crystal using an oscilloscope and I can see that it outputs the expected waveform.
I've also checked the TX and RX line from the 16U2. There are data being send by the 16U2 but the SAM3X is not responding.
One thing I notice is that the 32 kHz crystal is not working. But from what I've read in these forum, that is not powered by the SAM3X until the slow clock oscillator is enabled to be externally sourced.
The last thing I think that I've done different is that I'd connected the VBUS pin to the 3.3V supply rail where it was directly connected to the USB power. The reason I've done this is because I'm not using USB anyway.
Also, the data lines for the native USB, I've terminated them using 1MHz resistors to ground just so they're not left flaoting.
Are these (VBUS and datalines) causing my SAM3X to not reply and properly work so sketches can be uploaded? Would want to confirm VBUS first before destroying the trace in my board as I'm afraid I might fry the SAM3X chip with 5V.
Are there other things I've done wrong?

SAM3X doesn't have Ethernet as MCU peripheral?

It has. Just that in our development, we'd used W5500 and opt not to change that part.


text:
Arduino Due 16U2 Programming Port Documentation
Are there any documentation or whatsoever on what the 16U2 does when trying to program the Sam3X in Arduino Due?
I reallynwant to know what's wrong with my made up board but can't get pass the No Device Found problem.
Been searching it but I can't find any. I can't understand the hex file burned on the MCU.

did you upload the firmware to the ATmega 16u2? the firmware is in arduino/hardware/sam/1.6.11/firmwares/atmega16u2

https://www.arduino.cc/en/Hacking/Upgrading16U2Due

Yes, I'd already uploaded that firmware to the 16U2.

The 16u2 is merely acting as a usb to UART adapter. You can just as well use an ft232 or other serial adapter.
Of course the 16u2 needs firmware installing on it in order to function. That firmware is available (possibly bundled with the ide, or for download, not sure at the moment).

But I believe it is also responsible in asserting the reseta and erase pins that is needed for the SAMBA bootloader in the Sam3x and something about the CDC.

And you should have copied that from the due schematic, yes? And the firmware you install in the 16u2 does all that it needs to.

Yes. I've got everything (connections, voltage levels) of the pins in my board and due the same during power up but I'm still getting the No device found error. So I'm think that something I'd miss and I want to see it by looking at the code and what to expect on the pins using a scope.

If you're going to that sort of level then you really need a physical Due to compare it with.


text:
How to send multiple decoded IR signals in one script?
My final goal is to use my Arduino microcontroller as an "automatic remote". For now I would like to know how to send decoded NEC protocols one after another in a script.
I am using the Nano v3.0 with an IR LED I salvaged from an old remote. I used a VS838 and a 338R IR receiving module to decode the signals, both work 100%.
I know how to send one protocol in a loop.
e.g
#include <IRremote.h>

IRsend irsend;

void setup() {
}

void loop() {
    for (int i = 0; i < 2; i++) {
        irsend.sendNEC(0x10676897, 32);
        delay(40);
    }
    delay(5000); // 5-second delay between each signal burst
}

I also know how to send the same protocol repetitively.
(Although it won't work in the loop I reckon it'll work in the final script).
e.g
#include <IRremote.h>

IRsend irsend;

void setup() {
}

void loop() {
    for (int i = 0; i < 2; i++) {
        irsend.sendNEC(0xFFFFFFFF, 32);
        delay(40);
    }
    delay(5000); // 5-second delay between each signal burst
}

However, I would like to include 106722DD, 10676897 ,10678877 and send them in one single C++ script.
I was thinking something like calling each script through a loop might suffice but I have no idea how to do it in C++.
Any help will be appreciated.

I'm not 100% certain what you are asking, so sorry if there is superfluous info in here.
Given that:
void loop() {
    for (int i = 0; i < 2; i++) {
        irsend.sendNEC(0x10676897, 32);
        delay(40);
    }
    delay(5000); //5 second delay between each signal burst
}

Sends a single command twice as one burst I think what you want to do is this:
void loop() {
    for (int i = 0; i < 2; i++) {
        irsend.sendNEC(106722DD, 32);
        delay(40);
        irsend.sendNEC(10676897, 32);
        delay(40);
        irsend.sendNEC(10678877, 32);
        delay(40);
    }
    delay(5000); //5 second delay between each signal burst
}

If that works it could be generalised into:
// New function to send 'items' codes which are held in the array 'data'
void sendMulti (const uint8_t& items, const uint32_t* data)
{
    for (int i = 0; i < 2; i++)
    {
        for (uint8_t itemIndex = 0; itemIndex < items; ++itemIndex)
        {
            irsend.sendNEC(data[itemIndex], 32);
            delay(40);
        }
    }
    delay(5000); //5 second delay between each signal burst
}

void loop () {
    static const uint8_t MaxItems = 3;
    uint32_t  data[MaxItems] = {106722DD, 10676897, 10678877};

    sendMulti(MaxItems, data);
}

Then you could move onto reading the codes from serial or a network, etc.

Thanks it's working so far i'll post some updates as i progress.

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


text:
Reading and comparing data from Arduino Uno EEPROM
I'm trying to read compare data from EEPROM (Arduino UNO). Reading is working fine but comparing it using the '==' operator is not working as expected.
//string 'True' is already stored in EEPROM

int addr = 0;
char value = EEPROM.read(addr);

Serial.println(value);// this line successfully prints the letter 'T'

// but this function is not working
if (value == "T") {
  Serial.println("foo");
}

this has nothing to do with EEPROM ... this is a question about comparing strings

I have a problem like I that did you finally fix it. I will be glad if it worked.

There is a HUGE difference between "string" and 'c' 'h' 'a' 'r'.
You are comparing address of string "T" with the numerical value of character 'T'.
The expression: if (value == 'T') will be much better.

Thank you for the answer. How can I read and compare the first letter of the string stored at addr = 0; ?

@ShyamMohan  You have to use 'T' instead of "T" to compare value with...

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


text:
While doesn't the loop terminate?
I have a have project of Up Down counter using Arduino with seven segments, in which when I continuously press the push button, the counter moves upward from 0 to 99. When I release the push button, the counter moves downwards from the previous value.
For example: I continuously press the button counter from 0 to 58, then when I release the button, the counter moves backward from 58 to 0.
The problem is that when I simulate the code in Proteus software, the counter starts from 99 because the button is not pressed. But when I press the button the counter moves upward not accurately.
Also the other big issue is that when the button is released, the counter does not move backwards although the counter moves upwards continuously and the button is not working (whether the button is pressed or not).
Here my code and Proteus simulator circuit image.
int num_array_1[10][7] =
  { { 1,1,1,1,1,1,0 }, // 0
  { 0,1,1,0,0,0,0 }, // 1
  { 1,1,0,1,1,0,1 }, // 2
  { 1,1,1,1,0,0,1 }, // 3
  { 0,1,1,0,0,1,1 }, // 4
  { 1,0,1,1,0,1,1 }, // 5
  { 1,0,1,1,1,1,1 }, // 6
  { 1,1,1,0,0,0,0 }, // 7
  { 1,1,1,1,1,1,1 }, // 8
  { 1,1,1,0,0,1,1 }}; // 9
int num_array_2[10][7] =
  { { 1,1,1,1,1,1,0 }, // 0
  { 0,1,1,0,0,0,0 }, // 1
  { 1,1,0,1,1,0,1 }, // 2
  { 1,1,1,1,0,0,1 }, // 3
  { 0,1,1,0,0,1,1 }, // 4
  { 1,0,1,1,0,1,1 }, // 5
  { 1,0,1,1,1,1,1 }, // 6
  { 1,1,1,0,0,0,0 }, // 7
  { 1,1,1,1,1,1,1 }, // 8
  { 1,1,1,0,0,1,1 }}; // 9

const int button = 35;
const int alarm = 50;

//function header
void Num_Write_1(int);
void Num_Write_2(int);

void setup() {
  // set pin modes for Display 1
  pinMode(22, OUTPUT);
  pinMode(23, OUTPUT);
  pinMode(24, OUTPUT);
  pinMode(25, OUTPUT);
  pinMode(26, OUTPUT);
  pinMode(27, OUTPUT);
  pinMode(28, OUTPUT);
  // set pin modes for Display 2
  pinMode(40, OUTPUT);
  pinMode(41, OUTPUT);
  pinMode(42, OUTPUT);
  pinMode(43, OUTPUT);
  pinMode(44, OUTPUT);
  pinMode(45, OUTPUT);
  pinMode(46, OUTPUT);
  // set pin for alarm indication
  pinMode(alarm,OUTPUT);
  // set pin for button input
  pinMode(button,INPUT);
  int i = 1;
  int j = 1;
  int counter_1 = 0; // for counter 1
  int counter_2 = 0; // for counter 2
}

void loop() {
  int counter_1; // for counter 1
  int counter_2; // for counter 2
  int button_state = digitalRead(button);
  // check the button state
  //counter loop
  if (button_state == HIGH) {
    // if button is pressed , counter moves Upward(0,1,2,3,....,99)
    boolean start = true;
    while (start) {
      // when button pressed , loop is continuously running
      if (counter_1 == 10) {
        // if counter 1 is value 10
        counter_1 = 0; // reset counter1 to 0
        counter_2 = counter_2 + 1; // counter2 is starting now
        Num_Write_1(counter_1); // display value of counter1
        Num_Write_2(counter_2); // display value of counter2
        button_state = digitalRead(button); // check the button state
        if (button_state == LOW) {
          // if low then condition of while is false
          // button is released, button_state is low
          start = !start; // toggle the while condition true to false
          // which terminate the while loop
        }
      } else {
        counter_1 = counter_1 + 1; // incr. 1 by 1
        Num_Write_1(counter_1); // display value of counter1
        delay(200);
      }
      button_state = digitalRead(button);
      // again check the button state
      // button is released, button_state is low
      while (button_state == LOW) {
        // if low then condition of while is false
        start = !start;
      }
    }
  } else {
    //if button is release , counter moves Downward(56,55,54,...,0)
    Num_Write_1(counter_1); // show previous values on both counters
    Num_Write_2(counter_2); // b/c decr. starts from incremented values
    boolean start = true;
    while (start) {
      // when button release , loop is continuously running
      if (counter_1 == 0) {
        //if counter 1 is value 0
        counter_1 = 9; // reset counter1 to 9
        counter_2 = counter_2 - 1; // counter2 is starting now
        Num_Write_1(counter_1); // display on counter1
        Num_Write_2(counter_2); // display on counter2
        button_state = digitalRead(button); // check the button state
        if (button_state == HIGH) {
          // if high then condition of while is false
          // button is pressed, button_state is high
          start = !start; //toggle the condition
        }
      } else {
        counter_1 = counter_1 - 1; // decr. 1 by 1
        Num_Write_1(counter_1); // display on counter1
        delay(200);
      }
      button_state = digitalRead(button); // again check the button_state
      // if button pressed , button_state goes high
      if (button_state == HIGH) {
        start = !start;
        // toggle the while condition true to false
        // which terminate the while loop
      }
    }
  }
}
// this functions writes values to the sev seg pins for counter1
void Num_Write_1(int number) {
  int pin= 22;
  for (int j=0; j < 7; j++) {
    digitalWrite(pin, num_array_1[number][j]);
    pin++;
  }
}
// this functions writes values to the sev seg pins for counter2
void Num_Write_2(int number) {
  int pin= 40;
  for (int j=0; j < 7; j++) {
    digitalWrite(pin, num_array_2[number][j]);
    pin++;
  }
}

If button pressed ----------> logic goes HIGH
If button release ----------> logic goes LOW
Please resolve my problem. I have tried for 2 weeks solving this problem but still I'm stuck. Any little advice will be important for me.

Your next question should deal with managing switch bouncing.  You may get away without such extra code.  But you may also get some unexpected results.

I'd throw that code away and start over from scratch; it's overly verbose and needlessly repetitious, which may account for the kinds of errors you are seeing.
A few notes:
• The contents of num_array_1 look identical to those of num_array_2.  Ordinarily there is no need to have two copies of the same constant array, so get rid of one or the other.
• It doesn't make sense to use four different lengthy sections of code that do about the same trivial things, incrementing or decrementing a counter, displaying its value, and then doing some kind of switch check.  Instead, use one section of code that handles all the cases.  See example 1 below.
• In three of those four different sections of code just referred to, in effect you say
if (button_state == LOW) { start = !start; } and in one of them, you say
while (button_state == LOW) { start = !start; }.  That statement loops forever if encountered when button_state is LOW.
• int counter_1 and int counter_2 declared in setup() are not the same variables as the ones of the same name declared in loop().  If you want them to be the same, declare them at global scope before setup(), and don't declare them within either of setup() or loop().
•  As declared in loop(), counter_1 and _2 are automatic local variables, uninitialized and technically of undefined value.  See discussion in an answer to “local variable initialized to zero in C”  on stackoverflow.
• It doesn't make sense to use two different display-a-digit functions that do about the same thing.  Instead, use one function to handle both cases.  See example 2 below.
• You can save 126 bytes each of RAM and Flash by storing the ones and zeroes of num_array_1 or _2 packed into bytes.  See example 3 below.

Example 1:  First, declare int dir, which will be 1 when counting up, and -1 when counting down.  To change direction, say dir = -dir;.  To step the count, say:
count += dir;
if (dir<0)  dir = 0;
if (dir>99) dir = 99;
showDigit(count/10, 40); // Hi digit ports are 40...46
showDigit(count%10, 22); // Lo digit ports are 22...28

After stepping the counter and showing its digits, you can do your check some kind of switch thing, once in one place instead of spread out in four different places.  Note, you could (and should) create symbolic constants that stand for 40 and 22, via an enum like the following, and then use the symbols instead of hardcoded numbers in the showDigit() calls.
enum { hiDigitAt=40, loDigitAt=22};
...
showDigit(count/10, hiDigitAt);
showDigit(count%10, loDigitAt);

Example 2:  Your Num_Write_1() and _2 functions are identical except that one says int pin= 22; and the other int pin= 40;.  To combine them, you can add a parameter specifying the starting pin number:
void showDigit(byte value, byte basePin) {
  for (byte j=0; j < 7; ++j) {
    digitalWrite(basePin+j, num_array_1[value][j]);
}

Example 3:  Instead of using 14 bytes of RAM and 14 bytes of Flash for each entry in your digit-segments-pattern arrays, you can pack the seven ones and zeroes that represent one digit into a single byte.  For example, { 0,1,1,0,0,0,0 }, // 1 converts to 0b0110000, // 1.  Then use shifts to unpack the bits, as below.
byte digitPats[10] =
     { 0b1111110, 0b0110000, 0b1101101, 0b1111001, 0b0110011,
       0b1011011, 0b1011111, 0b1110000, 0b1111111, 0b1110011
     };
...
void showDigit(byte value, byte basePin) {
  byte pattern = digitPats[value], bitj;
  for (byte j=0; j < 7; ++j) {
    bitj = (pattern & 64)>>6;
    digitalWrite(basePin+j, bitj);
    pattern *= 2;  // Shift the pattern one bit left
}

Your counter variables only have scope within the methods they are declared in.  So initializing them in the setup() method will have no effect in other methods.
Instead, declare these variables as global or at least with "file" scope as you did with your array variables.