NodeMCU - enable UART1/2 on ESP32 - nodemcu

I've build firmware as described here: https://nodemcu.readthedocs.io/en/dev-esp32/build/
But I cannot get hardware UART 1 or 2 working. Is there any particular component that has to be enabled (and it's not enabled by default) in order to get it working?
here is my test code:
uart_id = 2
local function on_data(data)
print("IN: ", tostring(data))
end
local function on_error(data)
print("ERR: ", tostring(data))
end
local cnt = 0;
local function on_timer()
print(". "..cnt)
cnt = cnt + 1
uart.write(uart_id, "# " .. cnt .. "\n")
end
local tmrObj = tmr.create()
tmrObj:register(5000, tmr.ALARM_AUTO, on_timer)
tmrObj:start()
uart.setup(uart_id, 115200, 8, uart.PARITY_NONE, uart.STOPBITS_1, 1)
uart.on(uart_id, "data", '\r', on_data)
uart.on(uart_id, "error", on_error)
uart.setmode(uart_id, uart.MODE_UART)
uart.start(uart_id)

Firmware is OK, uart.setup was incorrect. PINs were missing, and for some reason default PINs did not work, this one is fine:
uart.setup(uart_id, 115200, 8, uart.PARITY_NONE, uart.STOPBITS_1, {rx = 16, tx = 17})

Related

How can I fix the Error of MSC Bootloader with ATxmega32a4?

I'm trying to upload a .hex file via Uart into an ATxmega32a4. I'm using BASCOM IDE and Programmed my MCU with the sample code which is available in sample folder of Bascom (I have attached my code). So I'm using MSC Bootloader Wizard in Bascom to upload my code but unfortunately it has error 6006. I increased timeout but the problem is not fixed.
I monitored serial port as you can find it in attachments.
Could anyone help?
'----------------------------------------------------------------
' (c) 1995-2020, MCS
' BootloaderXmega32A4.bas
' This sample demonstrates how you can write your own bootloader
' in BASCOM BASIC for the XMEGA
'-----------------------------------------------------------------
'The loader is supported from the IDE
$crystal = 29491200 ' xmega128 is running on 32 MHz
$regfile = "xm32a4def.dat"
$hwstack = 40
$swstack = 40
$framesize = 40
'first enabled the osc of your choice
''Config Osc = Disabled , 32mhzosc = Enabled 'internal 2 MHz and 32 MHz enabled
Config Osc = Enabled , 32mhzosc = Enabled , Extosc = Enabled
'configure the systemclock
''Config Sysclock = 32mhz , Prescalea = 1 , Prescalebc = 1_1 ' we will use 32 MHz and divide by 1 to end up with 32 MHz
Config Sysclock = External , Prescalea = 1 , Prescalebc = 1_1
$loader = &H4000 ' bootloader starts after the application
'this sample uses 38400 baud. To be able to use the Xplain which has a bootloader working at 9600 baud you need to use 9600 baud
''Config Com1 = 38400 , Mode = Asynchroneous , Parity = None , Stopbits = 1 , Databits = 8 ' use USART C0
'COM0-USARTC0, COM1-USARTC2, COM2-USARTD0. etc.
''Config Portc.3 = Output 'define TX as output
''Config Pinc.2 = Input
Config Com3 = 115200 , Mode = Asynchroneous , Parity = EVEN , Stopbits = 1 , Databits = 8
Open "COM3:" For Binary As #1
Config PortD.3 = Output 'define TX as output
Config PinD.2 = Input
Const Maxwordbit = 7 ' Z7 is maximum bit '
Const Maxword =(2 ^ Maxwordbit) * 2 '128
Const Maxwordshift = Maxwordbit + 1
Const Cdebug = 0 ' leave this to 0
'Dim the used variables
Dim Bstatus As Byte , Bretries As Byte , Bmincount As Byte , Bblock As Byte , Bblocklocal As Byte
Dim Bcsum1 As Byte , Bcsum2 As Byte , Buf(128) As Byte , Csum As Byte
Dim J As Byte , Spmcrval As Byte ' self program command byte value
Dim Z As Long 'this is the Z pointer word
Dim Vl As Byte , Vh As Byte ' these bytes are used for the data values
Dim Wrd As Word , Page As Word 'these vars contain the page and word address
Disable Interrupts 'we do not use ints
'We start with receiving a file. The PC must send this binary file
'some constants used in serial com
Const Nak = &H15
Const Ack = &H06
Const Can = &H18
$timeout = 300000 'we use a timeout
'When you get LOADER errors during the upload, increase the timeout value
'for example at 16 Mhz, use 200000
Bretries = 5 : Bmincount = 3 'we try 10 times and want to get 123 at least 3 times
Do
Bstatus = Waitkey(#1) 'wait for the loader to send a byte
If Bstatus = 123 Then 'did we received value 123 ?
If Bmincount > 0 Then
Decr Bmincount
Else
Print #1, Chr(bstatus);
Goto Loader ' yes so run bootloader
End If
Else 'we received some other data
If Bretries > 0 Then 'retries left?
Bmincount = 3
Decr Bretries
Else
Rampz = 0
Goto Proces_reset 'goto the normal reset vector at address 0
End If
End If
Loop
'this is the loader routine. It is a Xmodem-checksum reception routine
Loader:
Do
Bstatus = Waitkey(#1)
Loop Until Bstatus = 0
Spmcrval = &H20 : Gosub Do_spm ' erase all app pages
Bretries = 10 'number of retries
Do
Csum = 0 'checksum is 0 when we start
Bblocklocal = 1
Print #1, Chr(bstatus); ' firt time send a nack
Do
Bstatus = Waitkey(#1) 'wait for statuse byte
Select Case Bstatus
Case 1: ' start of heading, PC is ready to send
Csum = 1 'checksum is 1
Bblock = Waitkey(#1) : Csum = Csum + Bblock 'get block
Bcsum1 = Waitkey(#1) : Csum = Csum + Bcsum1 'get checksum first byte
For J = 1 To 128 'get 128 bytes
Buf(j) = Waitkey(#1) : Csum = Csum + Buf(j)
Next
Bcsum2 = Waitkey(#1) 'get second checksum byte
If Bblocklocal = Bblock Then 'are the blocks the same?
If Bcsum2 = Csum Then 'is the checksum the same?
Gosub Writepage 'yes go write the page
Print #1, Chr(bstatus); 'acknowledge
Incr Bblocklocal 'increase local block count
Else 'no match so send nak
Print #1, Chr(bstatus);
End If
Else
Print #1, Chr(bstatus); 'blocks do not match
End If
Case 4: ' end of transmission , file is transmitted
If Wrd > 0 Then 'if there was something left in the page
Wrd = 0 'Z pointer needs wrd to be 0
Spmcrval = &H24 : Gosub Do_spm 'write page
End If
Print #1, Chr(bstatus); ' send ack and ready
Waitms 20
Goto Proces_reset
Case &H18: ' PC aborts transmission
Goto Proces_reset ' ready
Case 123 : Exit Do 'was probably still in the buffer
Case 124 : Exit Do
Case Else
Exit Do ' no valid data
End Select
Loop
If Bretries > 0 Then 'attempte left?
Waitms 1000
Decr Bretries 'decrease attempts
Else
Goto Proces_reset 'reset chip
End If
Loop
'write one or more pages
Writepage:
For J = 1 To 128 Step 2 'we write 2 bytes into a page
Vl = Buf(j) : Vh = Buf(j + 1) 'get Low and High bytes
!lds r0, {vl} 'store them into r0 and r1 registers
!lds r1, {vh}
Spmcrval = &H23 : Gosub Do_spm 'write value into page at word address
Wrd = Wrd + 2 ' word address increases with 2 because LS bit of Z is not used
If Wrd = Maxword Then ' page is full
Wrd = 0 'Z pointer needs wrd to be 0
Spmcrval = &H24 : Gosub Do_spm 'write page
Page = Page + 1 'next page
End If
Next
Return
Do_spm:
Z = Page 'make equal to page
Shift Z , Left , Maxwordshift 'shift to proper place
Z = Z + Wrd 'add word
!lds r30,{Z}
!lds r31,{Z+1}
#if _romsize > 65536
!lds r24,{Z+2}
!sts rampz,r24 ' we need to set rampz also for the M128
#endif
Nvm_cmd = Spmcrval
Cpu_ccp = &H9D
!spm 'this is an asm instruction
Do_spm_busy:
!lds r23, NVM_STATUS
!sbrc r23,7 ;if busy bit is cleared skip next instruc tion
!rjmp do_spm_busy
Return
Proces_reset:
Rampz = 0
Goto _reset 'start at address 0

How to use the DIO SPI on ESP32 with espidf?

I'm trying to use the DIO SPI mode on the ESP32 with the espidf (version 4.4).
But I encountered problems.
I have a ram device (ref 23LC1024) than can be accessed with several modes (single, dual, quad).
The single mode works perfectly (can write and read back)
The dual mode creates problems.
Here is how I configure the SPI bus (same setup for single or dual mode)
memset(&config, 0, sizeof(spi_bus_config_t));
config.mosi_io_num = MOSI_PIN;
config.miso_io_num = MISO_PIN;
config.sclk_io_num = SCLK_PIN;
config.quadwp_io_num = -1; // -1 not used
config.quadhd_io_num = -1; // -1 not used
config.flags = SPICOMMON_BUSFLAG_DUAL | SPICOMMON_BUSFLAG_MASTER;
spi_bus_initialize(VSPI_HOST, &config, SPI_DMA_DISABLED); // 0 DMA not used
Now the setup for the device (same setup for single mode or dual):
spi_device_interface_config_t devcfg = {
.clock_speed_hz = freq,
.command_bits = 8,
.address_bits = 24,
.dummy_bits = 8,
.mode = 0, // SPI MODE 0
.flags = 0,
.spics_io_num = _cs,
.queue_size = 1,
.pre_cb = NULL,
.post_cb = NULL};
ESP_ERROR_CHECK(spi_bus_add_device(VSPI_HOST, &devcfg, &data_Ram));
Now the setup for the transaction:
spi_transaction_t t;
memset(&t, 0, sizeof(t)); // Zero out the transaction
t.cmd = WRITE;
t.tx_buffer = data;
t.rx_buffer = NULL;
t.addr = address;
t.length = size * 8;
if (USE_DIO) // configure these flags in case of DIO
t.flags = SPI_TRANS_MODE_DIO | SPI_TRANS_MULTILINE_ADDR | SPI_TRANS_MULTILINE_CMD;
ESP_ERROR_CHECK(spi_device_transmit(data_Ram, &t)); // Transmit!
It works nicely in the single mode but with the dual mode I got the error:
E (1618) spi_master: check_trans_valid(699): Incompatible when setting to both multi-line mode and half duplex mode
Does it mean I cannot use DIO in half duplex mode with the SPI master library?
Is there something I should change in my setup ?
I tried to specify the SPI_DEVICE_HALFDUPLEX flag in the spi_device_interface_config_t. Does not help.
Unfortunately I did not find any example on internet.
Thanks for your heads up!
E (1618) spi_master: check_trans_valid(699): Incompatible when setting to both multi-line mode and half duplex mode means that you cannot use MISO and MOSI for transfering (multiline) AND use them at the same time (full duplex).
Set your device to half duplex to fix the problem:
spi_device_interface_config_t devcfg = {
.flags = SPI_DEVICE_HALFDUPLEX,
...
};
In my experience, SPI_TRANS_MULTILINE_ADDR doesn't work, at least with spi_device_transmit.
If your ram device allows it, try without the "multilined" address and command.

Raspberry Pi 3 with wirpingpi - uart doesnt work

I want to communicate RPI3 with atmega8 via uart. In atmega I set 9600 baud rate, 8bits, no parity bit and one stop bit. I my rpi I'm using WiringPi library and this is my code:
int fd;
if ((fd = serialOpen ("/dev/ttyAMA0", 9600)) < 0)
{
cout << "Error";
return 1 ;
}
if (wiringPiSetup () == -1)
{
cout << "Error";
return 1 ;
}
serialPutchar (fd, 50) ;
But .. I atmega I don't receive this '50'. Maybe should I configure connection in termios ? Any Idea ?
When I try to use the code I receive a "2" in the ASCII table dec 50.
If you receive wrong data you might convert it first. If you don't receive data there might be a problem with the tty configuration or the hardware setup.

Low Power Mode on the TI MSP430

I am using the MSP430F2274 and trying to understand better the uses of Low Power mode.
In my program I am also using the SimplicTi API in order for two devices (one is the AP which is being connected by the other ,ED) to communicate.
AP - Access Point , which is also connected to a PC via the UART in order to recive a string from the user.
ED - End Device , simply connetes to the AP (with the SimplicTi protocol) and waits for messages form it.
I want to be sure I understand the low power mode uses , and to see how it "comes along" with the SimplicTi API.
The "flow" of the AP is as follows (after it is "linked" to the ED , see the code bellow):
#pragma vector = USCIAB0RX_VECTOR
__interrupt void USCI0RX_ISR(void)
{
// **A)** extract the "RXed" character (8 bits received from user) , use the while
// in order to be sure all the 8 bits are "desirialized" into a byte
while (!(IFG2 & UCA0RXIFG));
input_char = UCA0RXBUF; // input_char is global variable.
// **B)** if we received the "Enter" character , which indicates the
// end of the string
if(input_char == '\r' && input_count > 0)
{
TACCR0 = 10; // **F)**
TACTL = TASSEL_1 + MC_1; // ACLK, up mode
// **E)** Enter LPM3, interrupts enabled !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
__bis_SR_register(LPM3_bits + GIE);
}//end if Enter
// **C)** Any other char of the user's string when we
// have not got more than the maximum amount of bytes(chars)
else if (((FIRST_CHAR <= input_char && input_char <= LAST_CHAR) || ('a' <= input_char && input_char <= 'z')) && (input_count < INPUT_MAX_LENGTH))
{
input[input_count++] = input_char;
}
} //end of UART RX INTERRUPT
The TIMERA0 Interrupt Handler is the following code:
#pragma vector=TIMERA0_VECTOR
__interrupt void Timer_A(void)
{
if (i == strlen(morse)) // **D)** morse is a global array of chars who holds the string that we wish to send
{
SMPL_Send(sLID[0], (uint8_t*)EOT, 1); // EOT is the last char to send
TACTL = MC_0; //disable TimerA0
}
else if (!letterSpace)
{
char ch = morse[i++];
SMPL_Send(sLID[0], (char*)ch, 1);
switch(ch)
{
case '.':
{
TACCR0 = INTERVAL * 3;
letterSpace = 1;
break;
}
case '-':
{
TACCR0 = INTERVAL * 3 * 3;
letterSpace = 1;
break;
}
} // switch
} // else if
} //end TIMERA0 interrupt handler
The thing is like that:
I use the TIMERA0 handler in order to send each byte after a different amount of type , whether the char was transformed into a "-" or a "."
To do so I set the timer accordingly to a different value ( 3 times larger for "-").
Finnaly when I am done transmitting the whole string (D) , I disable the timer.
NOTE : The following method is performed at the begining of the AP code in order to configure the UART:
void UARTinit()
{
P3SEL = 0x30; // P3.4 and P3.5 as the UART TX/RX pins: P3SEL |= BIT4 + BIT5;
UCA0CTL1 |= UCSSEL_2; // SMCLK
// pre scale 1MHz/9600 =~ 104.
UCA0BR0 = 104;
UCA0BR1 = 0;
// 8-bit character and Modulation UCBRSx = 1
UCTL0 |= CHAR;
UCA0MCTL = UCBRS0;
UCA0CTL1 &= ~UCSWRST; // **Initialize USCI state machine**
IE2 |= UCA0RXIE; // Enable UART INPUT interrupt
} // end of UARTinit
So my questions are:
1) Just to be sure, in A) where I am "polling" the Rx buffer of the UART , is it necceary or is it just good practise for "any case" , cause AFAIK the UART handler gets called once the UART module recived the whole BYTE (as I configured it)?
2) In the main program of the AP , the last instruction is the one that "puts" it into LPM0 with interrupts enables : __bis_SR_register(LPM0_bits + GIE);
When for LPM0:
CPU is disable
ACLK and SMCLK remain active
MCLK is disabled
And for LPM3:
CPU is disable
MCLK and SMCLK are disabled
ACLK remains active
As I see it ,I can not enter LPM3 cause the AP needs the SMCLK clock not to be disable? (cause the UART uses it)
Is that correct?
3) In F) , is it a proper way to call the TIMERA0 handler ? I perfrom TACRR0 = 10 , cause it is a small value which the timer will reach "in no time" just so it will enter the TIMERA0 handler to perform the task of sending the bytes of the string.
4) For the "roll back" in the AP: As I see it , the "flow" is like that:
enters LPM0 (main) --> UART gets interrputed --> exit LPM0 and goes to the UART handler --> when it is done reciving the bytes (usually 5) it enters LPM3 --> the timer finishes counting to TACRR0 value (which is 10) --> the TIMERA0 handler gets called --> when the TIMERA0 handler done sending the last byte it disables the timer (TACTL0 = MC_0;) --> we "roll back" to the instruction which got us to LPM3 within the UART handler --> ??
Now , does ?? is "rolling back" to the instrcution which took us to LPM0 within the main program , OR do we "stay here" (in the instruction that entered us to LPM3 within the UART handler E) ?
If we do stay on E) , do I need to change it to LPM0 cause , again, the UART uses the SMCLK which is NOT active in LPM3 but indeed active in LPM0 ?
5) Any other comments will be super !!
Thanks allot,
Guy.
1) This will work
2) When you config this:
UCA0CTL1 |= UCSSEL_2; // SMCLK
This mean that UART used SMCLK, SMCLK will stop when you make MCU turn to LPM3;so that
UART will not work, you should config UART use ACLK, this will make UART work in LPM3 mode.
3) ...
4) ...
5) See 2
I hope this will help you

