Loading [MathJax]/jax/input/TeX/config.js
前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >【教程】Digispark实现串口通信

【教程】Digispark实现串口通信

作者头像
小锋学长生活大爆炸
发布于 2025-05-31 07:48:23
发布于 2025-05-31 07:48:23
7400
代码可运行
举报
运行总次数:0
代码可运行

没想到这么老,很多代码都不能用,修了好久。。。

TinySoftwareSerial.cpp

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <inttypes.h>

#include "Arduino.h"
#include "wiring_private.h"

#if USE_SOFTWARE_SERIAL
#include "TinySoftwareSerial.h"

extern "C"{
uint8_t getch() {
  uint8_t ch = 0;
    __asm__ __volatile__ (
    "   rcall uartDelay\n"          // Get to 0.25 of start bit (our baud is too fast, so give room to correct)
    "1: rcall uartDelay\n"              // Wait 0.25 bit period
    "   rcall uartDelay\n"              // Wait 0.25 bit period
    "   rcall uartDelay\n"              // Wait 0.25 bit period
    "   rcall uartDelay\n"              // Wait 0.25 bit period
    "   clc\n"
    "   in r23,%[pin]\n"
    "   and r23, %[mask]\n"
    "   breq 2f\n"
    "   sec\n"
    "2: ror   %0\n"
    "   dec   %[count]\n"
    "   breq  3f\n"
    "   rjmp  1b\n"
    "3: rcall uartDelay\n"              // Wait 0.25 bit period
    "   rcall uartDelay\n"              // Wait 0.25 bit period
    :
      "=r" (ch)
    :
      "0" ((uint8_t)0),
      [count] "r" ((uint8_t)8),
      [pin] "I" (_SFR_IO_ADDR(ANALOG_COMP_PIN)),
      [mask] "r" (Serial._rxmask)
    :
      "r23",
      "r24",
      "r25"
    );
  return ch;
}

void uartDelay() {
  __asm__ __volatile__ (
    "mov r25,%[count]\n"
    "1:dec r25\n"
      "brne 1b\n"
      "ret\n"
    ::[count] "r" ((uint8_t)Serial._delayCount)
  );
}

#if !defined (ANALOG_COMP_vect) && defined(ANA_COMP_vect)
//rename the vector so we can use it.
  #define ANALOG_COMP_vect ANA_COMP_vect
#elif !defined (ANALOG_COMP_vect)
  #error Tiny Software Serial cannot find the Analog comparator interrupt vector!
#endif
ISR(ANALOG_COMP_vect){
  char ch = getch(); //read in the character softwarily - I know its not a word, but it sounded cool, so you know what: #define softwarily 1
  store_char(ch, Serial._rx_buffer);
  sbi(ACSR,ACI); //clear the flag.
}

}
soft_ring_buffer rx_buffer  =  { { 0 }, 0, 0 };

// Constructor 

TinySoftwareSerial::TinySoftwareSerial(soft_ring_buffer *rx_buffer, uint8_t txBit, uint8_t rxBit)
{
  _rx_buffer = rx_buffer;

  _rxmask = _BV(rxBit);
  _txmask = _BV(txBit);
  _txunmask = ~_txmask;

  _delayCount = 0;
}

// Public Methods //
void TinySoftwareSerial::setTxBit(uint8_t txbit)
{
  _txmask=_BV(txbit);
  _txunmask=~txbit;
}