Write byte to Arduino from Ruby over serial

I'm trying to send an integer over the serial port to my Ardunio. The chip is then going to display the number in binary on the LED's. However I'm having lots of trouble trying to send the data as a byte over the serial port, as far as I can debug the following code sends it as the ASC char values.
Can anyone point me in the right direction or spot the mistake? I'd really appreciate it. I've been pulling my hair out over this for a long time.
Ruby
require 'rubygems'
require 'serialport' # use Kernel::require on windows, works better.
#params for serial port
port_str = "/dev/tty.usbserial-A700dZt3" #may be different for you
baud_rate = 9600
data_bits = 8
stop_bits = 1
parity = SerialPort::NONE
sp = SerialPort.new(port_str, baud_rate, data_bits, stop_bits, parity)
i = 15
#just write forever
while true do
sp.write(i.to_s(2))
sleep 10
end
Arduino
int ledPin = 10;
int ledPin1 = 11;
int ledPin2 = 12;
int ledPin3 = 13;
byte incomingByte; // for incoming serial data
void setup() {
pinMode(ledPin, OUTPUT); // initialize the LED pin as an output:
pinMode(ledPin1, OUTPUT); // initialize the LED pin as an output:
pinMode(ledPin2, OUTPUT); // initialize the LED pin as an output:
pinMode(ledPin3, OUTPUT); // initialize the LED pin as an output:
Serial.begin(9600);
Serial.println("I am online");
}
void loop() {
// send data only when you receive data:
if (Serial.available() > 0) {
incomingByte = Serial.read();
Serial.println(incomingByte, DEC);
int value = (incomingByte, DEC) % 16;
digitalWrite(ledPin, (value >> 0) % 2);
digitalWrite(ledPin1, (value >> 1) % 2);
digitalWrite(ledPin2, (value >> 2) % 2);
digitalWrite(ledPin3, (value >> 3) % 2); // MSB
}
}
I'm guessing you are trying to write the value 15 in order to light all the LEDs at once. However, 15.to_s(2) is "1111". The ASCII value of the character '1' is 49, so instead of writing 15 once you are writing 49 four times in rapid succession.
The write command you are looking for is therefore probably sp.putc(i). This writes only one character with the given binary value (= machine-readable for Arduino) instead of an ASCII string representation of the value expressed in binary (= human-readable for you).
So keeping everything else the same, replace the while loop in your Ruby code with:
loop do
sp.putc(i)
puts 'Wrote: %d = %bb' % [ i, i ]
i = (i == 15) ? 0 : (i + 1)
sleep(10)
end
If you wish to read the responses from Arduino, you can use e.g. sp.gets to get one line of text, e.g. try placing puts 'Arduino replied: ' + sp.gets in the loop before sleep (and one puts sp.gets before the loop to read the "I am online" sent when the connection is first established).
Edit: I just spotted another problem in your code, on the Arduino side: value = (incomingByte, DEC) % 16; always results in the value 10 because (incomingByte, DEC) has the value DEC (which is 10). You should use value = incomingByte % 16; instead. Or do away with value altogether and modify incomingByte itself, e.g. incomingByte %= 16;.
Your problems may be caused by buffering. To disable buffering, you can do one of the following:
Set sp to unbuffered after creating it (before writing): sp.sync = true
Call flush after the write
Use the unbuffered syswrite instead of write
It's been so long since I did anything with serial ports that I can't help there, but I do see one thing.
>> 15.to_s #=> "15"
and
>> 15.to_s(2) #=> "1111"
I think if you want the binary value to be sent you'll want "\xf" or "\u000F".
Change your code from:
while true do
sp.write(i.to_s(2)) # <-- this sends a multi-character ASCII representation of the "i" value, NOT the binary.
sleep 10
end
to:
while true do
sp.write(i.chr) # <-- this sends a single byte binary representation of the "i" value, NOT the ASCII.
sleep 10
end
To show the difference, here's the length of the strings being output:
>> 15.to_s(2).size #=> 4
>> 15.chr.size #=> 1
And the decimal values of the bytes comprising the strings:
>> 15.to_s(2).bytes.to_a #=> [49, 49, 49, 49]
>> 15.chr.bytes.to_a #=> [15]
I've had this Ruby code work before
while true do
printf("%c", sp.getc)
end
rather than using sp.write(i.to_s). It looks like you are explicitly converting it to a string, which may be the cause of your problems.
I found the original blog post I used:
http://www.arduino.cc/playground/Interfacing/Ruby

Resources