void TinySoftwareSerial::begin(long baud)
{
  long tempDelay = (((F_CPU/baud)-39)/12);
  if ((tempDelay > 255) || (tempDelay <= 0)){
  end(); //Cannot start as it would screw up uartDelay().
  }
  _delayCount = (uint8_t)tempDelay;
  cbi(ACSR,ACIE);  //turn off the comparator interrupt to allow change of ACD
#ifdef ACBG
  sbi(ACSR,ACBG); //enable the internal bandgap reference - used instead of AIN0 to allow it to be used for TX.
#endif
  cbi(ACSR,ACD);  //turn on the comparator for RX
#ifdef ACIC
  cbi(ACSR,ACIC);  //prevent the comparator from affecting timer1 - just to be safe.
#endif
  sbi(ACSR,ACIS1);  //interrupt on rising edge (this means RX has gone from Mark state to Start bit state).
  sbi(ACSR,ACIS0);
  //Setup the pins in case someone messed with them.
  ANALOG_COMP_DDR &= ~_rxmask; //set RX to an input
  ANALOG_COMP_PORT |= _rxmask; //enable pullup on RX pin - to prevent accidental interrupt triggers.
  ANALOG_COMP_DDR |= _txmask; //set TX to an output.
  ANALOG_COMP_PORT |= _txmask; //set TX pin high
  sbi(ACSR,ACI); //clear the flag.
  sbi(ACSR,ACIE);  //turn on the comparator interrupt to allow us to use it for RX
#ifdef ACSRB
  ACSRB = 0; //Use AIN0 as +, AIN1 as -, no hysteresis - just like ones without this register.
#endif
}

void TinySoftwareSerial::end()
{
  sbi(ACSR,ACI); //clear the flag.
  cbi(ACSR,ACIE);  //turn off the comparator interrupt to allow change of ACD, and because it needs to be turned off now too!
#ifdef ACBG
  cbi(ACSR,ACBG); //disable the bandgap reference
#endif
  sbi(ACSR,ACD);  //turn off the comparator to save power
  _delayCount = 0;
  _rx_buffer->head = _rx_buffer->tail;
}

int TinySoftwareSerial::available(void)
{
  return (unsigned int)(SERIAL_BUFFER_SIZE + _rx_buffer->head - _rx_buffer->tail) % SERIAL_BUFFER_SIZE;
}

void store_char(unsigned char c, soft_ring_buffer *buffer)
{
  int i = (unsigned int)(buffer->head + 1) % SERIAL_BUFFER_SIZE;

  // if we should be storing the received character into the location
  // just before the tail (meaning that the head would advance to the
  // current location of the tail), we're about to overflow the buffer
  // and so we don't write the character or advance the head.
  if (i != buffer->tail) {
    buffer->buffer[buffer->head] = c;
    buffer->head = i;
  }
}

int TinySoftwareSerial::peek(void)
{
  if (_rx_buffer->head == _rx_buffer->tail) {
    return -1;
  } else {
    return _rx_buffer->buffer[_rx_buffer->tail];
  }
}

int TinySoftwareSerial::read(void)
{
  // if the head isn't ahead of the tail, we don't have any characters
  if (_rx_buffer->head == _rx_buffer->tail) {
    return -1;
  } else {
    unsigned char c = _rx_buffer->buffer[_rx_buffer->tail];
    _rx_buffer->tail = (unsigned int)(_rx_buffer->tail + 1) % SERIAL_BUFFER_SIZE;
    return c;
  }
}

size_t TinySoftwareSerial::write(uint8_t ch)
{
  uint8_t oldSREG = SREG;
  cli(); //Prevent interrupts from breaking the transmission. Note: TinySoftwareSerial is half duplex.
  //it can either receive or send, not both (because receiving requires an interrupt and would stall transmission
  __asm__ __volatile__ (
    "   com %[ch]             \n" // ones complement, carry set
    "   sec                   \n"
    "1: brcc 2f               \n"
    "   in r23,%[uartPort]    \n"
    "   and r23,%[uartUnmask] \n"
    "   out %[uartPort],r23   \n"
    "   rjmp 3f               \n"
    "2: in r23,%[uartPort]    \n"
    "   or r23,%[uartMask]    \n"
    "   out %[uartPort],r23   \n"
    "   nop                   \n"
    "3: rcall uartDelay       \n"
    "   rcall uartDelay       \n"
    "   rcall uartDelay       \n"
    "   rcall uartDelay       \n"
    "   lsr %[ch]             \n"
    "   dec %[count]          \n"
    "   brne 1b               \n"
    :
    :
      [ch] "r" (ch),
      [count] "r" ((uint8_t)10),
      [uartPort] "I" (_SFR_IO_ADDR(ANALOG_COMP_PORT)),
      [uartMask] "r" (_txmask),
      [uartUnmask] "r" (_txunmask)
    : "r23",
      "r24",
      "r25"
  );
  SREG = oldSREG;
  return 1;
}

void TinySoftwareSerial::flush()
{

}

TinySoftwareSerial::operator bool() {
  return true;
}

// Preinstantiate Objects //
#ifndef ANALOG_COMP_DDR
#error Please define ANALOG_COMP_DDR in the pins_arduino.h file!
#endif

#ifndef ANALOG_COMP_PORT
#error Please define ANALOG_COMP_PORT in the pins_arduino.h file!
#endif

#ifndef ANALOG_COMP_PIN
#error Please define ANALOG_COMP_PIN in the pins_arduino.h file!
#endif

#ifndef ANALOG_COMP_AIN0_BIT
#error Please define ANALOG_COMP_AIN0_BIT in the pins_arduino.h file!
#endif

#ifndef ANALOG_COMP_AIN1_BIT
#error Please define ANALOG_COMP_AIN1_BIT in the pins_arduino.h file!
#endif

TinySoftwareSerial Serial(&rx_buffer, ANALOG_COMP_AIN0_BIT, ANALOG_COMP_AIN1_BIT);

#endif // whole file

TinySoftwareSerial.h

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
#if USE_SOFTWARE_SERIAL
#ifndef TinySoftwareSerial_h
#define TinySoftwareSerial_h
#include <inttypes.h>
#include "Stream.h"

#if !defined(ACSR) && defined(ACSRA)
#define ACSR ACSRA
#endif

#if (RAMEND < 250)
  #define SERIAL_BUFFER_SIZE 8
#elif (RAMEND < 500)
  #define SERIAL_BUFFER_SIZE 16
#elif (RAMEND < 1000)
  #define SERIAL_BUFFER_SIZE 32
#else
  #define SERIAL_BUFFER_SIZE 128
#endif
struct soft_ring_buffer
{
  volatile unsigned char buffer[SERIAL_BUFFER_SIZE];
  volatile int head;
  volatile int tail;
};

extern "C"{
  void uartDelay() __attribute__ ((naked,used)); //used attribute needed to prevent LTO from throwing it out.
  uint8_t getch();
  void store_char(unsigned char c, soft_ring_buffer *buffer);
}

class TinySoftwareSerial : public Stream
{
  public: //should be private but needed by extern "C" {} functions.
  uint8_t _rxmask;
  uint8_t _txmask;
  uint8_t _txunmask;
  soft_ring_buffer *_rx_buffer;
  uint8_t _delayCount;
  public:
    TinySoftwareSerial(soft_ring_buffer *rx_buffer, uint8_t txBit, uint8_t rxBit);
    void begin(long);
    void setTxBit(uint8_t);
    void end();
    virtual int available(void);
    virtual int peek(void);
    virtual int read(void);
    virtual void flush(void);
    virtual size_t write(uint8_t);
    using Print::write; // pull in write(str) and write(buf, size) from Print
    operator bool();
};

#if (!defined(UBRRH) && !defined(UBRR0H)) || USE_SOFTWARE_SERIAL
  extern TinySoftwareSerial Serial;
#endif

//extern void putch(uint8_t);
#endif
#endif

pins_arduino.h

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
#ifndef Pins_Arduino_h
#define Pins_Arduino_h

#include <avr/pgmspace.h>

#include "core_build_options.h"

//WARNING, if using software, TX is on AIN0, RX is on AIN1. Comparator is favoured to use its interrupt for the RX pin.
#define USE_SOFTWARE_SERIAL           1
//Please define the port on which the analog comparator is found.
#define ANALOG_COMP_DDR               DDRB
#define ANALOG_COMP_PORT              PORTB
#define ANALOG_COMP_PIN               PINB
#define ANALOG_COMP_AIN0_BIT          0
#define ANALOG_COMP_AIN1_BIT          1



#if defined( __AVR_ATtinyX313__ )
#define PORT_A_ID 1
#define PORT_B_ID 2
#define PORT_D_ID 4
#endif

#if defined( __AVR_ATtinyX4__ )
#define PORT_A_ID 1
#define PORT_B_ID 2
#endif

#if defined( __AVR_ATtinyX5__ )
#define PORT_B_ID 1
#endif

#define NOT_A_PIN 0
#define NOT_A_PORT 0

#define NOT_ON_TIMER 0
#define TIMER0A 1
#define TIMER0B 2
#define TIMER1A 3
#define TIMER1B 4

//changed it to uint16_t to uint8_t
extern const uint8_t PROGMEM port_to_mode_PGM[];
extern const uint8_t PROGMEM port_to_input_PGM[];
extern const uint8_t PROGMEM port_to_output_PGM[];
extern const uint8_t PROGMEM port_to_pcmask_PGM[];

extern const uint8_t PROGMEM digital_pin_to_port_PGM[];
// extern const uint8_t PROGMEM digital_pin_to_bit_PGM[];
extern const uint8_t PROGMEM digital_pin_to_bit_mask_PGM[];
extern const uint8_t PROGMEM digital_pin_to_timer_PGM[];

// Get the bit location within the hardware port of the given virtual pin.
// This comes from the pins_*.c file for the active board configuration.
// 
// These perform slightly better as macros compared to inline functions
//
#define digitalPinToPort(P) ( pgm_read_byte( digital_pin_to_port_PGM + (P) ) )
#define digitalPinToBitMask(P) ( pgm_read_byte( digital_pin_to_bit_mask_PGM + (P) ) )
#define digitalPinToTimer(P) ( pgm_read_byte( digital_pin_to_timer_PGM + (P) ) )
#define analogInPinToBit(P) (P)
// in the following lines modified pgm_read_word in pgm_read_byte, word doesn't work on attiny45
#define portOutputRegister(P) ( (volatile uint8_t *)( pgm_read_byte( port_to_output_PGM + (P))) )
#define portInputRegister(P) ( (volatile uint8_t *)( pgm_read_byte( port_to_input_PGM + (P))) )
#define portModeRegister(P) ( (volatile uint8_t *)( pgm_read_byte( port_to_mode_PGM + (P))) )
#define portPcMaskRegister(P) ( (volatile uint8_t *)( pgm_read_byte( port_to_pcmask_PGM + (P))) )

#if defined(__AVR_ATtinyX5__)
#define digitalPinToPCICR(p)    (((p) >= 0 && (p) <= 5) ? (&GIMSK) : ((uint8_t *)NULL))
#define digitalPinToPCICRbit(p) (PCIE)
#define digitalPinToPCMSK(p)    (((p) >= 0 && (p) <= 5) ? (&PCMSK) : ((uint8_t *)NULL))
#define digitalPinToPCMSKbit(p) (p)
#endif

#if defined(__AVR_ATtinyX4__)
#define digitalPinToPCICR(p)    (((p) >= 0 && (p) <= 10) ? (&GIMSK) : ((uint8_t *)NULL))
#define digitalPinToPCICRbit(p) (((p) <= 2) ? PCIE1 : PCIE0)
#define digitalPinToPCMSK(p)    (((p) <= 2) ? (&PCMSK1) : (((p) <= 10) ? (&PCMSK0) : ((uint8_t *)NULL)))
#define digitalPinToPCMSKbit(p) (((p) <= 2) ? (p) : (10 - (p)))
#endif

#if defined(__AVR_ATtiny4313__)
#define digitalPinToPCX(p,s1,s2,s3,s4,s5) \
    (((p) >= 0) \
        ? (((p) <=  1) ? (s1)  /*  0 -  1  ==>  D0 - D1 */  \
        : (((p) <=  3) ? (s2)  /*  2 -  3  ==>  A1 - A0 */  \
        : (((p) <=  8) ? (s3)  /*  4 -  8  ==>  D2 - D6 */  \
        : (((p) <= 16) ? (s4)  /*  9 - 16  ==>  B0 - B7 */  \
        : (s5))))) \
        : (s5))
//                                                   s1 D     s2 A     s3 D     s4 B
#define digitalPinToPCICR(p)    digitalPinToPCX( p, &GIMSK,  &GIMSK,  &GIMSK,  &GIMSK,  NULL )
#define digitalPinToPCICRbit(p) digitalPinToPCX( p, PCIE2,   PCIE1,   PCIE2,   PCIE0,   0    )
#define digitalPinToPCMSK(p)    digitalPinToPCX( p, &PCMSK2, &PCMSK1, &PCMSK2, &PCMSK0, NULL )
#define digitalPinToPCMSKbit(p) digitalPinToPCX( p, p,       3-p,     p-2,     p-9,     0    )
#endif

#endif

实测效果

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2025-04-21,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
Arduino安装目录探秘.1
我们也可以看看这个ISP就是烧写AVR芯片进Bootloader,出现了这个Arduino.h的头文件.我们来研究一下(之后重点研究)
云深无际
2020/12/03
1.1K0
Arduino安装目录探秘.1
Tiny85哒哒哒
今天在盒子里面看见一个小玩意,一看是个开发板.好像是3块钱买的.一直也没有用过,看看怎么玩.看了半天主控发现是atmel家的玩意儿.
云深无际
2020/09/03
2.1K0
Tiny85哒哒哒
串口通信DMA中断
这是以前学32的时候写的,那时候学了32之后感觉32真是太强大了,比51强的没影。关于dma网上有许多的资料,亲们搜搜,这里只贴代码了,其实我也想详详细细地叙述一番,但是自己本身打字就慢,还有好多事情
杨奉武
2018/04/18
2K0
串口通信DMA中断
MIT 6.828 操作系统工程 Lab6: e1000 网络驱动程序
lab6 实际上并没有想象中那么难,代码量很少,主要是需要理解网卡外设的运作方式。
云微
2023/02/24
5970
MIT 6.828 操作系统工程 Lab6: e1000 网络驱动程序
在全志XR806开发板使用编码器进行调光
https://www.bilibili.com/video/BV1ou4y147Bg?t=6.7
阿志小管家
2024/02/02
1540
在全志XR806开发板使用编码器进行调光
ESP32与ROS调试笔记(Linux和Windows)
其实很简单,和esp8266类似,只用arduino自带的ros包即可,注意版本号0.7.8。
zhangrelay
2021/03/03
9490
TKM32F499评估板串口通信学习与实践笔记
我们在上面这篇文章已经领会了TKM32F499的强大了,接下来进入主题,串口通信实验。
杨源鑫
2020/05/21
1.9K0
【STM32H7教程】第30章 STM32H7的USART应用之八个串口FIFO实现
完整教程下载地址:http://forum.armfly.com/forum.php?mod=viewthread&tid=86980 第30章       STM32H7的USART应用之八个串口F
Simon223
2019/07/22
3.2K1
STM32通信串口RS232
RS232是美国电子工业协会(Electronic Industries Association,EIA)于1962年发布的串行通信接口标准,其中RS为英文“Recomend Standard”的缩写,中文翻译为“推荐标准”,232为标识号。该标准对串行通信的物理接口及逻辑电平都做了规定,其输出的电平称为RS232电平。
韦东山
2022/05/05
1.2K0
STM32通信串口RS232
STM32通信模拟SPI
SPI(Serial Peripheral Interface,串行外设接口)是由摩托罗拉(Motorola)在1980前后提出的一种全双工同步串行通信接口,它用于MCU与各种外围设备以串行方式进行通信以交换信息,通信速度最高可达25MHz以上。
韦东山
2022/05/09
1.5K0
STM32通信模拟SPI
用cube移植PS2手柄–HAL库[通俗易懂]
D0 input D1 output D2 output D3 output
全栈程序员站长
2022/08/14
1.4K0
用cube移植PS2手柄–HAL库[通俗易懂]
STM32开发项目:ADS1115的驱动与使用
ADS1115是具有 PGA、振荡器、电压基准、比较器的 16 位、860SPS、4 通道 Δ-Σ ADC,数据通过一个 I2C 兼容型串行接口进行传输。有关它的详细说明可以参考官方数据手册。
全栈程序员站长
2022/11/17
3.2K0
【STM32H7教程】第94章 STM32H7的SPI总线应用之双机通信(DMA方式)
完整教程下载地址:http://www.armbbs.cn/forum.php?mod=viewthread&tid=86980 第94章       STM32H7的SPI总线应用之双机通信(DMA
Simon223
2022/05/10
2K0
【STM32H7教程】第94章    STM32H7的SPI总线应用之双机通信(DMA方式)
VsCode设置ESP32工具链+刨根问底点灯
ESP-IDF扩展使您可以轻松开发,构建,刷新,监视和调试ESP-IDF代码,其中一些功能包括:
云深无际
2021/01/20
4K0
VsCode设置ESP32工具链+刨根问底点灯
基于单片机的煤气泄漏检测报警装置设计
煤气泄漏是一种常见的危险情况,可能导致火灾、爆炸和人员伤亡。为了及时发现煤气泄漏并采取相应的安全措施,设计了一种基于单片机的煤气泄漏检测报警装置。
DS小龙哥
2023/09/30
6050
基于单片机的煤气泄漏检测报警装置设计
【STM32H7教程】第66章 STM32H7的低功耗串口LPUART应用之串口FIFO和停机唤醒实现
完整教程下载地址:http://www.armbbs.cn/forum.php?mod=viewthread&tid=86980 第66章       STM32H7的低功耗串口LPUART应用之串口
Simon223
2020/03/08
2.1K0
M-Arch(雅特力M4)【AT-START-F425测评】No.06 驱动段码LCD
还是之前折腾GD32L233时弄的一块SLCD屏,改吧改吧就在AT32F425上跑起来了。
滚神大人
2022/06/09
6220
M-Arch(雅特力M4)【AT-START-F425测评】No.06 驱动段码LCD
【STM32】串口通信---用代码与芯片对话
文章目录 前言 一、串口通信基本知识 二、编程思路 usart.h usart.c main.c 宏定义 三、总结 前言 开发板:stm32f407VET6 开发环境:keil5 MDK 一、串口通信基本知识 【STM32】5分钟了解STM32的串口通信 二、编程思路 usart.h // ============================================= # @Time : 2020-09-03 # @Author : AXYZdong # @CSDN : http
AXYZdong
2020/11/05
8970
STM32通信模拟 I2C
I²C(Inter-Integrated Circuit),常读作“I方C”,它是一种多主从架构串行通信总线。在1980年由飞利浦公司设计,用于让主板、嵌入式系统或手机连接低速周边设备。如今在嵌入式领域是非常常见通信协议,常用于MPU/MCU与外部设备连接通信、数据传输。
韦东山
2022/05/09
1.1K0
STM32通信模拟 I2C
【玩转ESP32】12、esp32串口使用
ESP32芯片有三个UART控制器(UART0, UART1和UART2),其中UART0(GPIO3用于U0RXD,GPIO1用于U0TXD)用作下载、调试串口,引脚不可改变;
ManInRoad
2021/07/01
8.4K0
相关推荐
Arduino安装目录探秘.1
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验